我正在为一个学校项目做一个问答游戏,我想做的是当用户输入一个无效的命令时,它会返回并尝试再次进入该菜单并调出完全相同的输入框和再次尝试代码。我将在我希望发生这种情况的地方发布一个部分。
#---->TO HERE
if userinput == str("help"):
print ("This is the help menu")
print ("This is how you play")
else:
print ("Invalid Command")
#This is where I want the user to go back and try entering a command again to get the same code to run through again.
#FROM HERE <----
最佳答案
while True:
userinput = input()
if userinput == 'help':
print('This is the help menu')
print('This is how you play')
break
else:
print('Invalid command')
while
循环用于此类情况。 break
语句允许您“中断”while
或for
循环。 while True
循环将永远循环下去,除非遇到 break
语句。
还有一个continue
语句允许您跳过循环的其余部分并返回到开头,但这里没有必要使用它。
参见 the docs进一步阅读。
关于python - 如果用户尝试了一个选项,但选项不正确,则返回到某个点并重试 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300321/