Exercises: Making Decisions — Conditionals and Boolean Logic
These exercises progress from concept checks to challenging applications. All coding exercises require Python 3.12+.
Difficulty Guide: - ⭐ Foundational (5-10 min each) - ⭐⭐ Intermediate (10-20 min each) - ⭐⭐⭐ Challenging (20-40 min each) - ⭐⭐⭐⭐ Advanced/Research (40+ min each)
Part A: Conceptual Understanding ⭐
A.1. Without running the code, predict the output of each snippet. Then verify by running it.
x = 7
if x > 5:
print("A")
if x > 10:
print("B")
print("C")
A.2. What is the difference between two if statements in sequence and an if-elif chain? Explain when you'd use each, and give a scenario where they produce different results for the same input.
A.3. Evaluate each Boolean expression by hand (don't use Python). Then verify your answers.
- a)
True and False - b)
True or False - c)
not True - d)
True and True and False - e)
False or False or True - f)
not (True and False) - g)
True or False and False(watch the precedence!) - h)
(True or False) and False
A.4. Explain short-circuit evaluation in your own words. Give one example where short-circuiting prevents an error, and one example where it improves performance.
A.5. What's wrong with this code? Identify the bug and fix it.
grade = input("Enter your grade (A/B/C/D/F): ")
if grade = "A":
print("Excellent!")
Part B: Basic Conditionals ⭐-⭐⭐
B.1. Write a program that asks the user for a number and prints whether it is positive, negative, or zero.
Expected behavior:
Enter a number: -5
-5 is negative.
Enter a number: 0
0 is zero.
Enter a number: 42
42 is positive.
B.2. Write a program that asks for a year and determines whether it is a leap year. The rules are: - A year is a leap year if it's divisible by 4 - EXCEPT years divisible by 100 are NOT leap years - EXCEPT years divisible by 400 ARE leap years
Test with: 2024 (leap), 1900 (not leap), 2000 (leap), 2023 (not leap).
B.3. Write a program that asks for a temperature in Fahrenheit and gives clothing advice:
| Temperature | Advice |
|---|---|
| 90 and above | "It's hot! Wear light clothing and stay hydrated." |
| 70-89 | "Nice weather! A t-shirt should be fine." |
| 50-69 | "It's cool. Grab a jacket." |
| 32-49 | "It's cold! Wear a warm coat." |
| Below 32 | "Freezing! Bundle up — hat, gloves, heavy coat." |
B.4. Write a program that simulates a simple password check. The correct username is "admin" and the correct password is "python123". The program should:
- Check username first
- Only ask for a password if the username is correct
- Print an appropriate message for each outcome
Test with: correct credentials, wrong username, right username but wrong password.
B.5. Write a grade calculator that takes a numeric score (0-100) and prints the letter grade (A/B/C/D/F) using the scale from the chapter. Add validation: if the score is below 0 or above 100, print an error message instead of a grade.
Part C: Boolean Operators and Compound Conditions ⭐⭐
C.1. Write a program that determines whether a person can rent a car. The requirements are: - Must be at least 21 years old - Must have a valid driver's license - Must have a credit card OR a debit card with sufficient funds
Ask for each piece of information and use Boolean operators to make the decision.
C.2. A movie theater offers discounts for: - Children (under 13): $8 - Seniors (65 and over): $9 - Students (13-64 with valid student ID): $10 - Regular adult (13-64 without student ID): $14
Write a program that asks the user's age and whether they have a student ID, then prints the ticket price.
C.3. Write a program that checks whether a given year, month, and day form a valid date. Consider: - Month must be 1-12 - Day must be valid for the given month (use 28 for February — don't worry about leap years) - Year must be positive
C.4. A shipping calculator charges: - Within the same state: $5.00 - Different state, same region (e.g., both "west"): $8.50 - Different region: $12.00 - International: $25.00
Use the following region mapping: - West: CA, OR, WA, NV - East: NY, NJ, MA, PA - Central: TX, IL, OH, MN
Ask for origin and destination states (or "international") and calculate the shipping cost.
C.5. Without running the code, predict the output:
a = 5
b = 10
c = 15
if a < b and b < c:
print("ascending")
if a < b or b > c:
print("partial")
if not (a > b):
print("not reversed")
if a < b < c:
print("chained")
Now run it and check. If any answer surprised you, explain why Python produced that result.
Part D: Nested Conditionals and Decision Trees ⭐⭐-⭐⭐⭐
D.1. Write a "Crypts of Pythonia" scene where the player enters a room with three objects: a sword, a shield, and a potion. The player can pick up one item, and the outcome depends on their choice AND a randomly generated danger level (1-10). Use the random module:
import random
danger = random.randint(1, 10)
- Sword + danger >= 7: "You fight the monster and win!"
- Sword + danger < 7: "The monster was weak — overkill, but effective."
- Shield + danger >= 7: "You block the monster's attack and escape safely."
- Shield + danger < 7: "Nothing to block — you walk through peacefully."
- Potion + danger >= 7: "You drink the potion and become invisible — clever escape!"
- Potion + danger < 7: "The potion heals a scratch. Not very exciting."
- Invalid choice: "You hesitate too long. The door slams shut."
D.2. Write a program that classifies a triangle based on its three side lengths:
- First, validate that all sides are positive and satisfy the triangle inequality (the sum of any two sides must be greater than the third)
- Then classify as: equilateral (all equal), isosceles (exactly two equal), or scalene (all different)
- Bonus: also classify by angle — if a² + b² == c² (where c is the longest), it's a right triangle
D.3. A cell phone plan calculator: - Base plan: $40/month for 5 GB data - Each additional GB over 5: $10 - If customer is on a family plan, 20% discount on the base price (not on overage) - If customer has been a member for 2+ years, $5 loyalty discount (applied last)
Write a program that asks for data used (GB), whether they're on a family plan, and years of membership, then calculates the monthly bill. Show the breakdown.
D.4. Convert this deeply nested conditional to a flat if-elif-else chain that produces identical output:
temp = float(input("Temperature: "))
humid = float(input("Humidity %: "))
if temp > 90:
if humid > 60:
print("Dangerous heat — stay indoors")
else:
print("Hot but manageable")
else:
if temp > 70:
if humid > 80:
print("Muggy — use air conditioning")
else:
print("Pleasant weather")
else:
if temp > 50:
print("Cool — light jacket weather")
else:
print("Cold — dress warmly")
Part E: match/case and Advanced Patterns ⭐⭐-⭐⭐⭐
E.1. Rewrite the Crypts of Pythonia menu from Section 4.8 using match/case, but add two new options:
- Option 5: "Cast a spell" — display a list of available spells
- Option 6: "Rest" — restore health points to 100
Include a wildcard _ case for invalid inputs.
E.2. Write a simple calculator using match/case. The program asks for two numbers and an operator (+, -, *, /). Use match on the operator to perform the correct calculation. Handle division by zero.
Expected behavior:
Enter first number: 15
Enter second number: 4
Enter operator (+, -, *, /): *
15.0 * 4.0 = 60.0
E.3. Write a program that converts between units using match/case. Supported conversions:
- km to miles (multiply by 0.621371)
- miles to km (multiply by 1.60934)
- celsius to fahrenheit (C * 9/5 + 32)
- fahrenheit to celsius ((F - 32) * 5/9)
- kg to lbs (multiply by 2.20462)
- lbs to kg (multiply by 0.453592)
The user enters the value and then the conversion type (e.g., "km_to_miles").
E.4. Write a rock-paper-scissors game where the player plays against a random computer choice. Use match/case for determining the winner. Display both choices and the result (win/lose/tie).
import random
computer = random.choice(["rock", "paper", "scissors"])
Part M: Mixed Review and Integration ⭐⭐⭐-⭐⭐⭐⭐
M.1. (Spaced review — Chapter 2) Write a program that asks for the user's name, age, and favorite language, then prints a formatted profile card using f-strings. Add a conditional: if the favorite language is "Python" (case-insensitive), add "Excellent choice!" to the output.
M.2. (Spaced review — Chapter 3) Write a program that: 1. Asks for a price and a tax rate (as a percentage) 2. Validates that both are non-negative numbers 3. Calculates the total with tax 4. If the total is over $100, apply a 10% discount and show both the original and discounted totals
This combines type conversion (Ch 3), arithmetic expressions (Ch 3), and conditionals (Ch 4).
M.3. (Integration) Build an expanded grade calculator that: - Asks for three exam scores and a homework average - Validates each score is between 0 and 100 - Calculates the weighted average: exams = 60% (20% each), homework = 40% - Assigns a letter grade with +/- modifiers: - A: 93+, A-: 90-92, B+: 87-89, B: 83-86, B-: 80-82, etc. - Prints a summary with all scores, the weighted average, and the letter grade
M.4. (Challenge — Computational thinking) Design a "20 Questions" style guessing game that can identify one of 8 animals using a binary decision tree. The program asks yes/no questions and uses nested conditionals to narrow down the animal. Plan your decision tree on paper first (decomposition!), then implement it.
Animals to distinguish: dog, cat, eagle, penguin, shark, goldfish, snake, frog
Hint: Start with broad categories (mammal? bird? lives in water?) and narrow down.