python - 如何使 python "goto"成为前一行以获得更多输入?

标签 python if-statement goto

所以我知道 goto 是一种非常糟糕的编码形式,但是当控制台中的输入不正确时,我需要一个程序返回到上一行。

print ("You wake up.")
print ("You do what?")
seg1 = input()
if seg1 == ("Stand") or seg1 == ("stand") or seg1 == ("stand up") or seg1 == ("Stand up") or seg1 == ("Stand Up"):
    print ("You get up")
    print ("You look around you... your in a dark room. A door hangs slightly ajar infront of you.")
    print ("You do what?")
else:
    print ("I dont understand")

在 else 语句运行后,我希望它重复第 2 行并从那里继续执行程序...我该怎么做?

最佳答案

Goto 语句通常用于非常低级的语言,例如汇编语言或基本语言。在像 python 这样的高级语言中,它们被抽象出来,所以它们不存在。您想要执行此操作的方法是使用循环(这是 goto 语句的抽象)。这可以通过以下代码实现。

valid_input = False
while not valid_input:
    print ("You wake up.")
    print ("You do what?")
    seg1 = input()
    if seg1 == ("Stand") or seg1 == ("stand") or seg1 == ("stand up") or seg1 == ("Stand up") or seg1 == ("Stand Up"):
       print ("You get up")
       print ("You look around you... your in a dark room. A door hangs slightly ajar infront of you.")
       print ("You do what?")
       valid_input = True
   else:
       print ("I dont understand")

关于python - 如何使 python "goto"成为前一行以获得更多输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25457923/

相关文章:

python - if else 检查 Python 中的每个条件,即使一个条件的计算结果为真

bash - 如何使用 bash 脚本解压目录中的每种类型的 tar 文件?

recursion - Erlang 的递归函数不只是一个 goto 吗?

c - 在函数结束时跳转到清理时 GOTO 是否被认为是无害的?

javascript - 这组 IF 语句有更好的写法吗?

linux - Bash - 创建 'goto' 等价物的问题

python - 由于tensorflow的Python代码中的语法错误而无法完成此问题?

Python - Pandas 将所有其他列的列和统计度量分组为新列

python - 无效的表达式 sre_constants.error : nothing to repeat

python - 使用python,绑定(bind)在pyside QListWidgets中显示对象列表?