The else clause is only executed after the while condition is evaluated to be false.

Thus, if you break out of the loop, or if an exception is raised, the else won't be executed (since the while condition has not been evaluated to be false yet).

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()
Answer from ars on Stack Overflow
🌐
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 · Match Code Challenge Python While Loops · While Loops Code Challenge Python For Loops · For Loops Code Challenge Python Functions · Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range ·
Discussions

While loops can have an else statement!
You're almost right! The code under the else will be executed only when the while loop is not "broke out of". In the following code, if you change the variable guess to the value 10. The else clause will be executed. l = [4,5,6,7,8,9] count = 0 guess = 5 while count < len(l): if l[count] == guess: break count += 1 else: # if guess == 5 this will not be executed print("guess not found") print(count) More on reddit.com
🌐 r/learnpython
4
9
January 31, 2024
Examples of the while...else or for...else constructs in the wild?
I use a for/else in my code for a Miller-Rabin primality checker: def isPrime(n, k=5): # miller-rabin if n < 2: return False for p in [2,3,5,7,11,13,17,19,23,29]: if n % p == 0: return n == p s, d = 0, n-1 while d % 2 == 0: s, d = s+1, d/2 for i in range(k): x = pow(randint(2, n-1), d, n) if x == 1 or x == n-1: continue for r in range(1, s): x = (x * x) % n if x == 1: return False if x == n-1: break else: return False return True More on reddit.com
🌐 r/Python
34
13
November 13, 2014
Why do for loops have an else block?
https://book.pythontips.com/en/latest/for_-_else.html More on reddit.com
🌐 r/Python
129
307
August 25, 2022
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
🌐
Reddit
reddit.com › r/python › til you can use else with a while loop
r/Python on Reddit: TIL you can use else with a while loop
March 1, 2025 -

Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable

This will execute when the while condition is false but not if you break out of the loop early.

For example:

Using flag

nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0

while i < len(nums):
    if nums[i] == target:
        found = True
        print("Found:", target)
        break
    i += 1

if not found:
    print("Not found")

Using else

nums = [1, 3, 5, 7, 9]
target = 4
i = 0

while i < len(nums):
    if nums[i] == target:
        print("Found:", target)
        break
    i += 1
else:
    print("Not found")
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-else
Python While Else - GeeksforGeeks
July 23, 2025 - In Python, the while loop is used for iteration. It executes a block of code repeatedly until the condition becomes false and when we add an "else" statement just after the while loop it becomes a "While-Else Loop".
🌐
Codefinity
codefinity.com › courses › v2 › a8aeafab-f546-47e9-adb6-1d97b2927804 › 98dca52d-9dbe-41d0-9260-dd6a4c00f21e › d2099d74-36c9-4479-b70a-e3049bdcdfbe
Learn The else Statement in a while Loop | The while Loop
The else block executes when the loop terminates normally, meaning the loop condition becomes False without encountering a break statement. 1234567891011 travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize ...
🌐
Medium
allwin-raju.medium.com › understanding-the-while-else-loop-in-python-436c791649e8
Understanding the while-else Loop in Python | by Allwin Raju | Medium
November 12, 2024 - The else block in a while-else loop only executes if the while loop finishes without encountering a break statement. If a break statement terminates the loop early, Python skips the else block entirely.
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
In a for loop, the else clause is executed after the loop finishes its final iteration, that is, if no break occurred. In a while loop, it’s executed after the loop’s condition becomes false.
🌐
Reddit
reddit.com › r/learnpython › while loops can have an else statement!
r/learnpython on Reddit: While loops can have an else statement!
January 31, 2024 -

Maybe I'm the only one who didn't know this, but you can put an else statement after a while loop which will be used if the while loop is never entered. I found this out on the Leetcode problem of the day for today when I tried putting an else after my while loop, mostly expecting an error but typing because it's what I wanted the code to do, and it ran! The code I used is below. I know there are more optimal solutions, but I'm happy with what I learned today.

class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    n = len(temperatures)
    answers = [0] * n
    stack = []
    for i in range(n):
        while len(stack) > 0 and temperatures[i] > stack[-1][1]:
            answers[stack[-1][0]] = i - stack[-1][0]
            stack.pop()
        else:
            stack.append([i, temperatures[i]])
        if len(stack) == 0:
            stack.append([i, temperatures[i]])
    return answers

