【问题标题】:Control flow - Jump to another loop?控制流 - 跳转到另一个循环?
【发布时间】:2021-11-04 13:49:26
【问题描述】:

我没有找到这个问题的任何重复项,我知道 Python 本身没有“goto”功能以及如何在循环中使用“继续”来获得相同的效果,但我不是真的确定是否有任何推荐的“跳回”到另一个循环的方法,例如?下面我给大家举个例子

while True:
    print("Hey! Some text.. blablah")
    x = input("You wanna continue? (yes/no) ")
    if x == "yes":
        continue
    else:
        print("End of loop")
        break
        
while True:
    print("Hey! Some more text, blablah even more")
    x = input("You wanna continue? (yes/no): ")
    if x == "yes":
        continue
    elif x == "no":
        print("End of program")
        break
    else:
        pass
        # Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no" 

我现在唯一能想到的有意义的事情(不必简单地再次重写整个事情)就是简单地将第一个循环设置为一个函数并从第二个循环调用它以获得结果 i想要,这就像我想要的那样工作:

def firstloop():
    while True:
        print("Hey! Some text.. blablah")
        x = input("You wanna continue? (yes/no) ")
        if x == "yes":
            continue
        else:
            print("End of loop")
            break
            
firstloop()
        
while True:
    print("Hey! Some more text, blablah even more")
    x = input("You wanna continue? (yes/no): ")
    if x == "yes":
        continue
    elif x == "no":
        print("End of program")
        break
    else:
        firstloop()

但不知何故,我觉得我把事情复杂化了,或者这是我可以通过这样的事情去做的“最好”的方式?谢谢

【问题讨论】:

  • 说到“回来”运行sn-p代码,我见过的唯一方法就是使用函数
  • 回答yesno以外的东西不应该是错误吗?为什么会回到firstloop()
  • 是的,抱歉,这可能是一个不好的例子,但这只是一个示例来说明我的意思,问题的重点是循环之间的“返回”。但在一个真正的程序中,我当然会使用其他触发器而不是任何随机输入:)
  • 一般来说,如果你想回到某个东西,把它放在一个循环中。您将拥有一个包含您想要返回的代码的循环。

标签: python while-loop goto


【解决方案1】:

您应该将第二个循环放在第一个循环内(或者两个循环都放在一个封闭的 while 内)。永远不需要 GOTO,请参见此处:https://en.wikipedia.org/wiki/Structured_programming

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多