counter = 1 
while (counter <= 5): 
    if counter < 2:
        print("Less than 2")
    elif counter > 4:
        print("Greater than 4")
    counter += 1

This will do what you want (if less than 2, print this etc.)

Answer from trolley813 on Stack Overflow
🌐
Python.org
discuss.python.org › python help
If statements within a while loop (beginner question) - Python Help - Discussions on Python.org
January 28, 2023 - Hello. I’m new to Python (and coding in general). I’m trying to make a sample store, and I want to ask the user if they have a coupon. If they have a coupon they have to type in the coupon code to get a discount. Everything works up until the part where the wrong coupon code is entered and it skips my loop entirely.
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
syntax - Else clause on Python while statement - Stack Overflow
I've noticed the following code is legal in Python. My question is why? Is there a specific reason? n = 5 while n != 0: print n n -= 1 else: print "what the..." Many beginners accidentally stumble on this syntax when they try to put an if/else block inside of a while or for loop, and don't ... More on stackoverflow.com
🌐 stackoverflow.com
if statement - Why does python use 'else' after for and while loops? - Stack Overflow
See also Else clause on Python while statement for the specific question about what the syntax means. ... You might like to translate it to "then" in your head. ... Don't forget the key line in the Zen of Python: "... that way may not be obvious at first unless you're Dutch." ... In my head I translate it into "if not break". And, since break is used a lot in "I've found it" loops... More on stackoverflow.com
🌐 stackoverflow.com
Whats the difference between a while loop and a for loop?
Consider how the terms are used in common language: FOR For each day in July, I will practice writing loops. For every student in the class, provide a lunchtime meal. For each letter in the alphabet, write down a word beginning with that letter. For numbers in the range 1 to 10, calculate the square root. Notice that for each case, we iterate through multiple things (days in the month / students in the class / letters in the alphabet / numbers in a range). WHILE While there is still daylight, we can play football. While the music is playing, we will dance. While I am waiting, I will read a book. While my set of Pokémon cards is incomplete, I will keep collecting them. Notice that in each case, something is done for as long as a condition (a "predicate") is satisfied (is "True"). In these examples, the predicates are: "There is daylight?", "The music is playing?", "I am waiting?", "The set is incomplete?". As soon as the answer is "False", the loop stops. More on reddit.com
🌐 r/learnpython
69
124
July 15, 2024
🌐
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".
🌐
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

🌐
W3Schools
w3schools.com › python › python_while_loops.asp
Python While Loops
Python Examples Python Compiler ... 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. The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. With the break statement we can stop the loop even if the while ...
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 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.
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - Python allows an optional else clause at the end of while loops. The syntax is shown below: ... The code under the else clause will run only if the while loop terminates naturally without encountering a break statement.
Find elsewhere
🌐
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....
🌐
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 · Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match · Match Code Challenge Python While Loops ·
🌐
Programiz
programiz.com › python-programming › while-loop
Python while Loop (With Examples)
In Python, we use a while loop to repeat a block of code until a certain condition is met. For example, number = 1 while number <= 3: print(number) number = number + 1 ... In the above example, we have used a while loop to print the numbers from 1 to 3. The loop runs as long as the condition ...
🌐
Python documentation
docs.python.org › 3 › reference › compound_stmts.html
8. Compound statements — Python 3.14.3 documentation
while_stmt: "while" assignment_expression ":" suite ["else" ":" suite] This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the ...
🌐
Python Tutorial
pythontutorial.net › home › python basics › python while else
Python while...else Statement
March 31, 2025 - When the condition becomes False and the loop runs normally, the else clause will execute. However, if the loop is terminated prematurely by either a break or return statement, the else clause won’t execute at all.
🌐
TOOLSQA
toolsqa.com › python › python-while-loop
Python While Loop | While True and While Else in Python || ToolsQA
August 6, 2021 - To run a statement if a python while loop fails, the programmer can implement a python "while" with else loop.
🌐
Programiz
programiz.com › python-programming › if-elif-else
Python if, if...else Statement (With Examples)
In computer programming, we use the if statement to run a block of code only when a specific condition is met. In this tutorial, we will learn about Python if...else statements with the help of examples.
🌐
StudySmarter
studysmarter.co.uk › python while else
Python while else: Definition & Meaning | StudySmarter
In Python, a "while-else" loop allows for code execution as long as a specified condition is true, with the optional "else" block running only if the loop completes naturally without encountering a break statement.
🌐
Tutorialspoint
tutorialspoint.com › python › python_while_loops.htm
Python while Loop Statements
April 4, 2023 - Python supports having an else statement associated with a while loop. If the else statement is used with a while loop, the else statement is executed when the condition becomes false before the control shifts to the main line of execution.
🌐
PYnative
pynative.com › home › python exercises › python if else, for loop, and range() exercises with solutions
Python if else, for loop, and range() Exercises with Solutions
April 19, 2025 - Control flow statements: Use the ... loop with range(), we can repeat an action a specific number of times. while loop: To execute a code block repeatedly, as long as the condition is True....
Top answer
1 of 16
944

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
427

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