如何使python“goto”成为前一行以获取更多输入?

2024-06-02 09:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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行并从那里继续执行程序。。。我该怎么做?


Tags: ortoyougo编码dowhatelse
2条回答

Goto语句通常用于非常低级的语言,如assembly或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的情况下工作,结果可能会更好。

相关问题 更多 >