Basic

Control Flow: Conditionals

Make decisions in code with if/elif/else and comparison operators.

What you will see

positive odd

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

Branches let a program choose. I grade a score with if/elif/else, combine conditions with and/or/not, print which values count as truthy, watch short-circuiting skip work, and nest one choice inside another to see how the pieces stack.

1

A single grade depends on where a number lands. I set a score, walk it through descending thresholds, and print only the branch that first matches.

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
Only the first matching branch runs. elif is one word, not 'else if', and every branch line ends with a colon.
2

I combine conditions into one decision. A gate checks two things at once, a second line flips a flag, and a membership test asks whether the age is on a special list, printing each outcome.

age = 20 has_id = True if age >= 18 and has_id: print("Entry allowed") if not has_id: print("Need ID") if age in [16, 18, 21]: print("Notable age") print("done")

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

What it prints
Entry allowed done
and, or, and not short-circuit: evaluation stops as soon as the result is known, so later checks may not run at all.
3

Truthy is Python's quieter rule. I feed a list of empty and non-empty values into an if and print which side each lands on, so the shapes that count as 'no' become obvious.

for item in [0, "", [], {}, None, [1]]: if item: print("truthy:", item) else: print("falsy:", repr(item))

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

What it prints
falsy: 0 falsy: '' falsy: [] falsy: {} falsy: None truthy: [1]
0, '', [], {}, None, and set() are all falsy; everything else is truthy, even a string like 'False'.
4

or can act as a fallback: give it an empty first value and it hands back the second. I pair that with a zero that short-circuits the and, and print both results to see the pattern live.

name = "" result = name or "guest" print(result) x = 0 y = x and 100 print(y)

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

What it prints
guest 0
or returns the first truthy value, and and returns the first falsy one; here y is 0, not 100, because the and stops early.
5

A choice can sit inside another choice. I test whether a number is positive first, then split positives into even or odd so the inner decision only runs when the outer one agrees.

num = 15 if num > 0: if num % 2 == 0: print("positive even") else: print("positive odd") else: print("not positive")

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

What it prints
positive odd
Indentation marks the inner block. Python reads nesting from how far left the lines sit, so keep it consistent.

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 to a boolean; exactly one branch executes based on the result.
1 Evaluate the expression -> boolean
↓
2 if True -> run first block, skip the rest
↓
3 elif -> evaluate next condition only if prior failed
↓
4 else -> runs when no branch matched
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
Indentation defines scope

Unlike languages that use {}, Python marks a block by its indentation. All lines more indented than the if belong to that branch. Mixing tabs and spaces raises IndentationError, so configure your editor to use 4 spaces.

if x:
    if y:      # nested block, one more indent
        do_thing()

The logical structure is visible purely from indentation.

Short-circuit evaluation

and returns the first falsy operand or the last operand; or returns the first truthy operand or the last. This enables compact patterns:

name = user_name or "guest"   # fallback when empty
result = value and process(value)

Because evaluation stops early, side effects in the second operand only run when needed.

Examples

Basic if/elif/else

Branching on a condition

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

Python uses indentation (not braces) to define blocks. Only the first matching branch runs.

Boolean expressions and operators

Combining conditions

age = 20
has_id = True
if age >= 18 and has_id:
    print("Entry allowed")

if not has_id:
    print("Need ID")

if age in [16, 18, 21]:
    print("Notable age")

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

Comparison and truthiness

Truthy and falsy values

if 0:            print("zero")     # never prints
if "":           print("empty")    # never prints
if []:           print("list")     # never prints
if [1]:          print("has item") # prints

0, None, "", [], {}, and set() are falsy; everything else is truthy.

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.

← Strings and Text Operations
Previous Lesson
Strings and Text Operations
Next Lesson
Loops and Iteration
Loops and Iteration →