🌐
W3Schools
w3schools.com › python › gloss_python_for_else.asp
Python For Else
for x in range(6): if x == 3: break print(x) else: print("Finally finished!") Try it Yourself » · Python For Loops Tutorial For Loop Through a String For Break For Continue Looping Through a Range Nested Loops For pass ... If you want to use W3Schools services as an educational institution, ...
🌐
W3Schools
w3schools.com › python › python_if_else.asp
Python Else Statement
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... The else keyword catches anything which isn't caught by the preceding conditions....
🌐
W3Schools
w3schools.com › python › python_conditions.asp
Python If Statement
Everything else is treated as True. This includes positive numbers (5), negative numbers (-3), and any non-empty string (even "False" is treated as True because it's a non-empty string).
🌐
W3Schools
w3schools.com › python › gloss_python_while_else.asp
Python While Else
Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match ... Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range ... Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts
🌐
Python Tips
book.pythontips.com › en › latest › for_-_else.html
21. for/else — Python Tips 0.1 documentation
for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n/x) break · It finds factors for numbers between 2 to 10. Now for the fun part. We can add an additional else block which catches the numbers which have no factors and are therefore prime numbers:
🌐
W3Schools
w3schools.com › python › gloss_python_else.asp
Python If Else
Python Examples Python Compiler ... Q&A Python Bootcamp Python Training ... The else keyword catches anything which isn't caught by the preceding conditions....
🌐
W3Schools
w3schools.com › python › python_challenges_if_basics.asp
Python If...Else Code Challenge
Python Examples Python Compiler ... Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... Test your understanding of if, elif, else, and shorthand if statements. ... If you want to use W3Schools services as an educational institution, team ...
🌐
W3Schools
w3schools.com › python › ref_keyword_else.asp
Python else Keyword
Python Examples Python Compiler ... Python Training ... The else keyword is used in conditional statements (if statements), and decides what to do if the condition is False....
🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): ... Note: The else block will NOT be executed if the loop is stopped by a break statement. Break the loop when x is 3, and see what happens with the else block: for x in range(6): if x == 3: break print(x) else: print("Finally finished!") Try it Yourself »
Find elsewhere
🌐
Tutorial Teacher
tutorialsteacher.com › python › python-else-loop
Python else Loop
for x in range(5): print ("iteration no {} in for loop".format(x+1)) else: print ("else block in loop") print ("Out of loop") The output of the above code confirms that the else block in the for loop will be executed while the number is in the range.
🌐
Python Snacks
pythonsnacks.com › p › python-for-else-statement
A quick tutorial for the for/else construct in Python
April 15, 2025 - The else block in a for/else loop is executed only if the loop completes all its iterations without encountering a break statement.
🌐
W3Schools
w3schools.com › python › gloss_python_if_else_shorthand.asp
Python Shorthandf If Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: ... Python If...Else Tutorial If statement If Indentation Elif Else Shorthand If If AND If OR If NOT Nested If The pass keyword in If ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
Tutorialspoint
tutorialspoint.com › python › python_forelse_loops.htm
Python for-else Loops
Following is the syntax of for loop with optional else block − · for variable_name in iterable: #stmts in the loop . . . else: #stmts in else clause .
🌐
GeeksforGeeks
geeksforgeeks.org › using-else-conditional-statement-with-for-loop-in-python
Using Else Conditional Statement With For loop in Python - GeeksforGeeks
In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed. ... # Python 3.x program to check if an array consists # of even number def contains_even_number(l): for ele in l: if ele % 2 == 0: print ("list contains an even number") break # This else executes only if break is NEVER # reached and loop terminated after all iterations.
Published   July 13, 2022
Top answer
1 of 16
948

A common construct is to run a loop until something is found and then to break out of the loop. The problem is that if I break out of the loop or the loop ends I need to determine which case happened. One method is to create a flag or store variable that will let me do a second test to see how the loop was exited.

For example assume that I need to search through a list and process each item until a flag item is found and then stop processing. If the flag item is missing then an exception needs to be raised.

Using the Python for...else construct you have

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

Compare this to a method that does not use this syntactic sugar:

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

In the first case the raise is bound tightly to the for loop it works with. In the second the binding is not as strong and errors may be introduced during maintenance.

2 of 16
428

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
    if obj.key == search_key:
        found_obj = obj
        break
else:
    print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
    for obj in objects:
        if obj.key == search_key:
            return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
    print('Found {}'.format(matching_objs[0]))
else:
    print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

🌐
GeeksforGeeks
geeksforgeeks.org › python › using-else-conditional-statement-with-for-loop-in-python
Using Else with Loops in Python - GeeksforGeeks
In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed. ... # Python 3.x program to check if an array consists # of even number def contains_even_number(l): for ele in l: if ele % 2 == 0: print ("list contains an even number") break # This else executes only if break is NEVER # reached and loop terminated after all iterations.
Published   October 4, 2025
🌐
W3Schools
w3schools.com › python › gloss_python_try_else.asp
Python Try Else
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Try it Yourself » · Python Try Except Tutorial Error Handling Handle Many Exceptions Try Finally raise ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-for-else
Python For Else - GeeksforGeeks
July 23, 2025 - The else block is executed only if the for loop finishes iterating over the sequence without being interrupted by a break statement. Here’s a basic example to illustrate the for-else loop:
🌐
Scaler
scaler.com › home › topics › python › python for else
Python For Else - Scaler Topics
December 1, 2023 - The 'else' block in a 'for loop' in Python, often referred to as 'for else python', is executed after the for loop completes its iteration over the entire sequence, but only if a break statement didn't terminate the loop.
🌐
Python Tutorial
pythontutorial.net › home › python basics › python for…else
Introduction to the Python for else statement - Python Tutorial
March 31, 2025 - for item in iterables: # Process ... language: PHP (php) ... Python will execute the else block only if the for loop iterates all items in the iterables without hitting a break statement....