发布于2019-08-07 18:22 阅读(867) 评论(0) 点赞(4) 收藏(5)
Python中可以通过while和for循环来限制猜测年龄的次数
1. 在猜测年龄的小程序中,不加循环的代码是这样的:
age_of_yu = 23
guess_age = int(input("guess_age:"))
if guess_age == age_of_yu:
print("you got it!")
elif guess_age > age_of_yu:
print("think smaller...")
else:
print("think bigger...")
# 这里的 int(input("guess_age:")) 是将变量定义的默认数据类型(str)强制转换成 int 类型,从而可以进行 if 的条件比较
2. 通过for循环限制猜测年龄的次数为3次
age_of_yu = 23
for i in range(3):
guess_age = int(input("guess_age:"))
if guess_age == age_of_yu:
print("you got it!")
break
elif guess_age > age_of_yu:
print("think smaller...")
else:
print("think bigger...")
else:
print("you have tried too many times!")
3. 通过 while 循环限制猜测年龄的次数为3次
age_of_yu = 23
count = 0
while count < 3:
guess_age = int(input("guess_age:"))
if guess_age == age_of_yu:
print("you got it!")
break
elif guess_age > age_of_yu:
print("think smaller...")
else:
print("think bigger...")
count += 1
else:
print("you have tried too many times!")
4. 猜测年龄,要求猜到三次询问是否还要继续猜测,如果输入"n"则表示继续猜,否则表示不继续
age_of_yu = 23
count = 0
while count < 3:
guess_age = int(input("guess_age:"))
if guess_age == age_of_yu:
print("you got it!")
break
elif guess_age > age_of_yu:
print("think smaller...")
else:
print("think bigger...")
count += 1
if count == 3:
continue_guess = input("Do you want to go on guessing ?(输入n结束,输入其他任意键继续...)")
if continue_guess != 'n':
count = 0
else:
print("guessing end...")
作者:急流勇退
链接:https://www.pythonheidong.com/blog/article/12053/6192575784a72a043301/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!