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
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-else
Python While Else - GeeksforGeeks
July 23, 2025 - Below are some of the ways by which we can use Python while else more effectively in Python: In the below code, we have created a list of numbers, after that we have written a while-else loop to search the target in the list 'numbers'. The while loop is iterated over the list and check if the target is present in the list or not using if condition and in this example the target is not present so the while loop run completely using break statement and hence executed the else block.
🌐
W3Schools
w3schools.com › python › gloss_python_while_else.asp
Python While Else
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else
Discussions

TIL you can use else with a while loop
You can also use it with for! More on reddit.com
🌐 r/Python
197
641
March 1, 2025
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
🌐
Towards Data Science
towardsdatascience.com › home › latest › python for-else and while-else clearly explained with 4 real-world examples
Python For-Else and While-Else Clearly Explained with 4 Real-World Examples | Towards Data Science
March 5, 2025 - For a moment, stop trying to make sense of the wordelse`. Just think that Python is offering you an additional feature with its loops. Let us see how it works. ... The else clause will not be executed if the loop gets terminated by a break statement. If a loop does not hit a break statement, then the else clause will be executed once after the loop has completed all its iterations (meaning, after the loop has completed normally). Image by Author – For-Else and While-Else in Python
🌐
Python Examples
pythonexamples.org › python-while-else
Python While Else
In this example, we will use else block after while block to close the file we read line by line in the while block. f = open("sample.txt", "r") while True: line = f.readline() if not line: break print(line.strip()) else: f.close · Hi User! Welcome to Python Examples.
🌐
Python Tutorial
pythontutorial.net › home › python basics › python while else
Python while...else Statement
March 31, 2025 - The else clause in the while else statement will execute when the condition of the while loop is False and the loop runs normally without encountering the break or return statement. Try the Python while else statement whenever you need to have a flag in a while 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
1234567891011 travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize index i = 0 # Iterate through the destinations while i < len(travel_list): print(travel_list[i]) i += 1 else: print('All destinations have been listed!') ...
Find elsewhere
🌐
Vaia
vaia.com › en-us › explanations › computer-science › computer-programming › python-while-else
Vaia | The #1 learning app for university & school
February 25, 2026 - Vaia is an intelligent learning app for students. Achieve your learning goals with more structure, motivation & efficiency. ⭐ Sign up now!
🌐
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")
🌐
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

🌐
Perlego
perlego.com › index › computer-science › python-while-else
Python while else | Overview & Research Examples
>python if_python.py Return TRUE or FALSE: Python was released in 1991: FALSE Wrong Bye! Solution for this activity can be found at page 283. A while statement allows you to execute a block of code repeatedly, as long as a condition remains true. That is to say, as long as condition X remains true, execute this code . A while statement can also have an else clause that will be executed exactly once when the condition, X , that's mentioned is no longer true.
🌐
StudySmarter
studysmarter.co.uk › computer science › computer programming › python while else
Python While Else: Loop, True Else, Break | StudySmarter
The 'else' keyword, followed by another colon (:), starts the else block. This block will execute once the while condition becomes false. The else block is optional. Let us consider a simple example demonstrating the Python while else loop in action:
🌐
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) index += 1 ... An if-statement checks if a condition is True, and if it is, then the code in its block will be executed: ... An if-else statement goes through two conditions to see if the specified condition ...
🌐
Real Python
realpython.com › lessons › while-loop-else-clause
The While Loop Else Clause (Video) – Real Python
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. You don’t know what that means? Check out this lesson to find out! Furthermore, you can find two examples below, which you can copy-paste and run to get ...
Published   March 1, 2019
🌐
TOOLSQA
toolsqa.com › python › python-while-loop
Python While Loop | While True and While Else in Python || ToolsQA
August 6, 2021 - The example above uses python lists and breaks statements in the code. Please refer to python lists and break statements in python to learn more about them. The while loop in python also supports another interesting use case. If there are any program requirements to execute a sentence after the loop, we can construct an "else" statement that would execute when the condition returns "False."
🌐
Programiz
programiz.com › python-programming › while-loop
Python while Loop (With Examples)
For example, while True: user_input = input('Enter your name: ') # terminate the loop when user enters end if user_input == 'end': print(f'The loop is ended') break print(f'Hi {user_input}') ... Here, the condition of the while loop is always True. However, if the user enters end, the loop ...
🌐
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 - while condition: # Loop code if some_condition: break # Exits the loop, so 'else' is skipped else: # Executes only if the loop condition becomes False without hitting 'break'
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-loop
Python While Loop - GeeksforGeeks
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 · Output · 1 2 3 4 No Break 1 ·
Published   June 3, 2026
🌐
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.