Level: Basic | Prerequisite: Week 3 (Comparison/Logic Operators, Input/Output)
Learning Goals
- Understand the flow of
if,elif,else - Follow indentation rules
- Use nested conditional statements
- Know the concept of truthy/falsy values
1. if Statement
The indented block is executed only when the condition is True.
score = 85
if score >= 60:
print("Passed!")
Indentation is 4 spaces as the standard. VS Code automatically converts Tab to 4 spaces.
2. if-else
score = 50
if score >= 60:
print("Pass")
else:
print("Fail")
3. if-elif-else
Check multiple conditions in order. Only the first True branch is executed, the rest are skipped.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
4. Nested Conditional Statements
A conditional statement inside another conditional statement. If it becomes too deep, readability drops, so limit to 2-3 levels.
age = 17
if age >= 18:
if age >= 65:
print("Preferential route")
else:
print("Adult")
else:
print("Minor")
5. Conditional Expression (Ternary Operator)
Handle branches in a single line. Use only in simple cases.
n = 7
result = "Even" if n % 2 == 0 else "Odd"
print(result) #Odd
6. Truthy/Falsy Values
In if condition:, 0, "", [], None, False are all considered false.
if "":
print("Not running")
if 0:
print("Not running")
if "hello":
print("Executed")
Key Examples (examples/)
| File | Content |
|---|---|
01_if_else.py |
Basic if/else |
02_grade.py |
if/elif/else Grade Evaluation |
03_nested.py |
Nested Conditional Statements |
04_truthy.py |
Truthy/Falsy Behavior |
⚠️ Common Mistakes
- Missing or inconsistent indentation
if x > 0: print("Positive") # IndentationError
→ Always use proper indentation. Mixing tabs and spaces can cause invisible errors.
-
=instead of==if x = 5: # SyntaxError if x == 5: #Normal -
else ifinstead ofelifPython only supportselif. (Different from Java/C'selse if) -
Use only
ifin all branchesif score >= 90: # A print("A") if score >= 80: #If 80~89, both A and B are printed! print("B")
→ Use elif for exclusive branches.
- Force parentheses in conditions
if (x > 0): #Works but not recommended if x > 0: #Python style
❓ FAQ
Q1. What if there are multiple conditions combined?
A. Use and and or. Chained comparisons like if 0 < x < 100: are also possible (Python-specific).
Q2. How many elif can be used?
A. No limit. However, if it gets longer than 5, consider other structures like dictionary mapping.
Q3. Is there no switch-case statement?
A. From Python 3.10+, match-case has been added. At the beginner level, if/elif is sufficient.
📝 Exercises (exercises/)
exercise1.md— Grade calculatorexercise2.md— Leap year checkerexercise3.md— Rock-paper-scissors (one round)
Next Week
Week 5. Loops — Automatically perform the same action multiple times