python - 如果用户尝试了一个选项,但选项不正确,则返回到某个点并重试 - Python

标签 python python-3.x

我正在为一个学校项目做一个问答游戏,我想做的是当用户输入一个无效的命令时,它会返回并尝试再次进入该菜单并调出完全相同的输入框和再次尝试代码。我将在我希望发生这种情况的地方发布一个部分。

#---->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 语句允许您“中断”whilefor 循环。 while True 循环将永远循环下去,除非遇到 break 语句。

还有一个continue 语句允许您跳过循环的其余部分并返回到开头,但这里没有必要使用它。

参见 the docs进一步阅读。

关于python - 如果用户尝试了一个选项,但选项不正确,则返回到某个点并重试 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300321/

相关文章:

python - 有没有办法在 PIL 中指定矩形的宽度?

python - App Engine 数据存储区了解 noSql

python - mypy: "__eq__"与父类(super class)型 "object"不兼容

python - 获取列表中所有元素的增量计数

python - += : 'NoneType' and 'list' 不受支持的操作数类型

python - 使用代数约束和边界最小化最小二乘法

python - 在 Bokeh 中使用适当的上标格式化日志轴标签

python - 比较 int 值

python - Python 中改进的负二项式 GLM

python - 如何从不同的子模块导入一个子模块?