【问题标题】:How to return to previously nested `while True` loops? [duplicate]如何返回到之前嵌套的“while True”循环? [复制]
【发布时间】:2017-06-06 12:54:24
【问题描述】:

假设我有这种格式的东西:

while True1:
    if something:
        do some thing
    elif something else:
        do something else
        while True2:
            if something1:
                do some thing1
            if something2:
                do some thing2
            if want to end this while True2 loop
                go back to first while True1 loop
    elif something else else:
        do some thing else else

等等

如何使 while True 循环中的某些内容返回到之前嵌套在其中的 while True 循环?

【问题讨论】:

  • break 将跳出当前循环

标签: python python-3.x loops while-loop nested-loops


【解决方案1】:

使用break 语句。

x = 0
while True:
    x += 1
    if x == 5:
        print(x)
        break

将输出5 并退出

【讨论】:

    【解决方案2】:

    break 语句就是这样做的。

    while True: #1
        if something:
            do something
        elif something else:
            do something else
            while True: #2
                if something1:
                    do something
                if something2:
                    do something else
                if want to end this while True #2 loop:
                    break            # will break out of the innermost loop only
        elif something else else:
            do some thing else else
    

    阅读更多:Control Flow Tools

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      相关资源
      最近更新 更多