2

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?

1 Answers1

5

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

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Oh dear. It seems that I formatted that method wrong when I did it the first time, so I believed that it did the opposite of that. Thank you. – TheRaidGaming Mar 23 '21 at 21:10