我试图找到一种方法来防止“播放器”,或用户输入,进入我的游戏非整数的答案。我发现了一个速战速决,但它不会做我想要什么(代码休息,如果用户输入一个非整数的答案),它似乎打破代码的其余部分。我希望用户能够重复尝试(while循环?)并遍历整个代码。感谢您的帮助。
# 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 = input("Guess a number from 1 - 3 ")
# Cycle through player's guesses until player enters correct number.
while True:
if userGuess != userGuess.isdigit():
input("Sorry you broke the code for entering a non-numeric value")
break
elif int(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 int(userGuess) < number:
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