Skip to content

Latest commit

 

History

History
120 lines (94 loc) · 3.2 KB

File metadata and controls

120 lines (94 loc) · 3.2 KB

Else Suite with Loops

In Python, loops (for and while) can have an optional else block. This is a unique and advanced feature of Python that isn't commonly found in other programming languages.

How it Works

The else block in a loop executes only if the loop completes its execution normally. If the loop is terminated prematurely by a break statement, the else block will not be executed.

Syntax for for...else

for item in iterable:
    # Code to execute for each item
    if condition:
        break # This will skip the else block
else:
    # Code to execute if the loop finishes without breaking

Syntax for while...else

while condition:
    # Code to execute while condition is true
    if break_condition:
        break # This will skip the else block
else:
    # Code to execute if the condition becomes false normally

Example 1: for...else

Scenario: Searching for an item in a list

Without else (Standard approach):

numbers = [1, 3, 5, 7, 9]
target = 4
found = False

for num in numbers:
    if num == target:
        print(f"Found {target}!")
        found = True
        break

if not found:
    print(f"{target} is not in the list.")

Output:

4 is not in the list.

With else (Pythonic approach):

numbers = [1, 3, 5, 7, 9]
target = 4

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

Output:

4 is not in the list.

Notice how the else block makes the code cleaner by eliminating the need for the found flag variable.


Example 2: while...else

Scenario: Trying to connect to a server with a retry limit

retries = 3

while retries > 0:
    print(f"Attempting to connect... ({retries} retries left)")
    # Simulating a connection failure
    connection_successful = False
    
    if connection_successful:
        print("Connected successfully!")
        break
    
    retries -= 1
else:
    print("Failed to connect after all attempts. Please try again later.")

Output:

Attempting to connect... (3 retries left)
Attempting to connect... (2 retries left)
Attempting to connect... (1 retries left)
Failed to connect after all attempts. Please try again later.

In this example, since connection_successful is always False, the loop naturally exhausts retries to 0. Thus, the else block executes.


Important Notes:

  1. The else block executes when the loop condition evaluates to False (for while) or when the iterable is exhausted (for for).
  2. A continue statement does not bypass the else block. The else block will still run when the loop finishes.
  3. If the loop never runs (e.g., iterating over an empty list, or while False:), the else block will execute immediately.