val=input("请输入带温度表示符号的温度值(例如32C/200f):") if val[-1] in ['C','c']: f=1.8*float(val[0:-1])+32 print("转换吼的温度为:%。2fF"%f); elif val[-1] in ['F','f']: c=(float(val[0:-1]-32))/1.8 print("转换后的温度为:%。2fC"%c) else: print("输入错误")
字符串
格式:[N:M]表示从N到M(不包含M)的子字符串,即左闭右开区间
格式框架
缩进
单层缩进
1 2 3 4 5 6 7
if <条件1>: <语句块1> elif<条件2>: <语句块2> ... else: <语句块N>
多层缩进
1 2 3
for <>: if<>: <>
注释
Python有两种注释方法:
单行注释以#开头
多行注释 ‘’‘ ’‘’(三个单引号j将注释括起来)or “”” “””(三个双引号将注释括起来)
命名与保留字
变量名首字符不能是数字!中间不能出现空格!
Python的33个保留字(关键字):arrow_down:
False
def
if
raise
None
del
import
return
True
elif
in
try
and
else
is
while
as
except
lambda
with
assert
finally
nonlocal
yield
break
for
not
class
from
or
continue
global
pass
赋值语句
“=”表示赋值
1 2 3 4
#单一赋值 x=y #同步赋值 x,y=y,x
分支语句
根据判断条件选择程序执行路径
1 2 3 4 5 6 7
if <条件1>: <语句块1> elif<条件2>: <语句块2> ... else: <语句块N>
TempStr =input("请输入符号:") x=eval(input("请输入温度的数值:")) if TempStr in ['F','f']: C = (x - 32) / 1.8 print("华氏温度{}转换为摄氏度温度是:{:.0f}C".format(TempStr,C)) elif TempStr in ['C','c']: F = x*1.8 + 32 print("摄氏温度{}转换为华氏温度是:{:.0f}F".format(TempStr,F)) else: print("输入格式错误")
汇率兑换程序
1 2 3 4 5 6 7 8 9 10
x=input("请输入金钱种类(美元:D or d;人民币:R or d):") money=eval(input("请输入金额;")) if x in ['D','d']: money=6*money print("换算为人民币:{:.2f}".format(money)) elif x in ['R','r']: money=money/6 print("换算为美元:{:.2f}".format(money)) else: print("输入格式错误")