https://book.pythontips.com/en/latest/for_-_else.html Answer from DismalActivist on reddit.com
🌐
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 »
Discussions

'Finally' equivalent for If/Elif statements in Python - Stack Overflow
Does Python have a finally equivalent for its if/else statements, similar to its try/except/finally statements? Something that would allow us to simplify this: if condition1: do stuff ... More on stackoverflow.com
🌐 stackoverflow.com
When would I use 'else' and 'finally' in a try-except statement in python? - Stack Overflow
try: f_noexception() print("hello") except Exception pass else: print("Hello again") Should give you two prints. Personallz, I think this is mildly useful and you actually don't see it being used very often. However, finally is much more useful. The finally block gets always executed no matter if an exception was raised or not. So you can use that for ... More on stackoverflow.com
🌐 stackoverflow.com
For/else, while/else, try/else.
I agree that while/else and for/else are not used very much, but they can be quite useful for search patterns. Say you are webscraping and looking for with a certain content: for price_div in document.findAll("div"): if "price" in price_div.text: break else: raise RuntimeError("price div not found") # Now price_div is the div you were looking for If you don't want to use the for/else here, you'd have to add a found variable, like this: found = False for price_div in document.findAll("div"): if "price" in price_div.text: found = True break if not found: raise RuntimeError("price div not found") ... More on reddit.com
🌐 r/Python
6
2
December 5, 2022
How does the else clause work in a try/except/else/finally block?
try runs first except runs following the first error else runs if there were no errors finally always runs last An error in anything except try won't be caught and requires its own error context (i.e. another try). More on reddit.com
🌐 r/learnpython
7
1
June 30, 2021
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 › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
try: # Some Code.... except: # optional block # Handling of exception (if required) else: # execute if no exception finally: # Some code .....(always executed)
Published   July 15, 2025
🌐
Codefinity
codefinity.com › courses › v2 › 4281312c-ad7e-416e-83ca-a30df8a34d27 › 1a4e550c-004c-4efd-a127-f487cb07b9f7 › e8d6ad0f-d8dc-4486-ba81-2e203eab31c0
Learn The else and finally Clauses | Advanced Exception Handling
The finally block always runs, whether or not an exception was raised or handled. You use the else block for actions that should only happen when no errors occur.
🌐
Python for Network Engineers
pyneng.readthedocs.io › en › latest › book › 06_control_structures › exceptions.html
Working with try/except/else/finally - Python for network engineers
# -*- coding: utf-8 -*- try: a = input("Enter first number: ") b = input("Enter second number: ") result = int(a)/int(b) except (ValueError, ZeroDivisionError): print("Something went wrong...") else: print("Result is squared: ", result``2) ... $ python divide_ver3.py Enter first number: 10 Enter second number: 2 Result is squared: 25 $ python divide_ver3.py Enter first number: werq Enter second number: 3 Something went wrong... Block finally is another optional block in try statement. It is always implemented, whether an exception has been raised or not. It’s about actions that you have to do anyway. For example, it could be a file closing.
Find elsewhere
🌐
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 else: # loop fell through without finding a factor print(n, 'is a prime number')
🌐
Saylor Academy
learn.saylor.org › mod › page › view.php
CS105: Example: Else and Finally | Saylor Academy | Saylor Academy
The "else" command can be used as part of a "try-except" block to execute code if no errors in the set of errors being tested have occurred. The "finally" section of code will always run, but it helps to programmatically delineate such code ...
🌐
Note.nkmk.me
note.nkmk.me › home › python
Try, except, else, finally in Python (Exception handling) | note.nkmk.me
August 15, 2023 - try: for i in [-2, -1, 0, 1, 2]: print(1 / i) except ZeroDivisionError as e: print(e) # -0.5 # -1.0 # division by zero ... You can specify the code to execute after the except clause using the else and finally clauses, which will be described later.
🌐
Jerry Ng
jerrynsh.com › python-for-else-construct-a-deep-dive
How and When To Use For Else in Python Loop - Jerry Ng
April 3, 2023 - Similar to the for-else construct, the try-else construct is useful to distinguish between: ... try: book = find_book(id=1) except BookNotFoundError: # handle the exception print("Book not found! :(") else: # run this block if no exception was raised send_slack_notification(book) finally: # this ...
🌐
Medium
galea.medium.com › pythons-try-except-else-finally-explained-f04d47d57125
Python’s “try except else finally” explained | by Alex Galea | Medium
October 4, 2020 - I showed a decent example of else above, and others I have seen work along similar lines. The finally statement is probably best understood in terms of code readability, since it offers a nice way of grouping similar logic within the same control flow structure. What do you think? Let me know in a comment or on twitter. In this post I shared my thoughts on dogs VS cats. Oh yeah and some Python stuff about control flow structures… whatever. As always, thanks for ...
🌐
W3Schools
w3schools.com › python › ref_keyword_finally.asp
Python finally Keyword
try: x > 3 except: print("Something went wrong") else: print("Nothing went wrong") finally: print("The try...except block is finished") Try it Yourself »
🌐
Stack Overflow
stackoverflow.com › questions › 70721324 › when-would-i-use-else-and-finally-in-a-try-except-statement-in-python
When would I use 'else' and 'finally' in a try-except statement in python? - Stack Overflow
What is the intended use of the optional "else" clause of the "try" statement in Python? (24 answers) Closed 4 years ago. ... try: print(x) #Not defined before except: print("Something went wrong") finally: print("The 'try except' is finished")
🌐
Snarky
snarky.ca › unravelling-finally-and-else-from-try
Unravelling `finally` and `else` from `try` statements
February 8, 2022 - In contrast to else, we want finally to always execute. That makes our biggest concern being not whether some other code executed but making sure we execute the finally clause once, every time.
🌐
Oracle
docs.oracle.com › javase › tutorial › › essential › exceptions › finally.html
The finally Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
The following finally block for the writeList method cleans up and then closes the PrintWriter and FileWriter. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } if (f != null) { System.out.println("Closing FileWriter"); f.close(); } } Important: Use a try-with-resources statement instead of a finally block when closing a file or otherwise recovering resources.
🌐
Python documentation
docs.python.org › 3 › reference › compound_stmts.html
8. Compound statements — Python 3.14.6 documentation
The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return, break or continue statement, the saved exception is discarded. For ...
🌐
Reddit
reddit.com › r/learnpython › how does the else clause work in a try/except/else/finally block?
r/learnpython on Reddit: How does the else clause work in a try/except/else/finally block?
June 30, 2021 -

