The else statement is used with the if statement to execute a block of code when the condition is False.
Syntax
if condition:
# code if condition is True
else:
# code if condition is False
Simple If Else Statement
Example:
age = 16
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Output:
You are a minor
How It Works
- If the condition is
True, theifblock executes. - If the condition is
False, theelseblock executes.
Example:
x = 5
if x > 10:
print("Greater than 10")
else:
print("Less than or equal to 10")
Output:
Less than or equal to 10
Using Comparison Operators
Example:
number = 20
if number == 20:
print("Number is 20")
else:
print("Number is not 20")
Output:
Number is 20
Checking User Login
Example:
is_logged_in = False
if is_logged_in:
print("Welcome")
else:
print("Please Login")
Output:
Please Login
Multiple Statements
You can place multiple statements inside both if and else blocks.
Example:
age = 20
if age >= 18:
print("Adult")
print("Can Vote")
else:
print("Minor")
print("Cannot Vote")
Output:
Adult
Can Vote
Nested If Else
Example:
age = 25
if age >= 18:
if age >= 21:
print("Access Granted")
else:
print("Limited Access")
else:
print("Access Denied")
Output:
Access Granted
Short Hand If Else
You can write an if else statement in a single line.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 20
print("Adult" if age >= 18 else "Minor")
Output:
Adult
Practical Example
Check whether a number is even or odd.
Example:
number = 7
if number % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output:
Odd Number
Common Mistake
Incorrect indentation:
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Output:
IndentationError
Correct:
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Summary
- The
elsestatement executes when theifcondition isFalse. - Only one block (
iforelse) is executed. - Multiple statements can be included in both blocks.
if elsestatements can be nested.- Short-hand
if elsecan be written in a single line.