如何让 python "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语句通常用于非常低级的语言,如汇编语言或basic语言。在像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")

您可以通过while循环而不是goto来实现这一点,如下所示:

print ("You wake up.")
print ("You do what?")
while True:
    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?")
        break
    else:
        print ("I dont understand")

发生的是while将永远循环,但在现实中,一旦我们得到我们喜欢的输入,我们将break退出它。这就解决了你的问题。

goto永远不应该出现在你的代码中。几乎总有一种方法可以重构你的程序,这样它就可以在没有goto的情况下工作,并且它可能会更好地工作。

最新更新