栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python学习(1):温度转换实例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python学习(1):温度转换实例

Python学习(1):温度转换实例
TempStr=input('Please input the value of temperature with notation:')
if TempStr[-1] in ['F','f']:
    #consider notation with upper or lower letter
    C=(eval(TempStr[0:-1])-32)/1.8
    #eval() function change strings to numbers
    #[a:b] means from index a to b-1. 
    #from left to right, index is from 0 to infinity. from right to left, index is from -1 to negative infinity.
    print('The converted temperature is {:.2f}C.'.format(C))
    #this is a format for printing value of variable C with its format 2f. 
    #{:.2f} means keeping 2 decimal places.
elif TempStr[-1] in ['C','c']:
    F=1.8*eval(TempStr[0:-1])+32
    print('Ten converted temperature is {:.2f}F.'.format(F))
else:
    print('The format of input is wrong.')

知识点:

  1. 在python中,缩进是严格明确的,它表达程序的格式框架,是语法的一部分。缩进不正确,程序可能运行错误。缩进表达所属关系,是表达代码间包含和层次关系的唯一手段。程序内缩进长度一致,一般为4个空格或1个TAB。
  2. print() 函数输入的结果为字符串
  3. eval() 函数将括号内字符串转化为数字
  4. 对于字符串而言,下标规则为:
    从左到右,0到正无穷
    从右向左,-1到负无穷
  5. 对于字符串而言, str[a:b] 表示对str取下标a到b-1
  6. print() 如果要输出变量,需要使用
    print(‘{ }’.format(变量名)),
    如果需要对变量值进行格式化,可以将{}变为
    {:.2f}(表示保留2位小数)、{:.2d} 等,对应过去C语言中的%2f、%2d等
  7. if-elif-else循环、需要冒号,不需要end
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号