Python’s for-else Statement: Processing When a Loop Completes Without break

It is well known that else in an if statement means “if the condition is not met.” However, it is surprisingly less known that else can also be used with loop structures like for and while in Python.

The else block in a loop has a unique and useful property: it executes “only when the loop completes normally without being interrupted by a break statement.”

This article explains how this for-else syntax works and how to write search logic without using flag variables.


目次

Basic Behavior of for-else

Usually, when searching for specific data in a loop, we implement logic like “break the loop if found.” The challenge is how to handle the case “if not found until the end.” The for-else statement allows you to write this intuitively.

Syntax:

for variable in iterable:
    if condition:
        # Interrupt the loop if the condition is met
        break
else:
    # Executed if the loop finishes without being broken

Specific Example: Searching for an Available Server

As an example, let’s create a program that attempts to connect to a list of servers in order. It succeeds if it can connect to at least one, and displays an error if it fails to connect to all servers.

import random

def try_connect(server_name):
    """
    Function to simulate connection to a server.
    (Returns True/False randomly)
    """
    # In a real implementation, network connection processing would go here
    is_success = random.choice([True, False])
    result_str = 'Success' if is_success else 'Failure'
    print(f"[{server_name}] Attempting connection... Result: {result_str}")
    return is_success

# List of backup servers
backup_servers = ["server-alpha", "server-beta", "server-gamma"]

print("--- Connection Process Start ---")

for server in backup_servers:
    # If connection is successful
    if try_connect(server):
        print(f"Connection established: {server}")
        # Goal achieved, so break the loop
        break
else:
    # Executed if the loop was never broken (All servers failed)
    print("Error: Failed to connect to all servers.")

print("--- Process End ---")

Execution Result Pattern A (Success):

--- Connection Process Start ---
[server-alpha] Attempting connection... Result: Failure
[server-beta] Attempting connection... Result: Success
Connection established: server-beta
--- Process End ---

Since break was executed at server-beta, the else block (error display) was skipped.

Execution Result Pattern B (All Failed):

--- Connection Process Start ---
[server-alpha] Attempting connection... Result: Failure
[server-beta] Attempting connection... Result: Failure
[server-gamma] Attempting connection... Result: Failure
Error: Failed to connect to all servers.
--- Process End ---

Since break was never executed until the end, the else block was executed.


Comparison with Using Flag Variables

If you implement the same logic without using for-else, you need a variable (flag) to manage the state, as shown below.

# Traditional way (Using a flag variable)
is_connected = False # Flag variable

for server in backup_servers:
    if try_connect(server):
        print(f"Connection established: {server}")
        is_connected = True # Update flag
        break

# Check flag after loop
if not is_connected:
    print("Error: Failed to connect to all servers.")

Using the for-else syntax eliminates the need for temporary variables like is_connected, making the code simpler.


Summary

  • You can add an else block to Python loops (for, while).
  • This else block runs only if the loop finishes without being breaked.
  • It is very useful when writing “search and not found” logic because it eliminates the need for flag variables.
  • Since the meaning differs from else in if statements, it is helpful to add comments for clarity.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次