🌱
Basic
if · elif · else · nested · ternary
Week 4 — Conditionals
Control program flow with if/elif/else blocks. Learn nested conditions, the ternary expression, and how to structure complex decision logic.
ifelifelseconditionsternary
Duration
⏱ 2.5 hours
Level
📊 Beginner
Prerequisite
🎯 Week 3
OUTCOME
Write a grade classifier and a simple text-based menu
What you'll learn
- 1Use if / elif / else to branch on conditions
- 2Write nested if statements
- 3Use the ternary (conditional) expression
- 4Combine multiple conditions with and/or
- 5Understand truthiness of non-boolean values
1. if / elif / else
python
score = int(input("Score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}")💡
Python uses indentation (4 spaces) to define blocks. Mixing tabs and spaces causes IndentationError.
2. Ternary Expression
A concise single-line conditional: value_if_true if condition else value_if_false.
python
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult3. Truthiness
In Python, many non-boolean values evaluate as True or False in a boolean context.
| Value | Truthiness |
|---|---|
| 0, 0.0 | False |
| "" (empty string) | False |
| [], {}, () | False |
| None | False |
| Any non-zero number | True |
| Any non-empty string/list | True |
4. Common Mistakes
- Using = instead of == in a condition — this is a SyntaxError in Python (unlike C).
- Forgetting the colon after if/elif/else — SyntaxError.
- Overlapping conditions — put the most specific (highest/lowest) check first.
💻 Examples
Run these examples and check the output yourself.
01_grade.py— Grade classifier with elif chain
CODE
score = int(input("Score (0-100): "))
if score >= 90:
print("A — Excellent")
elif score >= 80:
print("B — Good")
elif score >= 70:
print("C — Average")
elif score >= 60:
print("D — Below average")
else:
print("F — Fail")
02_season.py— Season lookup from month number
CODE
month = int(input("Month (1-12): "))
if month in [3, 4, 5]:
season = "Spring"
elif month in [6, 7, 8]:
season = "Summer"
elif month in [9, 10, 11]:
season = "Autumn"
else:
season = "Winter"
print(f"Month {month} is {season}.")
03_login.py— Simple username/password check
CODE
USER, PASS = "admin", "1234"
username = input("Username: ")
password = input("Password: ")
if username == USER and password == PASS:
print("Login successful!")
else:
print("Invalid credentials.")
📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
Triangle Classifier
Goal: Read three side lengths and classify the triangle.
Requirements
- Input three positive numbers
- Check if triangle is valid (sum of any two sides > third)
- Classify: equilateral / isosceles / scalene
Sample I/O
a: 5
b: 5
c: 8
Isosceles triangle▶Toggle solution
SOLUTION
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
if a+b > c and b+c > a and a+c > b:
if a == b == c:
print("Equilateral triangle")
elif a == b or b == c or a == c:
print("Isosceles triangle")
else:
print("Scalene triangle")
else:
print("Not a valid triangle")
Exercise 2
Rock-Paper-Scissors (1 round)
Goal: Play one round of rock-paper-scissors against a hard-coded computer choice.
Requirements
- Input: rock / paper / scissors
- Computer choice is fixed (e.g., 'rock')
- Print: win / lose / draw
▶Toggle solution
SOLUTION
computer = "rock"
user = input("rock / paper / scissors: ").lower()
if user == computer:
print("Draw!")
elif (user == "paper" and computer == "rock") or \
(user == "scissors" and computer == "paper") or \
(user == "rock" and computer == "scissors"):
print("You win!")
else:
print("You lose!")
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