Sample One:猜年龄小游戏,要求如下:
1.允许用户最多尝试三次
2.每尝试三次后,如果还没猜对 ,就问用户是退出还想继续玩,如果回答Y或y,就让其再猜三次,以此往复,如果回答N或n,就退出程序。
3.如果猜对了,就直接退出。
times=0
Age=int(10)
while times<=3:
Guess_Age=int(input("请输入您要猜的年龄大小:"))
if Guess_Age==Age:
print("猜对了,游戏结束咯!")
break
elif Guess_Age<=Age:
print("猜小啦!")
elif Guess_Age>=Age:
print("猜大了!")
pass
times+=1
if times==3:
temp=str(input("是否继续猜,是就请输入Y或者y,不继续就请输入N或者n:"))
if temp==str('Y') or temp==str('y'):
times=0
pass
elif temp==str('N') or temp==str('n'):
print("游戏结束啦!")
times=4
break
else:
print("请正确输入Y/y或者N/n")
Sample Two:小王身高1,75,体重80.5kg。请根据IBM公式(体重除以身高的平方)帮小王计算他的IBM指数,并根据BMI指数:
低于18.5 过轻
18.5-25 正常
25-28 过重
28-32 肥胖
高于32 严重肥胖
用if-elif判断并打印出结果
xw_weight=80.5
xw_height=1.75
IBM=float(xw_weight/(xw_height**2))
if IBM<=18:
print('过轻')
pass
elif IBM>18.5 and IBM<=25:
print('正常')
pass
elif IBM>25 and IBM<=28:
print('过重')
pass
elif IBM>28 and IBM<=32:
print('肥胖')
pass
else:
print("严重肥胖")
注意:break 在于中断本层循环,执行外层循环或者继续执行下面飞循环内的代码指令