The Else Keyword
Whatever the earlier conditions did not catch ends up in the else block.
Python runs it only after the if condition, and any elif conditions, have all turned out False.
Example
if, elif, and else to compare two variables and print which is greater or if they are equal.
Output: complete Python program
a = 200
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")
Else Without Elif
An else does not need an elif before it.
That gives you a plain choice between two paths. When the condition holds, the first block runs; when it doesn't, the else block runs instead.
Example
if and else (without elif) to check if b is greater than a.
Output: complete Python program
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
How Else Works
Think of else as the default action, a "catch-all" for every case that your if and elif statements left uncovered. It runs when all the conditions before it were false.
Note: Nothing can follow an else in the chain, so it always comes last and no elif may appear after it.
Example
if and else.
Output: complete Python program
number = 7
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Complete If-Elif-Else Chain
Together, if, elif and else give you a complete decision-making structure.
Example
if, elif, and else into hot, warm, cool, or cold.
Output: complete Python program
temperature = 22
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
Because else takes over when no earlier condition was true, it makes a good safety net. That is handy for handling errors, validating data and supplying default values.
Example
if and else.
Output: complete Python program
username = "Emil"
if len(username) > 0:
print(f"Welcome, {username}!")
else:
print("Error: Username cannot be empty")