🌐
Medium
medium.com › @andrewdass › python-for-loops-while-loops-and-if-else-statements-2ecc134953ca
Python: For Loops, While Loops and If-Else Statements | by Andrew Dass | Medium
February 12, 2024 - index = 0 while index < 3: print(index) ... executed: ... An if-else statement goes through two conditions to see if the specified condition from the if statement is true, otherwise, the else statement will be printed....
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - Welcome!") break if attempts >= MAX_ATTEMPTS: print("Too many failed attempts.") break else: print(f"Incorrect password. {MAX_ATTEMPTS - attempts} attempts left.") This loop has two exit conditions. The first condition checks whether the password is correct. The second condition checks whether the user has reached the maximum number of attempts to provide a correct password. Both conditions include a break statement to finish the loop gracefully. ... You’ve learned a lot about Python’s while loop, which is a crucial control flow structure for iteration.
🌐
W3Schools
w3schools.com › python › gloss_python_for_else.asp
Python For 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 ... Note: The else block will NOT be executed if the loop is stopped by a break statement.
🌐
Medium
monalishakumari.medium.com › for-while-loop-with-else-in-python-8a5f1d22f715
For/While Loop with Else in Python | by Monalisha Kumari | Medium
January 17, 2023 - i=0 while i<7: print(i) i=i+1 else: print("Hello") ... Similarly like for loop, here also we can see that wherever loop got successfully completed; else block executed whereas it is not executed ... I hope you find this useful in journey of learning your python programming.
🌐
DEV Community
dev.to › nomidlseo › mastering-pythons-loop-else-block-a-beginners-guide-to-for-and-while-loops-30je
Mastering Python’s Loop Else Block: A Beginner’s Guide to For and While Loops - DEV Community
November 6, 2025 - Wait… an else block? With loops? That’s right! In Python, the else clause isn’t just for if statements — it can also appear after a for or while loop.
🌐
Scaler
scaler.com › home › topics › python › python for else
Python For Else - Scaler Topics
December 1, 2023 - In Python, 'for-else' and 'while-else' constructs provide a unique way to handle loops with an additional clause executed when the loop usually concludes without a break statement.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-loop
Python While Loop - GeeksforGeeks
In first example, loop completes all iterations, so the else block executes. In second example, loop stops because of break, so the else block is skipped. Python · i = 0 while i < 4: i += 1 print(i) else: print("No Break\n") i = 0 while i < 4: i += 1 print(i) break else: print("No Break") Try It Yourself ·
Published   June 3, 2026
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-else-loop
Python Else Loop - GeeksforGeeks
July 28, 2020 - So let's see the example of while loop and for loop with else below. Consider the below example. Python3 · i=0 while i<5: i+=1 print("i =",i) else: print("else block is executed") Output: i = 1 i = 2 i = 3 i = 4 i = 5 else block is executed · declare i=0 ·
🌐
W3Schools
w3schools.com › python › python_if_else.asp
Python Else Statement
Python Examples Python Compiler ... Interview Q&A Python Bootcamp Python Training ... The else keyword catches anything which isn't caught by the preceding conditions....
🌐
Plain English
python.plainenglish.io › what-i-learned-today-pythons-while-else-a-hidden-gem-for-beginners-10d67172c8e8
🌟 What I Learned Today: Python's while-else — A Hidden Gem for Beginners | by Saran Raj k | Python in Plain English
July 24, 2025 - The else block runs only if the loop ends normally — that is, not via a break. ... It lets you handle situations where you want to do something only if no early exit (break) happened during the loop. ... Let’s say we want to check if a number exists in a list.
🌐
Real Python
realpython.com › lessons › while-loop-else-clause
The While Loop Else Clause (Video) – Real Python
Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... This lesson covers the while-loop-else-clause, which is unique to Python. The else-block is only executed if the while-loop is exhausted.
Published   March 1, 2019
🌐
W3Schools
w3schools.com › python › python_while_loops.asp
Python While Loops
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 ... With the while loop we can execute a set of statements as long as a condition is true. ... Note: remember to increment i, or else the loop will continue forever.