Advanced

Conditionals & branching

Make programs choose between paths using if/elif/else and comparison operators.

What you will see

False True Allow delete

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Conditionals make a program choose between paths. I branch on a score with if/elif/else, combine conditions with and/or/not, and see how equality and short-circuiting decide which way the code goes.

1

I branch on a score with if/elif/else. Only the first matching condition runs, so the correct grade prints and the program continues straight past the block.

score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C" print(grade)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
B
The first matching branch wins and stops the chain. A score of 92 would hit 'A' before ever reaching 'B'.
2

I combine conditions with and / or / not. The age-and-ticket check passes and prints Enter; the not-ticket check is false, so nothing prints, showing how simple tests build a compound one.

age = 20 has_ticket = True if age >= 18 and has_ticket: print("Enter") if not has_ticket: print("Buy a ticket")

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Enter
The first line prints; the second never does, because has_ticket is True and 'not True' is False.
3

Equality cares about type and and short-circuits. I compare a string to a number (a mismatch), compare the converted number to itself (a match), and run a safe admin check that only fires when the user really exists.

print("5" == 5) print(int("5") == 5) user = {"name": "ada", "is_admin": True} if user and user.get("is_admin"): print("Allow delete")

Before you run it, say out loud what it will print. Then open the answer.

What it prints
False True Allow delete
5 == "5" is False because an int and a str differ. Always convert before comparing when a value may arrive as text.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A condition is evaluated as true or false, and the matching branch runs before continuing.
1 Evaluate a boolean expression
↓
2 True -> run the if branch
↓
3 False -> run the else branch
↓
4 Continue after the block
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

score = 85 sets nothing on screen
if score >= 90: sets nothing on screen
grade = "A" sets nothing on screen
elif score >= 80: sets nothing on screen
grade = "B" sets nothing on screen
else: sets nothing on screen
grade = "C" sets nothing on screen
print(grade) B
Why this works
Comparison operators

Conditionals compare values with these operators:

OperatorMeans
==equal to
!=not equal
< >less / greater than
<= >=less/equal / greater/equal

age = 16
if age >= 16:
    print("Can drive (in many places)")

Note == (compare) is not the same as = (assign). Mixing them is a classic bug.

Truth tables and short-circuiting

and and or short-circuit: evaluation stops as soon as the result is known.

A and B  ->  if A is False, B is not checked
A or B   ->  if A is True,  B is not checked

This is useful for safe checks:

if user and user.is_admin:
    delete_everything()

user.is_admin only runs if user exists. That prevents crashes on empty input.

Examples

Basic if/elif/else

Branching on a score

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
print(grade)  # B

Why it works: only the first matching branch runs, then the program continues after the block.

Combining conditions

Using and / or / not

age = 20
has_ticket = True
if age >= 18 and has_ticket:
    print("Enter")

if not has_ticket:
    print("Buy a ticket")

and, or, and not let you build complex conditions from simple ones.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Writing pseudocode
Previous Lesson
Writing pseudocode
Next Lesson
Loops & iteration
Loops & iteration →