Back to series
· 7 min read

The else Statement in Python Loops


I. What Is the else in a Loop

In Python, both for and while loops can be used together with else.

Its basic characteristic is:

When the loop ends normally, the else block runs; when the loop is terminated early by break, the else block does not run.

"Normal termination" here covers two typical cases:

  • for loop: all elements in the iterable have been traversed.
  • while loop: the loop condition becomes false and the loop ends naturally.

1. Basic syntax of for-else

for item in iterable:
    # Loop body
    statements
else:
    # Executed after the loop ends naturally
    statements

Example:

for number in range(5):
    print(number)
else:
    print("Loop ended naturally")

Output:

0
1
2
3
4
Loop ended naturally

All elements in range(5) have been traversed, so the else block runs.

2. Basic syntax of while-else

while condition:
    # Loop body
    statements
else:
    # Executed after the loop ends naturally
    statements

Example:

count = 0

while count < 3:
    print(count)
    count += 1
else:
    print("The loop condition no longer holds")

Output:

0
1
2
The loop condition no longer holds

When count grows to 3, count < 3 no longer holds, the loop ends naturally, and then the else block runs.

3. The else in a loop is not part of if-else

The else in a loop is easily confused with the else in a conditional statement.

The two have completely different semantics:

Syntax Condition for else to run
if-else The if condition does not hold
for-else The for loop ends naturally
while-else The while loop condition becomes false

The else in a loop does not mean "it runs only when the loop never executed", nor does it mean "it always runs when the loop condition fails".

What it really cares about is: whether the loop was terminated early by break.

II. The Relationship Between Loop else and break

The most important thing in understanding the loop else is to grasp how break affects it.

1. break skips else

break is used to immediately end the innermost loop that currently contains it.

If break is encountered during loop execution, the loop terminates early and the following else does not run.

for number in range(5):
    if number == 3:
        print("Target found, exiting early")
        break

    print(number)
else:
    print("Loop ended naturally")

Output:

0
1
2
Target found, exiting early

Execution process:

  1. The loop processes 0, 1, and 2 in turn.
  2. When number == 3, the condition holds.
  3. break executes, ending the loop immediately.
  4. The loop's else block is skipped.

2. else runs when there is no break

for number in range(5):
    if number == 10:
        break

    print(number)
else:
    print("Target not found, loop ended naturally")

Output:

0
1
2
3
4
Target not found, loop ended naturally

Because number never equals 10, break never executes, the loop completes its traversal normally, and finally enters else.

3. How break and else relate in execution

Loop termination method Whether else executes
for iterates over all elements Yes
while condition becomes False Yes
break is executed No
The loop body executes continue Yes, provided it ends naturally afterward
The loop body executes pass Yes, provided it ends naturally afterward
The loop body raises an unhandled exception No
The loop body executes return to exit the function No

Note that continue only skips the current iteration; it does not terminate the entire loop, so by itself it does not prevent else from executing.

III. The Relationship Between Loop else and continue

Both continue and break change the loop's execution process, but they affect else differently.

  • break: terminates the entire loop and skips else.
  • continue: ends the current iteration and proceeds to the next; it does not affect execution of else when the loop eventually ends naturally.

Example:

for number in range(5):
    if number == 2:
        print("跳过数字 2")
        continue

    print(number)
else:
    print("所有元素处理完毕")

Output:

0
1
跳过数字 2
3
4
所有元素处理完毕

Although the iteration for the number 2 ends early, the entire for loop still iterates over all elements, so else executes normally.

Comparison of continue and break

# continue: skip the current iteration
for number in range(3):
    if number == 1:
        continue
else:
    print("循环自然结束")

# break: terminate the entire loop
for number in range(3):
    if number == 1:
        break
else:
    print("这段代码不会执行")

Output:

循环自然结束

Understanding this distinction helps avoid mistaking continue for early termination of the loop.

IV. Typical Use Cases of for-else

The most typical use of for-else is: iterate over a set of data and determine whether an item matching the condition is found.

1. Finding an Element

numbers = [12, 25, 38, 46, 59]
target = 38

for number in numbers:
    if number == target:
        print(f"找到目标:{target}")
        break
else:
    print(f"没有找到目标:{target}")

Output:

找到目标:38

If the target does not exist:

numbers = [12, 25, 38, 46, 59]
target = 100

for number in numbers:
    if number == target:
        print(f"找到目标:{target}")
        break
else:
    print(f"没有找到目标:{target}")

Output:

没有找到目标:100

Here, else serves as a “not found” branch.

It does not require an extra flag variable to record the search result.

2. Checking Whether Certain Data Exists in a List

For example, check whether an administrator exists in the user list:

users = [
    {"name": "Alice", "role": "user"},
    {"name": "Bob", "role": "user"},
    {"name": "Charlie", "role": "admin"},
]

for user in users:
    if user["role"] == "admin":
        print(f"发现管理员:{user['name']}")
        break
else:
    print("没有管理员")

If an administrator is found during traversal, end the search with break.

If all users have been checked and no administrator is found, execute else.

3. Determining Whether a Number Is Prime

Determining whether an integer is prime is a classic use case of for-else.

A prime number is an integer greater than 1 that is divisible only by 1 and itself.

number = 29

if number <= 1:
    print(f"{number} 不是质数")
else:
    for divisor in range(2, int(number ** 0.5) + 1):
        if number % divisor == 0:
            print(f"{number} 不是质数")
            break
    else:
        print(f"{number} 是质数")

