UNIHIVE

Study Hub UNIPORT CSC 280

CSC 280 · Introduction to Computer Programming

Decisions: if, else and nested conditions

Making choices in a program with if, if-else, else-if chains and nested ifs, conditions with and/or, and common decision programs.

Our notes

1 min read

The if statement

In Python, a colon ends the condition line and the indented lines below belong to it.
score = int(input("Score: "))
if score >= 40:
    print("Pass")
else:
    print("Fail")

Else-if chains (elif)

The first true condition wins and the rest are skipped, so put the conditions in order.
if score >= 70:
    grade = "A"
elif score >= 60:
    grade = "B"
elif score >= 50:
    grade = "C"
elif score >= 45:
    grade = "D"
elif score >= 40:
    grade = "E"
else:
    grade = "F"
Trace: score 64 → fails the first test, passes "≥ 60" → B. Score 39 → F.

Combining conditions

  • and: both must be true. if age >= 16 and has_olevel: …
  • or: at least one true. if day == "Sat" or day == "Sun": print("Weekend")
  • not: reverses it.

Range test: if 0 <= score <= 100 (Python allows this chain; in most languages write score >= 0 and score <= 100).

Nested ifs

An if inside another if.
if x > 0:
    if x % 2 == 0:
        print("positive even")
    else:
        print("positive odd")
else:
    print("zero or negative")
Trace for x = 7 → positive odd.

Classic decision programs

Even or odd: if n % 2 == 0 → even.
Largest of three:
big = a
if b > big:
    big = b
if c > big:
    big = c
print(big)
Trace with a = 4, b = 9, c = 2 → big becomes 9 → prints 9.

Roots of a quadratic ax² + bx + c = 0:
d = b * b - 4 * a * c
if d > 0: two real roots (-b ± √d)/(2a)
elif d == 0: one repeated root -b/(2a)
else: complex roots (no real roots)
Worked example. a = 1, b = -5, c = 6: d = 25 - 24 = 1 > 0; roots (5 ± 1)/2 = 3 and 2.

Leap year: a year is a leap year if it is divisible by 4 and not by 100, or divisible by 400. 2024 → leap; 1900 → not; 2000 → leap.
if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0: print("Leap year")

Switch/case

Some languages (C, Java; FORTRAN's SELECT CASE) choose among many fixed values with a switch statement; Python uses elif chains (or match from Python 3.10).

Exams usually ask: write programs for pass/fail, grades, even/odd, largest of three, quadratic roots, leap years; trace nested ifs; truth of and/or conditions.

Common mistake: writing = (assignment) instead of == (comparison) in a condition, or putting a smaller limit first in an elif chain (if score >= 40 first, every pass becomes an E).

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 CSC 280 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.