Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The else clause is a control flow construct that dictates the execution of a code block when an associated primary condition evaluates to a falsy value (such as False, 0, None, "", or []), or when a specific block of code completes its execution without interruption. In Python, else is uniquely overloaded to function alongside conditional statements, iterative loops, and exception-handling blocks.

Conditional Statements (if / elif)

In conditional branching, the else block serves as the fallback execution path. It triggers strictly when the initial if expression, along with any subsequent elif expressions, evaluate to a falsy value. It must be the final clause in the conditional chain.
x = 10

if x > 15:
    print("x is greater than 15")
elif x == 15:
    print("x is exactly 15")
else:
    print("x is less than 15")

Iterative Loops (for / while)

When attached to a loop, the else clause executes only if the loop terminates naturally. Natural termination occurs when a for loop exhausts its iterable, or when a while loop’s condition evaluates to a falsy value. If the loop is terminated prematurely via a break statement, the else block is bypassed entirely.
items = [1, 2, 3]

for item in items:
    print(item)
    if item == 5:
        break
else:
    print("Loop exhausted the iterable without breaking")
count = 0

while count < 5:
    print(count)
    count += 1
    if count == 3:
        break
else:
    print("Loop condition became falsy without breaking")

Exception Handling (try / except)

In exception handling, the else clause defines a block of code that executes strictly if the try block completes successfully without raising any exceptions. However, the else block is also bypassed if the try block is exited prematurely via a return, break, or continue statement. Lexically, it must be positioned after all except blocks but before the finally block. Exceptions raised within the else block itself are not caught by the preceding except blocks.
numerator = 10
denominator = 2

try:
    result = numerator / denominator
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print(f"Division successful, result is {result}")
finally:
    print("Execution of try-except-else-finally block complete")
Master Python with Deep Grasping Methodology!Learn More