Output:

29 is a prime number

The logic here is:

  1. Start from 2 to look for possible factors.
  2. You only need to check up to the integer square root.
  3. If a factor that divides it evenly is found, it is not a prime number, so execute break.
  4. If all candidate factors have been checked and break was not triggered, execute else, indicating that it is a prime number.

Why do you only need to check up to the square root?

If an integer can be factored into the product of two integers greater than 1, then at least one of these two factors is not greater than its square root.

Therefore, there is no need to check up to number - 1.

4. Checking Whether a File Exists in the Directory Listing

files = [
    "config.yaml",
    "README.md",
    "main.py",
    "requirements.txt",
]

target = "main.py"

for filename in files:
    if filename == target:
        print(f"找到文件:{filename}")
        break
else:
    print(f"文件不存在:{target}")

This approach is suitable for simple linear searches.

If you need to frequently query a large number of filenames, consider using a set or dictionary to improve query efficiency.

5. Typical Use Cases of while-else

while-else is commonly used in retry mechanisms, status polling, and conditional waiting.

1. Retrying Operations

Suppose an operation can be executed at most 3 times; if it keeps failing, output a final failure message.

attempts = 0
max_attempts = 3

while attempts < max_attempts:
    attempts += 1

    print(f"正在尝试第 {attempts} 次")

    success = False

    if success:
        print("操作成功")
        break
else:
    print("多次尝试后仍然失败")

Output:

Attempt 1
Attempt 2
Attempt 3
Still failed after multiple attempts

Execution process:

  • Each loop first increments the number of attempts.
  • If the operation succeeds, execute break.
  • If all attempts fail, attempts reaches the maximum value.
  • The while condition becomes false, and the loop ends naturally.
  • Execute else, outputting the final failure message.

Note here: success in the example is only a simulated result; in real projects, you usually need to call the actual operation and handle exceptions.

2. Simulating Task Status Polling

For example, waiting for a task to complete:

import time

status = "running"
max_checks = 5
checks = 0

while checks < max_checks:
    checks += 1

    print(f"第 {checks} 次检查,任务状态:{status}")

    if status == "completed":
        print("任务执行成功")
        break

    time.sleep(1)
else:
    print("等待超时,任务仍未完成")

If the task completes during the checks, execute break and skip else.

If the maximum number of checks is reached and the task is still not complete, the loop ends naturally, and else is executed.

In real projects, polling also needs to consider:

  • Request timeout.
  • Network exceptions.
  • Maximum wait time.
  • Polling interval.
  • Task failure status.
  • Task cancellation status.

while-else is only responsible for expressing control flow; it does not automatically implement timeout, retry, or exception handling mechanisms.

3. Input Validation and Loop Exit

while True:
    password = input("请输入密码:")

    if len(password) >= 8:
        print("密码长度符合要求")
        break

    print("密码至少需要 8 个字符")
else:
    print("输入结束")

In this code, while True is an infinite loop, and it can only be exited by executing break.

Therefore, as long as this code runs normally, else will not be executed.

This example also shows that while-else does not mean that every while loop is suitable for using else.

If a loop is designed so that it must exit via break, then there is usually no need to add a loop else.

VI. Loop else vs. Flag Variables

Without a loop else, developers often use a flag variable to record the search result.

1. Using a Flag Variable

numbers = [10, 20, 30, 40]
target = 30

found = False

for number in numbers:
    if number == target:
        found = True
        print(f"找到目标:{target}")
        break

if not found:
    print(f"没有找到目标:{target}")

This approach works, but it requires maintaining the found state separately.

2. Using Loop else

numbers = [10, 20, 30, 40]
target = 30

for number in numbers:
    if number == target:
        print(f"找到目标:{target}")
        break
else:
    print(f"没有找到目标:{target}")

Both approaches can implement the same search logic.

However, in simple scenarios where you exit on a successful search and reach the end of the iteration without finding the target, the loop else is more direct.

3. How to Choose Between the Two Approaches

Comparison Dimension Flag Variable Loop else
Extra state Requires maintaining a variable No extra flag needed
Code structure Conditional logic is scattered Failure logic is centralized
Use cases Multiple states need to be recorded Primarily determines whether there was an early exit
Flexibility Higher Better suited to simple loop control
Readability Depends on variable design Suited to clear search logic

If the business logic needs to record multiple states at the same time—such as whether the target was found, whether it timed out, or whether an error occurred—then a flag variable or an explicit state object may be more appropriate.

Do not force a rewrite of complex logic just to use else.

VII. Execution Mechanism of Loop else

The execution mechanism of the loop else can be understood by looking at the two exit paths of a loop.

1. Normal Completion Path

Take a for loop as an example:

for item in [1, 2, 3]:
    print(item)
else:
    print("循环结束")

When the iterator is exhausted, the for loop ends normally, and then else is executed.

2. Early Exit via break

for item in [1, 2, 3]:
    if item == 2:
        break

    print(item)
else:
    print("循环结束")

When break is executed, control flow leaves the loop directly and does not enter else.

3. Control Flow Diagram

flowchart TD
    A["Enter the loop"] --> B["Execute the loop body"]
    B --> C{"Execute break?"}
    C -->|Yes| D["Exit the loop immediately"]
    C -->|No| E{"Is there another iteration?"}
    E -->|Yes| B
    E -->|No| F["Execute the else block"]
    D --> G["Execute the code after the loop"]
    F --> G

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px