Programming in Python · Lesson 6
Decision Control Structures — Programming Examples
Five runnable Python examples covering if-then, relational operators, Boolean expressions, if-then-else, nested-if, elif, fall through, and the and, or, and not operators.
Use these short, runnable examples as demonstration checkpoints. Ask students to predict the output before you run each one.
- If-then structure and the equal operator
print("Press 1 when you are ready to")
print("connect to an account agent.")
choice = input("Your choice: ")
# input() always returns a string, so compare to "1", not 1
if choice == "1":
print("Connecting you to an agent...")
print("Please have your account number ready.")
print("Bye.")
Teaching point: An if-then structure runs its indented block only when the condition is True; otherwise the program continues on the sequential path to print(“Bye.”). Use == to compare and = only to assign. Because input() always returns a string, the condition compares choice to “1” in quotes. Run it twice: once entering 1 and once entering 9.
- Relational operators, Boolean expressions, and Boolean variables
airtime = 1056 # minutes used this month
limit = 1000 # minutes included in the plan
print(airtime == limit)
print(airtime != limit)
print(airtime > limit)
print(airtime <= 2000)
# A Boolean variable holds True or False directly
over_limit = airtime > limit
vip = False
print("Over limit?", over_limit)
if over_limit:
print("You have used", airtime - limit, "extra minutes.")
if vip:
print("Transferring you to the VIP agent.")
print("Thanks for calling.")
Teaching point: Relational operators (==, !=, <, >, <=, >=) compare two operands and form Boolean expressions that evaluate to True or False. A Boolean variable such as vip already holds True or False, so if vip: is enough and if vip == True: is redundant. True and False must be capitalized.
- If-then-else and nested-if: confirming the quit option
print("Press 1 to connect to an account agent.")
print("Press 0 to quit.")
choice = input()
if choice == "0":
sure_thing = input("Are you sure you want to quit? (y/n) ")
# Inner decision: a second indent level
if sure_thing == "y":
print("Okay, you're sure. Disconnecting.")
else:
print("Connecting you to the help desk.")
else:
print("You chose option 1.")
print("Connecting you now.")
Teaching point: else gives the False branch its own statements, so exactly one of the two paths runs. Place else on its own line at the same indent level as its if, followed by a colon. The inner if-else is a nested-if structure: a decision within a decision, marked by a second indent level.
- Else-if structure and fall through: letter-grade calculator
score = int(input("Enter your quiz score: "))
# elif checks conditions in order and stops at the FIRST True one
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Letter grade:", grade)
# Separate if statements are ALL evaluated, so more than one can run
if score >= 90:
print("Above 90")
if score >= 80:
print("Above 80")
if score >= 70:
print("Above 70")
Teaching point: An elif chain checks its conditions in order and stops at the first True one, so a score of 85 gets only “B” even though it is also >= 70. Python has no fall through within an if-elif-else structure. The three separate if statements at the end are each evaluated, so 85 prints both “Above 80” and “Above 70”. Order the elif conditions from most to least restrictive.
- Conditional logical operators: shipping and discount checker
purchase = float(input("Purchase amount: $"))
vip = input("VIP member? (y/n) ") == "y"
has_coupon = input("Free-shipping coupon? (y/n) ") == "y"
on_clearance = input("Clearance item? (y/n) ") == "y"
# and: both must be True; or: at least one must be True
if (vip and purchase >= 50) or purchase > 100 or has_coupon:
print("Free shipping!")
else:
print("Shipping: $7.99")
# not flips a Boolean value
if not on_clearance:
print("A 10% discount applies.")
else:
print("Clearance items are not eligible for discounts.")
# Validate a menu choice: anything above 3 except 9 is invalid
choice = int(input("Menu choice (0-3 or 9): "))
if choice > 3 and choice != 9:
print("Invalid input.")
Build sequence:
- Start with hard-coded values for purchase and vip and a single and condition.
- Add or purchase > 100 and walk through the or truth table.
- Add the coupon and the parentheses, then discuss why (vip and purchase >= 50) is grouped.
- Add the clearance check with not, then the menu-validation check from the book.
Teaching point: and is True only when both conditions are True; or is True when at least one is True; not flips a Boolean value. Use parentheses when you combine and with or so the logic runs in the order you intend. A comparison such as input(…) == “y” stores a Boolean value directly in a variable.
Exit-ticket prompts
- What is wrong with: if choice = 1:
- Given airtime = 1056, what does airtime <= 1000 evaluate to?
- Rewrite more simply: if vip == True:
- In Example 4, what prints for a score of 70?
- Write a condition that is True when an item is not on clearance and is not jewelry, using variables on_clearance and is_jewelry.
Answer key
- It uses the assignment operator =; a condition needs the equal operator ==. Because input() returns a string, it should also compare to “1”.
- False
- if vip:
- Letter grade: C, then Above 70
- not on_clearance and not is_jewelry
Course Notes