我正在尝试运行该程序,但是由于某种原因,每当输入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
答案 0 :(得分:3)
0
是错误的,即它在布尔表达式中的值为False
。因此,while
循环从
while userGuess:
如果userGuess
为0
,将跳过。看起来您不需要检查循环中的任何条件,因此将其更改为
while True:
就足够了。顺便说一句,Process finished with exit code 0
仅表示程序已退出,没有任何错误。
答案 1 :(得分:1)
等于“ false”。因此,当您输入“ 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