0
0
Pythonprogramming~5 mins

For–else execution behavior in Python

Choose your learning style9 modes available
Introduction

The for-else statement helps you run extra code after a loop finishes normally. It tells you if the loop ended without interruptions.

When you want to check if a search inside a list found something or not.
When you want to run some code only if the loop did not stop early.
When you want to handle a case where no item met a condition inside the loop.
Syntax
Python
for item in collection:
    # do something with item
else:
    # do this if loop did NOT break

The else block runs only if the for loop finishes all items without a break.

If the loop uses break, the else block is skipped.

Examples
This prints all numbers, then prints 'Done looping' because the loop ended normally.
Python
for num in [1, 2, 3]:
    print(num)
else:
    print('Done looping')
This prints 1, then stops at 2 because of break. The else does NOT run.
Python
for num in [1, 2, 3]:
    if num == 2:
        break
    print(num)
else:
    print('Done looping')
Sample Program

This program looks for even numbers in the list. If it finds one, it stops and prints it. If none are found, it prints a message after the loop.

Python
numbers = [1, 3, 5, 7]

for n in numbers:
    if n % 2 == 0:
        print('Found an even number:', n)
        break
else:
    print('No even numbers found')
OutputSuccess
Important Notes

The else after for is different from if-else. It runs only if no break happens.

Use for-else to avoid extra flags or checks outside the loop.

Summary

The else block runs only if the for loop completes without break.

It helps detect if a loop ended normally or was stopped early.

Useful for searching or checking conditions inside loops.