In Python, you use if–elif–else statements for conditional branching.
Basic Syntax
if condition1:
# block of code if condition1 is True
elif condition2:
# block of code if condition2 is True
else:
# block of code if none of the above are True
if → checks the first condition.
elif (else-if) → checks more conditions if the previous ones failed.
else → runs if no condition is True.
Example 1: Simple If-Else
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Example 2: If-Elif-Else Chain
marks = 72
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")
Example 3: Nested If
num = 15
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Negative number or zero")
Example 4: One-line If (Ternary Operator)
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Output: Even
Summary:
Use if when you want to check a condition.
Use elif when you need multiple conditions.
Use else as a fallback when no condition matches.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Basic Syntax
if→ checks the first condition.elif(else-if) → checks more conditions if the previous ones failed.else→ runs if no condition isTrue.Example 1: Simple If-Else
Example 2: If-Elif-Else Chain
Example 3: Nested If
Example 4: One-line If (Ternary Operator)
Summary:
ifwhen you want to check a condition.elifwhen you need multiple conditions.elseas a fallback when no condition matches.