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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With