Loop else
- Python course
- Beginner
- Lesson 46/116
- 4 min
Learn for/else and while/else structure.
Loop with else
Python loops can have an else. This block runs when the loop ends without break:
for n in [1, 2, 3]:
if n == 5:
break
else:
print("5 not found")When the loop ends without break, else runs; if break exits, else is skipped. This is handy in search loops to say 'not found'.
Search loop with else
else is most used in search loops. If the target is found, break exits and else does not run. If not found, the loop ends and else says 'not found':
for n in [2, 4, 6]:
if n == 5:
print("Found")
break
else:
print("5 not in list")This puts the 'found/not found' logic in one loop.
Practice Print a loop else
Write for n in [1, 2, 3]: print(n). Add else: print("Done") after the loop.
Starter code
# loop elseSample solution
for n in [1, 2, 3]:
print(n)
else:
print("Done")Expected output
1 2 3 Done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does a loop else run?
- When it ends without break Correct answer
- When break occurs
- Always
- Never
Explanation: else runs when the loop ends without break.
2 Complete the loop else
for n in [1, 2, 3]:
print(n)
____:
print("Done")
for n in [1, 2, 3]:
print(n)
else:
print("Done")
Explanation: else runs when the loop ends without break.
3 Match the loop else concepts
| Term | Meaning |
|---|---|
else |
Breakless end |
break |
Exit |
continue |
Skip |
for |
Collection loop |