Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow control after breaking out of while loop in Python

I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:

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 

What I've ended up doing works, but feels off somehow:

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

Is there a better way?

like image 825
Ben S. Avatar asked Jun 08 '26 02:06

Ben S.


1 Answers

You're looking for while-else loop:

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 

From docs:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

like image 139
Ashwini Chaudhary Avatar answered Jun 10 '26 14:06

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!