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 - ... # Example of while else with continue statement counter = 1 num = 2 while(counter <= 10): if(counter%2 == 0): counter += 1 # Skip the rest of the loop body and go to the next iteration continue print(f"{num} * {counter} = {num*counter}") ...
Discussions

While loop with else statement - C++ Forum
How do I stop the infinite loop, and why did it start in the first place? I'm hoping it's a simple mistake since the else in the main function displays Invalid correctly, and although both elses are the same, (at least look the same, this is probably where I went wrong) it initiates the loop. More on cplusplus.com
🌐 cplusplus.com
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
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
If statements in a while loop with JOptionPane for input.
Nevermind, I just forgot how to java for entirely too long. The appropriate string comparison is as follows: if (isStudent.equals("yes)) More on reddit.com
🌐 r/javahelp
3
1
December 2, 2014
🌐
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
🌐
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!') ...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python while else
Python while...else Statement
March 31, 2025 - If the fruit is not found, the while loop is terminated normally and the else clause will be executed to add a new fruit to the list.
🌐
Cplusplus
cplusplus.com › forum › beginner › 206676
While loop with else statement - C++ Forum
( Yes or No ) How much? ( 1 - 10 ) Less or equal to 4. The loop also happens if I enter a number over 3,000,000,000, so it is using the else statement. It might have something to do with my first set of if elses being words to words, and my second set being numbers to numbers.
🌐
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

Find elsewhere
🌐
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
🌐
StudySmarter
studysmarter.co.uk › computer science › computer programming › python while else
Python While Else: Loop, True Else, Break | StudySmarter
When the count exceeds 5, the loop terminates, and the else block is executed, printing "The loop has ended." The output of this code will be: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 The loop has ended. Example: Imagine you want to create a program that prints the Fibonacci sequence up to a specific number. You could use a while else loop to do this:
🌐
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 - Further, if you want to execute some statements only if the loop has completed normally (meaning, completed all its iterations without hitting a break) then you could write those statements inside the loop’s else clause. Go through the below example to understand it better. The else clause of a loop (for/while) gets executed only if the loop has completed its execution fully without hitting a break statement (in other words, loop has completed normally).
🌐
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.
🌐
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")
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-else-loop
Python Else Loop | GeeksforGeeks
July 28, 2020 - i+=1 increment of i because we don't want to execute the while loop infinite times. ... Consider the below example. ... The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
For more on the try statement and exceptions, see Handling Exceptions. The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: >>> while True: ...
🌐
Programiz
programiz.com › python-programming › while-loop
Python while Loop (With Examples)
For example, counter = 0 while counter < 2: print('This is inside loop') counter = counter + 1 ... Here, on the third iteration, the counter becomes 2 which terminates the loop. It then executes the else block and prints This is inside else block.
🌐
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. ... 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")
Published   June 3, 2026
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - In this example, the game loop runs the game logic. First, it takes the user’s guess with input(), converts it into an integer number, and checks whether it’s greater or less than the secret number.
🌐
Codecademy
codecademy.com › forum_questions › 509fa70f44ee00bae7000ca7
Did you include an 'else' for the while loop? | Codecademy
while count < 4: if count == 1: guess = input("Guess:" + " " + str(count) + "/3") count += +1 elif count > 1: guess = input("Guess:" + " " + str(count) + "/3") count += +1 if guess == random_number: print "You win!" break elif count == 4: print ...
🌐
Coventry University
github.coventry.ac.uk › pages › CUEH › py-quickstart › iteration › while-loops
While Loops - Python for Hackers - Quick Start
The 'else statement only activates when the while loop successfully runs and exits naturally, so it never runs here because the break statement gets tripped. Here are a few 'while' loops to give you some ideas of the kinds of ways you might use them: ... # example-2.py # Search and index pet = ["dog", "cat", "rabbit", "snake", "octopus", ] search = "buffalo" i = 0 while i < len(pet): if pet[i] == search: # we would have found search in pet print(f"We found the search term in index {i}.") break i += 1 else: # We didn't find the search item in the list print("We didn't find the search term!")