Python 如何打破对用户的循环';收到有效输入后,是否选择?
如果用户没有选择1或2,我希望代码显示“请输入1或2以继续”,该部分正常工作。但是,如果用户输入“6”,它会询问“请输入1或2以继续”,但如果在无效输入之后直接输入有效输入,则代码不会正确显示 我曾尝试在没有需求函数的情况下实现这一点,但似乎没有任何东西能按我所希望的方式工作Python 如何打破对用户的循环';收到有效输入后,是否选择?,python,python-3.x,Python,Python 3.x,如果用户没有选择1或2,我希望代码显示“请输入1或2以继续”,该部分正常工作。但是,如果用户输入“6”,它会询问“请输入1或2以继续”,但如果在无效输入之后直接输入有效输入,则代码不会正确显示 我曾尝试在没有需求函数的情况下实现这一点,但似乎没有任何东西能按我所希望的方式工作 def requirement(): choice = "" while choice != "1" and choice != "2": choice = input ("Please e
def requirement():
choice = ""
while choice != "1" and choice != "2":
choice = input ("Please enter 1 or 2 to continue.\n")
if choice == "1" and choice == "2":
return choice
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
if play_again in "1":
print ("You win!")
elif play_again in "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
requirement()
intro()
else
语句已经考虑了是否输入了1或2,因此不需要使用requirement
函数 如果choice==“1”和choice==“2”:choice
永远不会同时等于1
和2
。无论哪种方式,当需求()
退出时,简介()
将退出。程序结束。可能的重复请不要在python程序中使用无端递归。
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
return play_again
def game(choice):
if choice == "1":
print ("You win!")
elif choice == "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
choice = input ("Please enter 1 or 2 to continue.\n")
game(choice)
game(intro())