【问题标题】:Python Loop - Valid InputPython 循环 - 有效输入
【发布时间】:2019-10-18 12:54:27
【问题描述】:
所以我在代码开头询问用户是否想玩时遇到了一些问题。如果用户输入无效响应,我如何让它重播循环?
以下是我目前所拥有的,但我不知道从哪里开始
play = input('Would you like to play the Guess the Number Game [y|n]?')
while play == 'y':
play = True
if play == 'n':
print ("No worries... another time perhaps... :)")
exit()
else:
print ("Please enter either 'y' or 'n'.")
【问题讨论】:
标签:
python
loops
if-statement
while-loop
numbers
【解决方案1】:
这也可以通过递归来完成:
def user_input():
play = input('Would you like to play the Guess the Number Game [y|n]?')
if play == 'y':
print("Play Starting...")
return True
elif play == 'n':
print("No worries... another time perhaps... :)")
return False
else:
user_input()
user_input()
【解决方案2】:
定义一个用于请求用户输入的递归函数,当输入无效时调用自身。
def playFunction():
play = input('Would you like to play the Guess the Number Game [y|n]?')
if play == 'y':
play = True
if play == 'n':
play = False
print ("No worries... another time perhaps... :)")
return
else:
print ("Please enter either 'y' or 'n'.")
playFunction()
【解决方案3】:
我想这就是你想要的:
break_condition = True
while break_condition:
play = input('Would you like to play the Guess the Number Game [y|n]?')
if play == 'y':
play = True
break_condition = False
elif play == 'n':
print ("No worries... another time perhaps... :)")
break_condition = False
else:
print ("Please enter either 'y' or 'n'.")
【解决方案4】:
while True:
play = input('Would you like to play the Guess the Number Game [y|n]?').lower()
if play == 'n':
print ("No worries... another time perhaps... :)")
break
elif play == 'y':
#write your game code here
else:
print ("Please enter either 'y' or 'n'.")