Home » Python for-else Loops: A Tutorial

Python for-else Loops: A Tutorial

Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]

In Python, the else clause can be used with loops (for and while).

It may seem unusual because else is typically associated with if statements, but when combined with loops, it has a special meaning.

The else block in a for loop runs when the loop completes normally (i.e., it wasn't terminated early by a break statement).

1. Basic Syntax of a for-else Loop

for item in sequence:
    # Code block to execute for each item in the sequence
else:
    # Code block to execute if the loop completes normally

The else block is executed only if the for loop terminates without encountering a break statement.
If a break statement is encountered, the else block is skipped.

2. Simple for-else Loop Example

Let's start with a simple example of how the else block works in a for loop.

# Example: Simple for-else loop
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
else:
    print("The loop completed without encountering a break.")

# Output:
# 1
# 2
# 3
# 4
# 5
# The loop completed without encountering a break.

In this example:

The loop iterates through all the numbers in the list, and since there’s no break statement, the else block runs after the loop finishes.

3. Skipping the else Block with break

If a break statement is used inside the for loop, the else block is skipped.

Example: for-else Loop with break

# Example: for-else loop with break
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)
    if num == 3:
        print("Breaking the loop.")
        break
else:
    print("The loop completed without encountering a break.")

# Output:
# 1
# 2
# 3
# Breaking the loop.

In this example:

The loop terminates when it encounters the number 3 and executes the break statement.
The else block is skipped because the loop was interrupted by the break statement.

4. Common Use Case: Searching for an Item

A common use case for the for-else loop is searching for an item in a sequence. If the item is found, the loop is exited with break, and the else block is skipped. If the item is not found, the else block executes after the loop completes.

Example: Searching for an Item in a List

# Example: Searching for an item in a list using for-else
numbers = [10, 20, 30, 40, 50]
target = 25

for num in numbers:
    if num == target:
        print(f"Found the target: {target}")
        break
else:
    print(f"Target {target} not found in the list.")

# Output:
# Target 25 not found in the list.

In this example:

The loop searches for the target value 25. Since 25 is not in the list, the loop completes normally, and the else block is executed.
If the target were in the list, the else block would not be executed because the break statement would terminate the loop.

Example: Searching for an Existing Item

# Example: Searching for an existing item
target = 30

for num in numbers:
    if num == target:
        print(f"Found the target: {target}")
        break
else:
    print(f"Target {target} not found in the list.")

# Output:
# Found the target: 30

In this example:

The loop finds the target value 30, executes the break statement, and the else block is skipped.

5. for-else with Empty Sequences

If the sequence is empty, the loop body is skipped entirely, and the else block executes.

Example: for-else with an Empty List

# Example: for-else with an empty list
numbers = []

for num in numbers:
    print(num)
else:
    print("The sequence is empty, so the loop did not run.")

# Output:
# The sequence is empty, so the loop did not run.

In this example:

Since the list numbers is empty, the loop body does not execute, and the else block runs immediately.

6. for-else with a String

You can also use the for-else loop with strings. Let's search for a specific character in a string.

Example: Searching for a Character in a String

# Example: Searching for a character in a string
text = "Hello, world!"
target_char = "x"

for char in text:
    if char == target_char:
        print(f"Found the target character: {target_char}")
        break
else:
    print(f"Target character '{target_char}' not found in the string.")

# Output:
# Target character 'x' not found in the string.

In this example:

The loop searches for the character x in the string text. Since it’s not found, the else block executes after the loop completes.

Example: Searching for an Existing Character

# Example: Searching for an existing character
target_char = "w"

for char in text:
    if char == target_char:
        print(f"Found the target character: {target_char}")
        break
else:
    print(f"Target character '{target_char}' not found in the string.")

# Output:
# Found the target character: w

In this example:

The loop finds the target character w and exits early with the break statement, so the else block is skipped.

7. Nested for-else Loops

You can nest for loops, and each can have its own else block. The inner loop’s else block will run only if the inner loop completes normally, and the outer loop’s else block runs only if the outer loop completes without a break.

Example: Nested for-else Loops

# Example: Nested for-else loops
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

target = 5

for row in matrix:
    for num in row:
        if num == target:
            print(f"Found {target}!")
            break
    else:
        continue  # Continue the outer loop if the inner loop didn't break
    break  # Break the outer loop if the inner loop broke
else:
    print(f"{target} not found in the matrix.")

# Output:
# Found 5!

In this example:

The outer loop iterates through each row in the matrix, and the inner loop searches for the target in each row.
The break in the inner loop exits both loops when the target is found, and the else block is skipped.

8. Practical Example: Prime Number Checker

Let's use a for-else loop to create a prime number checker. A prime number is a number greater than 1 that has no divisors other than 1 and itself.

Example: Prime Number Checker

# Example: Prime number checker using for-else
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False  # Not a prime number
    else:
        return True  # Prime number

# Test the function
print(is_prime(11))  # Output: True (11 is a prime number)
print(is_prime(10))  # Output: False (10 is not a prime number)

In this example:

The loop checks if the number n is divisible by any number from 2 to n-1. If it finds a divisor, it returns False.
If no divisors are found, the else block executes, returning True (indicating that n is a prime number).

9. Practical Example: Finding Divisors of a Number

You can use a for-else loop to find divisors of a number and print whether the number is prime or composite.

# Example: Finding divisors of a number
def find_divisors(num):
    divisors = []
    for i in range(2, num):
        if num % i == 0:
            divisors.append(i)
            break  # Exit the loop after finding the first divisor
    else:
        print(f"{num} is a prime number.")
        return
    print(f"Divisors of {num} found: {divisors}")

# Test the function
find_divisors(13)  # Output: 13 is a prime number.
find_divisors(12)  # Output: Divisors of 12 found: [2]

In this example:

The for-else loop checks for divisors. If a divisor is found, the loop is exited with break, and the else block is skipped.
If no divisors are found, the else block executes, indicating that the number is prime.

Summary

The for-else loop in Python allows you to execute the else block if the loop completes normally without encountering a break.
If the for loop is exited with a break statement, the else block is skipped.
This pattern is commonly used for searching operations, where the else block executes if the target is not found.
The for-else loop works with any iterable, such as lists, strings, and even empty sequences.
Nested for-else loops allow you to search within complex data structures like matrices.

By understanding how to use for-else loops, you can write more flexible and efficient Python code, especially when searching for items or checking conditions in loops.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More