0

我正在尝试运行这个程序,但由于某种原因,每当我输入 0 时,程序就会停止运行。我希望“您猜得太低,请再试一次”,因为输入小于生成的随机数。谁能帮忙解释一下?另外,请随时批评我的代码,以便我可以做得更好。非常感激。

# Generate random number for player to guess.
import random

number = random.randint(1, 3)
print(number)

# Ask player's name and have player guess the number.
welcomeUser = input("Hi, welcome to 'Guess a Number!'. Please tell us your name ")

userName = str(welcomeUser)
userGuess = int((input("Guess a number from 1 - 3 ")))

# Cycle through player's guesses until player enters correct number.
while userGuess:
    if userGuess > number:
        print("You've guess too high, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            break
    elif userGuess < number or userGuess == 0:
        print("You've guessed too low, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            break
    else:
        print("Congratulations " + userName + "! " + "You've guessed correctly! ")
        break
4

2 回答 2

3

0是错误的,即它False在布尔表达式中求值。因此,while循环以

while userGuess:

userGuess如果是将被跳过0。看起来您不需要检查循环中的任何条件,因此将其更改为

while True:

应该足够了。顺便说一句,Process finished with exit code 0只是意味着程序退出没有任何错误。

于 2019-02-03T00:16:19.570 回答
1

在 python 0 中等于“假”。因此,当您输入“0”时,userGuess 变为 false,while 循环终止。最好引入一个新变量:

continueProgram = True
while continueProgram :
    if userGuess > number:
        print("You've guess too high, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            continueProgram = False
    elif userGuess < number or userGuess == 0:
        print("You've guessed too low, please try again ")
        userGuess = int(input("Guess a number from 1 - 3 "))
        if userGuess == number:
            print("Congratulations! You've guessed correctly! ")
            continueProgram = False
    else:
        print("Congratulations " + userName + "! " + "You've guessed correctly! ")
        continueProgram = False
于 2019-02-03T00:20:07.473 回答