Python Basics — Control Flow Practice Exercises
Control Flow Practice Exercises
Test your understanding of if/elif/else, ternary operators, match-case, and truthy/falsy values.
Exercise 1: BMI Calculator
Write a program that asks for weight (kg) and height (m), calculates BMI, and prints the category.
| BMI Range | Category |
|---|---|
| < 18.5 | Underweight |
| 18.5–24.9 | Normal weight |
| 25.0–29.9 | Overweight |
| ≥ 30 | Obese |
Expected Output:
Enter weight (kg): 70
Enter height (m): 1.75
BMI: 22.9
Category: Normal weight
Solution
weight = float(input("Enter weight (kg): "))
height = float(input("Enter height (m): "))
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
print(f"\nBMI: {bmi:.1f}")
print(f"Category: {category}")
Exercise 2: Day Type Checker (match-case)
Use match-case to classify a day as “Weekday”, “Weekend”, or “Invalid”. Handle case-insensitive input.
Expected Output:
Enter a day: Saturday
Weekend!
Enter a day: MONDAY
Weekday
Enter a day: Funday
Invalid day: Funday
Solution
day = input("Enter a day: ").strip().lower()
match day:
case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
print("Weekday")
case "saturday" | "sunday":
print("Weekend!")
case _:
print(f"Invalid day: {day.title()}")
Exercise 3: Ticket Pricing
Write a program that calculates ticket price based on age, day, and membership.
Rules:
- Base price: $20
- Children (under 12): 50% off
- Seniors (65+): 40% off
- Weekends: $5 surcharge (after discount)
- Members: extra 10% off (applied last)
Expected Output:
Enter age: 10
Weekend? (yes/no): yes
Member? (yes/no): no
Base price: $20.00
Child discount (50%): -$10.00
Weekend surcharge: +$5.00
Final price: $15.00
Solution
age = int(input("Enter age: "))
is_weekend = input("Weekend? (yes/no): ").strip().lower() == "yes"
is_member = input("Member? (yes/no): ").strip().lower() == "yes"
base = 20.00
price = base
discount_label = ""
print(f"\nBase price: ${base:.2f}")
if age < 12:
discount = base * 0.50
price -= discount
print(f"Child discount (50%): -${discount:.2f}")
elif age >= 65:
discount = base * 0.40
price -= discount
print(f"Senior discount (40%): -${discount:.2f}")
if is_weekend:
price += 5
print(f"Weekend surcharge: +$5.00")
if is_member:
member_discount = price * 0.10
price -= member_discount
print(f"Member discount (10%): -${member_discount:.2f}")
print(f"Final price: ${price:.2f}")
Exercise 4: Truthy/Falsy Quiz
Without running the code, predict the output. Then verify by running it.
print("A:", bool([]))
print("B:", bool([0]))
print("C:", bool(""))
print("D:", bool(" "))
print("E:", bool(0.0))
print("F:", "hello" or "world")
print("G:", "" or "default")
print("H:", "hello" and "world")
print("I:", "" and "world")
print("J:", None or 0 or "" or [] or "found")
Solution
A: False # Empty list is falsy
B: True # Non-empty list (even with falsy element)
C: False # Empty string is falsy
D: True # String with a space is truthy
E: False # 0.0 is falsy
F: hello # or returns first truthy value
G: default # "" is falsy, so or returns "default"
H: world # and returns last value when all truthy
I: # and returns first falsy value ("")
J: found # or keeps going until it finds a truthy value
Exercise 5: Rock Paper Scissors
Build a rock-paper-scissors game where the user plays against the computer. Use match-case or if-elif to determine the winner.
Expected Output:
Choose rock, paper, or scissors: rock
Computer chose: scissors
You win! Rock beats scissors.
Solution
import random
choices = ["rock", "paper", "scissors"]
user = input("Choose rock, paper, or scissors: ").strip().lower()
computer = random.choice(choices)
print(f"Computer chose: {computer}\n")
if user not in choices:
print(f"Invalid choice: {user}")
elif user == computer:
print("It's a tie!")
else:
match (user, computer):
case ("rock", "scissors") | ("paper", "rock") | ("scissors", "paper"):
print(f"You win! {user.title()} beats {computer}.")
case _:
print(f"You lose! {computer.title()} beats {user}.")
Scoring Guide
| Exercises Completed | Level |
|---|---|
| 5/5 | Expert — Control flow mastered! |
| 4/5 | Advanced — Strong conditional logic |
| 3/5 | Intermediate — Good foundation |
| 1-2/5 | Beginner — Review the chapter concepts |
Next Chapter: Loops →