Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the method for 'If loop does NOT break, run code'? [duplicate]

Tags:

python

loops

I am trying to write a for-loop to go through values, and if by the end of the loop it did not break, I want it to run some code. For example:

for i in range(10):
    if someCondition:
        break
#If the loop did NOT break, then...
doSomething()

There is a roundabout method. For example,

didNotBreak = True
for i in range(10)
    if someCondition:
        didNotbreak = False
        break
if didNotBreak:
    doSomething()

Is there a simpler method?

like image 383
TheRaidGaming Avatar asked Jan 24 '26 05:01

TheRaidGaming


1 Answers

You can use an else clause on the loop.

for i in range(10):
    if someCondition:
        break
else:
    #If the loop did NOT break, then...
    doSomething()

The else clause is executed if the loop completes without hitting a break.

See https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops which specifies:

... a loop’s else clause runs when no break occurs

like image 160
khelwood Avatar answered Jan 25 '26 17:01

khelwood



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!