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

2019-03-01 10:13:39来源:博客园 阅读 ()

新老客户大回馈,云服务器低至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.cnblogs.com/yuzs122/p/10455302.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python学习笔记一:基本数据类型

下一篇:13-函数的基本使用