3

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?

2
  • 1
    If you put an else clause on the loop, it will be run if the loop did not break. Commented Mar 23, 2021 at 21:05
  • Doesn't it do the opposite? Commented Mar 23, 2021 at 21:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.