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
TrueorFalse. - The indented code under
ifruns only when the condition isTrue. - The indented code under
elseruns if the condition isFalse.
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
ageis 18 or more, it prints "You are an adult." - Otherwise (if
ageis 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 >= 75is true, so it prints "Grade: B".
Key Points:
- The
elseblock is optional. - Python requires a colon
:afterif,elif, andelse. - Code blocks under each condition must be indented (typically 4 spaces).
- Conditions can be any expression that returns
TrueorFalse.
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
ifto test a condition. - Use
eliffor additional checks. - Use
elsefor the default case. - Always indent the code inside these blocks.
- Use comparison operators (
==, !=, >, <, >=, <=) to form conditions. - Combine conditions with logical operators (
and, or, not).
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
