UNIHIVE

Study Hub UNIPORT COS 102

COS 102 · Problem Solving

Making decisions: selection

Conditions, comparison and logical operators, and if, elif and else in Python.

Our notes

1 min read

Conditions

A condition is an expression that is True or False.

Comparison operators: == equal, != not equal, < less than, > greater than, <= at most, >= at least.

Logical operators: and (both true), or (at least one true), not (reverses).

if, elif, else

score = int(input("Score: "))
if score >= 40:
    print("Pass")
else:
    print("Fail")

The colon and the indentation (four spaces) mark the block that belongs to each branch.

Worked example: largest of three

a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a >= b and a >= c:
    largest = a
elif b >= c:
    largest = b
else:
    largest = c
print("Largest:", largest)

Trace: 12, 30, 7 → the first test fails (12 ≥ 30 is False); 30 ≥ 7 is True, so largest = 30. Inputs 5, 5, 2 → the first test is True: 5 (ties handled).

Worked example: leap year

A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400.
year = int(input("Year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")

2024 → leap; 1900 → not leap (divisible by 100 but not 400); 2000 → leap.

Truth table for and / or

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

Testing selection

Test every branch and every boundary: for "score ≥ 40" try 39, 40 and 41, and unusual inputs such as 0, 100 and a negative number.

Exams usually ask

  • Write a program with if/elif/else for grading, tax bands or the largest number.
  • Evaluate a compound condition for given values.

Common mistake

Writing = (assignment) where == (comparison) is meant, or getting the order of elif tests wrong (testing score >= 40 before score >= 70 gives every pass the same grade).

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All COS 102 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.