[英]How to break loop to user's choice once valid input is received?
If the user does not select 1 or 2, I want the code to say "Please enter 1 or 2 to continue", that part works.如果用户没有选择 1 或 2,我希望代码说“请输入 1 或 2 以继续”,该部分有效。 However if user inputs "6" it asks "Please enter 1 or 2 to continue" as it should but if a valid input is entered directly after an invalid input, code does not display correctly.但是,如果用户输入“6”,它会询问“请输入 1 或 2 以继续”,但如果在无效输入后直接输入有效输入,则代码无法正确显示。
I've tried to do this without the requirement function but nothing seems to work how I want it to.我试图在没有需求功能的情况下做到这一点,但似乎没有任何我想要的方式工作。
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()
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())
The else
statement already takes care of whether or not a 1 or 2 is input, so there is no need for the requirement
function. else
语句已经处理了是否输入 1 或 2,因此不需要requirement
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.