PythonElse Statement
The Else Keyword
Theelse keyword catches anything which isn't caught by the preceding conditions.
Theelse statement is executed when theif condition (and anyelif conditions) evaluate toFalse.
Example
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this examplea is greater thanb,so the first condition is not true, also theelif condition is not true,so we go to theelse condition and print to screen that "a is greater than b".
Else Without Elif
You can also have anelse without theelif:
Example
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
This creates a simple two-way choice: if the condition is true, execute one block; otherwise, execute the else block.
How Else Works
Theelse statement provides a default action when none of the previous conditions are true. Think of it as a "catch-all" for any scenario not covered by yourif andelif statements.
Note: Theelse statement must come last. You cannot have anelif after anelse.
Example
Checking even or odd numbers:
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Complete If-Elif-Else Chain
You can combineif,elif, andelse to create a comprehensive decision-making structure.
Example
Temperature classifier:
if temperature > 30:
print("It's hot outside!")
elif temperature > 20:
print("It's warm outside")
elif temperature > 10:
print("It's cool outside")
else:
print("It's cold outside!")
Else as Fallback
Theelse statement acts as a fallback that executes when none of the preceding conditions are true. This makes it useful for error handling, validation, and providing default values.
Example
Validating user input:
if len(username) > 0:
print(f"Welcome, {username}!")
else:
print("Error: Username cannot be empty")

