Chapter 3

Selection

FREE Selection β€” if, elif, else
Article Β· 15 min
πŸ“ Homework 12

In real life, we make decisions every day: "If it's raining, take an umbrella. Otherwise, wear sunglasses."

In programming, we use selection statements to make decisions. Python gives us if, elif, and else.


🧠 The if Statement

Syntax:

if condition:
    # code runs if condition is True

Example:

age = 18
if age >= 18:
    print("You are an adult.")   # βœ… This runs

age = 15
if age >= 18:
    print("This won't print")    # ❌ Condition is False

πŸ”‘ Notice the colon : at the end of the if line, and the indentation (4 spaces) before print. Python uses indentation to know which code belongs to the if.

1
Practice 1
✏️ Try it yourself!
1 Code
Write an if statement that prints "You passed!" if score is 50 or more.
2 Code
Write an if statement that prints "Even number" if a number is divisible by 2.

🧠 if...else

Syntax:

if condition:
    # runs if True
else:
    # runs if False

Example:

score = 45
if score >= 50:
    print("Pass βœ…")
else:
    print("Fail ❌ β€” better luck next time!")
2
Practice 2
✏️ Try it yourself!
1 Code
Ask the user for a number. Print "Even" if it's even, "Odd" otherwise.
2 Code
Ask for the user's age. Print "Adult" if 18+, "Minor" otherwise.

🧠 if...elif...else Chain

Syntax:

if condition1:
    # runs if condition1 is True
elif condition2:
    # runs if condition1 is False and condition2 is True
else:
    # runs if none of the above are True

Example β€” grade calculator:

mark = 75

if mark >= 90:
    grade = "A*"
elif mark >= 80:
    grade = "A"
elif mark >= 70:
    grade = "B"
elif mark >= 60:
    grade = "C"
else:
    grade = "D"

print(f"Your grade is {grade}")  # B
πŸ’‘ Key Rule: Python checks conditions from top to bottom. The moment one condition is True, it runs that block and skips the rest. Order matters!
3
Practice 3
✏️ Try it yourself!
1 Code
Ask the user for a number and print "Positive", "Negative", or "Zero".
2 Code
Ask for a score (0-100) and print: A (β‰₯80), B (β‰₯60), C (β‰₯40), or D (<40).
3 Code
Ask for a temperature and print "Hot" (>30), "Warm" (>20), "Cool" (>10), or "Cold".

🎯 Logical Operators: and, or, not

Syntax:

if condition1 and condition2:   # both True
if condition1 or condition2:    # at least one True
if not condition:               # the opposite

Examples:

age = 20
has_ticket = True

if age >= 18 and has_ticket:
    print("Welcome to the show! 🎭")

if age < 12 or age > 65:
    print("You get a discount! πŸŽ‰")

if not has_ticket:
    print("Please buy a ticket first.")
4
Practice 4
✏️ Try it yourself!
1 Code
Write a condition that checks if x is between 10 and 20 (inclusive).
2 Code
Ask the user for their age and whether they have a licence. Print "You can drive" if 18+ AND has licence.
3 Code
Check if a number is NOT a multiple of 5.

πŸ”— Relational Operators

PythonMeaningPseudocode
==Equal to=
!=Not equal to<>
<Less than<
<=Less/equal<=
>Greater than>
>=Greater/equal>=

πŸͺ† Nested IF Statements

Syntax β€” an if inside an if:

if outer_condition:
    if inner_condition:
        # both are True

Example:

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Welcome! πŸŽ‰")
    else:
        print("Need ID first.")
else:
    print("Too young.")

πŸ”‘ Each level of nesting adds 4 more spaces. Keep it to 3 levels max in exams!

5
Practice 5
✏️ Try it yourself!
1 Code
Ask for a number. If it's positive, check if it's even or odd and print accordingly.
2 Code
Write a program that asks for a score. If 40+, check if it's a Distinction (80+), Merit (60+), or Pass.
FREE Validation, Test Data &amp; Trace Tables
Article Β· 15 min
πŸ“ Homework 12

Writing code is only half the story. You also need to check inputs are correct and test your program thoroughly. Let's look at three key IGCSE topics.


βœ… Validation β€” Checking Input Data

Validation checks if data is reasonable and complete before the program uses it.

1. Range check β€” is the value within limits?

age = int(input("Enter age (0-120): "))
if age < 0 or age > 120:
    print("Invalid age! ❌")

2. Type check β€” is it the right kind of data?

try:
    score = int(input("Enter score: "))
    print(f"Valid score: {score}")
except ValueError:
    print("That's not a number! ❌")

3. Length check β€” is it the right length?

password = input("Create password (min 8 chars): ")
if len(password) < 8:
    print("Too short! ❌")

4. Presence check β€” was something entered?

name = input("Enter your name: ")
if name == "":
    print("Name cannot be empty! ❌")

5. Format check β€” does it match a pattern?

email = input("Enter email: ")
if "@" not in email or "." not in email:
    print("Invalid email format! ❌")
πŸ“ IGCSE Note: Also know verification β€” checking data hasn't changed (visual check = look at it, double entry = type it twice).
1
Practice 1
✏️ Try it yourself!
1 Code
Write validation that keeps asking for an age until a valid value (0-120) is entered.
2 Code
Add range, length, and presence checks for a registration form (name, age, password).
3 Code
Validate an email address β€” must contain @ and a dot after the @.

πŸ§ͺ Test Data β€” Normal, Abnormal, Boundary, Extreme

When testing, you need different kinds of test data:

TypeMeaningExample (age 0-120)
NormalTypical, expected values25, 0, 120
AbnormalInvalid values that should be rejected-5, 200, "hello"
BoundaryAt the edges (includes just outside)-1, 0, 120, 121
ExtremeLargest/smallest acceptable0, 120
πŸ”‘ Boundary vs Extreme: Extreme is the biggest/smallest acceptable value (0 and 120). Boundary also includes the values just outside (-1 and 121). Don't confuse them in the exam!
2
Practice 2
✏️ Try it yourself!
1 Code
Suggest normal, abnormal, boundary, and extreme test data for a program that accepts marks 0-100.
2 Code
For a password validator (min 8 characters), what boundary values would you test?

πŸ“‹ Trace Tables β€” Dry-Run Your Code

A trace table lets you step through an algorithm on paper, tracking how variable values change.

Example β€” find the highest score:

scores = [3, 7, 2]
highest = scores[0]
for i in range(1, len(scores)):
    if scores[i] > highest:
        highest = scores[i]
print(highest)
iscores[i]> highest?highestOutput
β€”β€”β€”3
17True7
22False7
β€”β€”β€”77
3
Practice 3
✏️ Try it yourself!
1 Code
Draw a trace table for linear search on [7, 2, 9, 4] looking for 9.
2 Code
Draw a trace table for bubble sort on [3, 1, 4, 2] β€” show the list after each pass.