有没有办法限制while循环或输入循环的数量?

时间:2017-02-10 22:48:47

标签: python

我只是想知道是否有办法限制用户在while循环中输入内容的次数。这只是一个1-100游戏的猜测。我找到了变量= False。

while not found:
    user_guess = int(input("Your guess: "))
    if user_guess == random_number:
        print("you got it!")
        found = True
    elif user_guess > random_number:
        print("Guess lower")
    else:
        print("guess higher")

我想看看我是否可以通过限制用户猜测输入的数量来使这个代码看起来更像游戏。我有一些想法,我无法绕过它。我是否为输入设置了一个变量值来设置它可以运行的次数?我是编程新手,所以我有点挣扎。

2 个答案:

答案 0 :(得分:2)

count = 0
max_guesses_allowed = pick your max here

while not found or count < max_guesses_allowed:
    user_guess = int(input("Your guess: "))
    if user_guess == random_number:
        print("you got it!")
        found = True
    elif user_guess > random_number:
        count += 1
        print("Guess lower")

    else:
        count += 1
        print("guess higher")

答案 1 :(得分:0)

标准方法是计算循环次数,然后在超过最大值时退出。

max_allowed = 10
attempt = 0

while not found:
    attempt += 1
    user_guess = int(input("Your guess: "))
    if user_guess == random_number:
        print("you got it!")
        found = True
    elif attempt == max_allowed:
        print("You've reached the maximum number of guesses.")
        break
    elif user_guess > random_number:
        print("Guess lower")
    else:
        print("guess higher")