程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(2)

【Python 学习】通过while循环和for循环猜测年龄

发布于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黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)