Python else keyword

The else statement in Python is a key part of conditional and loop constructs. It defines a block of code that runs when no preceding conditions are met in an if or if-elif structure, or when a loop completes without being interrupted by a break statement.


Example

x = 10

if x > 15:

    print("x is greater than 15")

else:

    print("x is 15 or less")

Output:

x is 15 or less

Syntax

In Conditional Statements

if condition:

    # Code block if condition is True

else:

    # Code block if condition is False

In Loops

for item in iterable:

    # Loop body

else:

    # Executes if the loop completes without a break

while condition:

    # Loop body

else:

    # Executes if the loop completes without a break

Why Use else?

The else statement provides a fallback block that executes when all preceding conditions fail or when a loop completes naturally. It ensures your program handles all possible scenarios and adds clarity and robustness to the code. Lets see some examples:

1. Fallback Logic in Conditional Statements

Scenario: You want to handle cases not covered by if or if-elif.

age = 70

if age < 18:

    print("Minor")

elif age < 65:

    print("Adult")

else:

    print("Senior Citizen")

If age is 70, the output will be:

Senior Citizen

2. Handling Loop Completion

Scenario: You want to know when a loop completes without interruption.

For Loop Example:

for number in range(5):

    if number == 10:

        break

else:

    print("Loop completed without finding 10")

Output:

Loop completed without finding 10

While Loop Example:

count = 0

while count < 5:

    count += 1

else:

    print("While loop finished without interruption")

Output:

While loop finished without interruption

Key Notes

  1. Fallback in Conditions: The else statement ensures your program can handle all possible outcomes in an if-based decision tree.
  2. Loop Completion Logic: The else block in loops only executes if the loop exits normally without a break.
  3. Optional: The else block is not mandatory and should only be used when meaningful fallback or completion logic is required.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top