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.')
知识点:
- 在python中,缩进是严格明确的,它表达程序的格式框架,是语法的一部分。缩进不正确,程序可能运行错误。缩进表达所属关系,是表达代码间包含和层次关系的唯一手段。程序内缩进长度一致,一般为4个空格或1个TAB。
- print() 函数输入的结果为字符串
- eval() 函数将括号内字符串转化为数字
- 对于字符串而言,下标规则为:
从左到右,0到正无穷
从右向左,-1到负无穷 - 对于字符串而言, str[a:b] 表示对str取下标a到b-1
- print() 如果要输出变量,需要使用
print(‘{ }’.format(变量名)),
如果需要对变量值进行格式化,可以将{}变为
{:.2f}(表示保留2位小数)、{:.2d} 等,对应过去C语言中的%2f、%2d等 - if-elif-else循环、需要冒号,不需要end