I just re-learned some Python fundamentals and found that I almost forgot that it's possible to add an else clause after try/except (and before finally).

I thought this else is no more than a catch-all version of the usual except clause, which catches those exceptions not specified in the preceding except statements.

So this is what I think it works like:

try:
    x = items[1]
except IndexError:
    ... # maybe there are fewer than two elements
except TypeError:
    ... # maybe it's a generator or whatever does not support indexing
else:
    ... # any exceptions other than IndexError and TypeError. Like NameError, if items is not even defined

which I think is the same as

try:
    x = items[1]
except IndexError:
    ...
except TypeError:
    ... 
except Exception:
    ... # this catches all other exceptions

But some answers on SO explain that else is used when the exception is raised in the previous except clauses. Is that one of the differences between the two snippets above? So it's like wrapping the try/except block in another try/except block?

I also wonder whether the else actually does what I think (as in the first snippet). Maybe not? It's not a catch-all except?

🌐
Reddit
reddit.com › r/python › when to use try-except-else-finally in python
r/Python on Reddit: When to use try-except-else-finally in Python
February 4, 2023 - Unlike many other languages and according to some popular coding suggestion guides the try block should be just the line(s) of code that can throw the exception you are catching; the else is what to do if the exception didn't occur. The finally is useful for freeing up resources regardless of success / error code path (like closing a file / socket).