美文网首页互联网科技
Python 学习:通过while循环和for循环猜测年龄

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

作者: 919b0c54458f | 来源:发表于2019-03-01 21:32 被阅读13次

    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...")
    

    相关文章

      网友评论

        本文标题:Python 学习:通过while循环和for循环猜测年龄

        本文链接:https://www.haomeiwen.com/subject/lxnjuqtx.html