【问题标题】:break command for nested loops inside conditional statement [duplicate]条件语句内嵌套循环的中断命令[重复]
【发布时间】:2020-10-28 10:01:36
【问题描述】:

我想在 if 条件中使用 break 语句来中断 main while 循环

a = 0
b = True
while b:
    print(a)
    while a < 10:
        if a == 8:
            b = False
            break       # want to break both while loops using this command
        else:
            print(a)
            a += 1

结果应该是 0 0 1 2 3 4 5 6 7

【问题讨论】:

标签: python if-statement while-loop conditional-statements break


【解决方案1】:

Python 不提供一次跳出两个(或更多)循环的方法,因此简单的方法如下所示:

b = True
while b:
    print(a)
    while a < 10:
        if a == 8:
            b = False #Use this value to break out of top loop
            break
        else:
            print(a)
            a += 1
    if !b: #Use the value of b like this to break out of top loop
        break

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 2017-12-20
    • 2018-04-02
    • 1970-01-01
    • 2022-01-14
    • 2015-01-18
    • 2013-02-16
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多