Conditionals & Logic
Making decisions in code
📖 Concept Recap
if/elif/else lets your code branch based on conditions.
- Comparison operators:
==!=><>=<= - Logical operators:
andornot - Critical:
=assigns a value,==compares two values. - Truthy/falsy: 0, empty string, empty list, and None are all falsy.
Python evaluates conditions top-to-bottom and stops at the first True branch. Order matters!
👀 Worked Example
A temperature classifier using nested conditions:
Exercise 1 — Grade Classifier
Complete the grade classifier by filling in the threshold values. Standard scale: A=90+, B=80+, C=70+, D=60+, F=below 60.
Exercise 2 — Voter Eligibility
Write a function can_vote(age, is_citizen) that returns True only if age ≥ 18 AND is_citizen is True. Test it with four different combinations:
- age=20, is_citizen=True
- age=16, is_citizen=True
- age=25, is_citizen=False
- age=17, is_citizen=False
and to combine two conditions: return age >= 18 and is_citizenExercise 3 — FizzBuzz
Write a FizzBuzz function. For numbers 1 through 30:
- Print
"FizzBuzz"if divisible by both 3 and 5 - Print
"Fizz"if divisible by 3 only - Print
"Buzz"if divisible by 5 only - Otherwise print the number
Important: The FizzBuzz check must come first. Why?
% to check divisibility. 15 % 3 == 0 is True. Check FizzBuzz (divisible by 15) BEFORE checking Fizz or Buzz individually.Mini Project — Grade Report Calculator
Build a complete grade calculator. Given the scores below, calculate and print:
- The average score
- The letter grade for the average
- Whether the student is on honor roll (average ≥ 90)
- The highest and lowest scores
- A formatted grade report
sum(scores) / len(scores) for the average, max(scores) and min(scores) for highest/lowest. Reuse your get_letter_grade() function from Exercise 1!✅ Lab 2 Complete!
You’ve mastered conditionals, comparison operators, logical operators, and built a complete grade calculator. Decision-making is at the heart of every useful program.
Continue to Lab 3: Loops & Iteration →