If, Elif, and Else Statements
Conditional statements let your program make decisions based on whether conditions are true or false. Python uses 'if', 'elif' (else if), and 'else' keywords.
The code block under each condition must be indented. Python uses indentation (typically 4 spaces) to define which statements belong to which block — no curly braces needed.
Example
# Simple if statement
age = 20
if age >= 18:
print("You are an adult.")
# If-else
temperature = 35
if temperature > 30:
print("It's hot outside!")
else:
print("The weather is pleasant.")
# If-elif-else chain
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade: {grade}") # Your grade: B - 'if' checks the first condition
- 'elif' checks additional conditions (you can have as many as you need)
- 'else' runs if none of the above conditions were true
- Only the first matching block executes — the rest are skipped
- Indentation (4 spaces) defines which code belongs to each block
Try Conditionals
JavaScript
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score}")
print(f"Grade: {grade}") Notes
- Python uses indentation to define code blocks. Mixing tabs and spaces will cause an IndentationError. Stick to 4 spaces for consistency.
Nested Conditions and Ternary Expressions
You can nest if statements inside other if statements to check multiple layers of conditions. However, deeply nested code can become hard to read — try to keep nesting to two or three levels at most.
Python also supports a ternary expression (conditional expression) that lets you write a simple if-else on a single line.
Example
# Nested conditions
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive.")
else:
print("You need to get a license first.")
else:
print("You are too young to drive.")
# Ternary expression (one-line if-else)
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}") # Status: adult
# Ternary in practice
num = -5
result = "positive" if num > 0 else "zero" if num == 0 else "negative"
print(result) # negative Try Nested Conditions
JavaScript
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive.")
else:
print("Get a license first.")
else:
print("Too young to drive.")
# Ternary expression
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}") Notes
- Use ternary expressions for simple conditions only. For complex logic, stick with regular if/elif/else blocks for readability.
