Python if-else
Condition
if-else
statements let your program make decisions — it executes different blocks of code based on whether a condition is true or false.
Basic Syntax
if condition:
# code block if condition is True
else:
# code block if condition is False
- The condition is an expression that evaluates to
True
or False
.
- The indented code under
if
runs only when the condition is True
.
- The indented code under
else
runs if the condition is False
.
Example 1: Simple if-else
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are an adult.
Explanation:
- If
age
is 18 or more, it prints "You are an adult."
- Otherwise (if
age
is less than 18), it prints "You are a minor."
Example 2: if-elif-else Ladder
When you have multiple conditions, use elif
(short for "else if"):
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
Explanation:
- Checks conditions from top to bottom.
- Once a true condition is found, the corresponding block runs, and the rest are skipped.
- Here,
marks >= 75
is true, so it prints "Grade: B".
Key Points:
- The
else
block is optional.
- Python requires a colon
:
after if
, elif
, and else
.
- Code blocks under each condition must be indented (typically 4 spaces).
- Conditions can be any expression that returns
True
or False
.
Example 3: Using Logical Operators in Conditions
temperature = 25
if temperature > 30:
print("It's hot outside.")
elif temperature >= 20 and temperature <= 30:
print("The weather is pleasant.")
else:
print("It's cold outside.")
Output:
The weather is pleasant.
Summary
- Use
if
to test a condition.
- Use
elif
for additional checks.
- Use
else
for the default case.
- Always indent the code inside these blocks.
- Use comparison operators (
==, !=, >, <, >=, <=
) to form conditions.
- Combine conditions with logical operators (
and, or, not
).