Skip to lesson content

PYTHON / LESSON 5 OF 18

Decision making

Read the explanations, work through the examples, and complete the student tasks.

Learning goals

Select branches using if, elif, else, nested conditions, and match.

Explanation

An if statement runs an indented block when a condition is truthy. An elif is tested only if earlier branches did not match. else handles the remaining cases. Colons start the blocks, and indentation defines their boundaries. Use four spaces consistently.

Arrange thresholds carefully. If score >= 50 appears before score >= 90 in the same ladder, a score of 95 reaches the first branch and never gets to the higher grade. Validate the permitted range before assigning a grade.

Example 1 Grade classification

score = 85
if not 0 <= score <= 100:
    print("Invalid score")
elif score >= 90:
    print("Grade A")
elif score >= 75:
    print("Grade B")
elif score >= 50:
    print("Grade C")
else:
    print("Needs improvement")

Expected output: Grade B. The chained comparison checks both ends of the range. Exactly one branch executes.

Example 2 Nested checks and a menu

age = 20
has_id = False
if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Age requirement not met")

command = "help"
match command:
    case "start":
        print("Starting")
    case "help" | "?":
        print("Available commands: start, help, quit")
    case "quit":
        print("Goodbye")
    case _:
        print("Unknown command")

Expected output is ID required followed by the available commands. match requires Python 3.10 or later. The vertical bar means either pattern, and _ is the fallback. For this menu use quoted strings; a bare name can capture a value rather than compare it to a constant.

Common mistakes

Use == for equality comparisons, not =. Avoid deeply nested checks when a simple combined condition would be clearer. The source's hardcoded login illustrates branching only; it is not a secure authentication design.

Student tasks

1. Classify an integer as positive, negative, or zero. Test all three paths.

2. Extend the grade program and test -1, 0, 49, 50, 74, 75, 89, 90, 100, and 101.

3. Build a menu with commands add, list, and quit, plus an unknown command response. Use match.

4. Apply a 10 percent discount only when the total is at least 5000 and the customer is a member. Test each condition separately.

Completion check: demonstrate every branch and explain why boundary tests matter.