【问题标题】:Is there a way to break out of two while loops? [duplicate]有没有办法打破两个while循环? [复制]
【发布时间】:2020-03-10 23:23:50
【问题描述】:

目前正在做一个项目,但我的程序有点停滞不前。

while(True):
    if p1.play() == False:
        break
    betInput = int(input("How much do you want to bet?"))
    while(betInput > p1.wallet or betInput <=0):
        betInput = int(input("How much do you want to bet?"))
        continue
    p1.bet(betInput)
    print("")

    for i in range(2):
        p1.getCard ( d.dealCard() )
        p2.getCard ( d.dealCard() )
    p1.show()
    p2.dealShow()
    gameInput = input("Hit or Stand? H\S")
    gameInput = gameInput.lower()
    p1.gameMove(gameInput)
    if p1.winCheck(betInput) == 1:
        continue

    while gameInput == 'h' and p1.cardCheck() != True or gameInput == 'hit' and p1.cardCheck() != True:
        gameInput = input("Hit or Stand? H\S")
        gameInput = gameInput.lower()
        p1.gameMove(gameInput)
        if p1.winCheck(betInput) == 1:
            if p1.play() == False:
                pass
        p2.winCheck(betInput)

问题是,当我跳出“gameInput”循环(退出程序)时,它只是跳出它,然后继续执行代码,有没有办法让它循环备份到第一个while循环?或者,有没有办法立即终止程序?

【问题讨论】:

  • break 只能退出立即循环。您可以(ab)使用异常来模拟您正在寻找的goto 的有限形式。
  • 创建一个布尔变量,并将其初始化为 False。在外部循环中,有一个 if 条件,如果变量设置为 True,则退出循环。在内循环中,如果你的条件满足,将条件设置为True,跳出内循环,然后进入条件for if变量为True,跳出外循环。
  • 您的问题表明存在设计问题。让你的循环成为函数的一部分,让调用者决定做什么。

标签: python


【解决方案1】:

如果您将代码包装在一个方法中,您始终可以从任意点return,无论其嵌套程度如何。

不过,请确保所有可能的代码路径都返回 something

【讨论】:

    【解决方案2】:

    如果我正确理解您的问题,您想回到 while 函数的开头。 continue 函数可以为您服务。Continue function example

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2022-01-22
      • 2021-07-02
      • 2020-03-28
      • 1970-01-01
      相关资源
      最近更新 更多