在Python中打破while循环后的流控制

Ben*_* S. 3 python flow while-loop

我对编程和Python都很陌生.几次,我创造了一个感觉就像一个尴尬的程序流程,我想知道我是否遵循最佳实践.这在概念上是我想要做的:

def pseudocode():
    while some condition is true:
        do some stuff
        if a condition is met:
            break out of the while loop
    now do a thing once, but only if you never broke out of the loop above 
Run Code Online (Sandbox Code Playgroud)

我最终做了什么工作,但不知怎的感觉:

def pseudocode():
    while some condition is true:
        do some stuff
        if some condition is met:
            some_condition_met = True
            break out of the while loop

    if some_condition_met is False:
        do a thing
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Ash*_*ary 8

你正在寻找while-else循环:

def pseudocode():
    while some condition is true:
        do some stuff
        if a condition is met:
            break out of the while loop
    else:
        now do a thing once, but only if you never broke out of the loop above 
Run Code Online (Sandbox Code Playgroud)

来自docs:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]
Run Code Online (Sandbox Code Playgroud)

一个break在首套房执行的语句终止循环,不执行该else条款的套件.