Skip to content

Lesson 4 of 52First steps

Conditions

Make decisions with comparisons, and/or/not, truthiness, if/elif/else, match, and one-line conditional expressions.

13 min read0/6 questions

Programs are useful because they react: show the error if the password is wrong, charge shipping if the cart is under 50, skip empty lines in a file. Every one of those is a condition. Python's version is clean and readable, with a few rules (truthiness, short-circuiting) that experienced developers rely on all the time and interviewers like to poke at.

Comparisons give you booleans

A comparison asks a yes-or-no question and gives back a bool: True or False.

OperatorMeans
==equal to
!=not equal to
< >less than, greater than
<= >=less than or equal, greater than or equal

Watch the difference between = and ==. One = assigns (ties a name to a value). Two == compares. Writing if age = 18: is a SyntaxError, which is Python doing you a favour.

Python
age = 20print(age >= 18)print(age == 21)print("apple" < "banana") # strings compare alphabeticallyprint("Zebra" < "apple") # but every uppercase letter sorts before lowercase
Output
Press Run (⌘ Enter) to see what happens.

Python also lets you chain comparisons the way you would write them in maths. 0 <= x < 10 means "x is at least 0 and less than 10", and x is only evaluated once.

Predict the outputPython

What does this print?

x = 7
print(0 <= x < 10)
print(1 < x > 5)
print(3 < x < 5)
Need a nudge? Hints walk you through it.

if, elif, else

An if statement runs a block only when its condition is true. The block is the indented lines below the colon. elif (else if) adds more conditions, and else catches everything left.

Python
temperature = 14 if temperature >= 25: print("T-shirt weather")elif temperature >= 15: print("Light jacket")elif temperature >= 5: print("Coat")else: print("Big coat and a hat")
Output
Press Run (⌘ Enter) to see what happens.

Python checks the conditions top to bottom and runs only the first branch that is true. Everything after is skipped, even if it would also be true. So order matters: put the most specific condition first.

Which branch runs for temperature = 14?
temperature>= 25T-shirt>= 15Light jacket>= 5CoatelseBig coatroot

Is 14 >= 25? False, so skip this block and try the next condition.

1/4
Predict the outputPython

What does this print?

n = 30
if n > 10:
  print("big")
elif n > 20:
  print("bigger")
else:
  print("small")
Need a nudge? Hints walk you through it.

and, or, not

Combine conditions with the logical operators:

  • a and b is true only if both are true.
  • a or b is true if at least one is true.
  • not a flips true and false.
Python
age = 25has_ticket = True if age >= 18 and has_ticket: print("Come in") if not has_ticket or age < 18: print("Sorry")else: print("Enjoy the show")
Output
Press Run (⌘ Enter) to see what happens.

These operators short-circuit: Python stops as soon as it knows the answer. In a and b, if a is false, b is never evaluated. That makes guards like if user is not None and user.is_admin: safe, because the second part only runs when there is a user.

Truthiness

An if does not need an actual bool. Every Python value is either truthy (counts as true) or falsy (counts as false). The falsy values are a short list worth memorising:

  • False and None
  • zero of any number type: 0, 0.0
  • empty collections: "", [], {}, (), set()

Everything else is truthy, including "0", " " and [0]. This lets you write if name: instead of if name != "":, which is the Pythonic style.

Quick checkPick all that apply
Which of these values are falsy? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

Here is the twist: and and or do not return True or False. They return one of their operands. a or b returns a if it is truthy, otherwise b. That gives you a neat default-value idiom: name = user_input or "Anonymous".

Predict the outputPython

What does this print?

print(0 or "" or "default")
print("a" and "b")
print(None or 0)
Need a nudge? Hints walk you through it.

The match statement

Python 3.10 added match, which compares one value against a list of patterns. For simple cases it reads like a cleaner chain of elif x == ...:

Python
def describe(status: int) -> str: match status: case 200 | 201: return "Success" case 404: return "Not found" case 500: return "Server error" case _: return "Something else" print(describe(201))print(describe(404))print(describe(418))
Output
Press Run (⌘ Enter) to see what happens.
  • case 200 | 201: matches either value (| means "or" inside a pattern).
  • case _: is the wildcard. It matches anything, like else.
  • The first matching case wins, and there is no fall-through to the next case.

match can also pull values apart. case ["go", direction]: matches a two-item list starting with "go" and puts the second item in direction. That is called structural pattern matching, and it is most useful for parsing commands and data shapes. For plain value checks, if/elif is still perfectly fine.

Quick check
In a match statement, what does case _: do?
Need a nudge? A hint rules out a wrong answer.

One-line conditional expressions

When you just need to pick between two values, use a conditional expression (often called the ternary): value_if_true if condition else value_if_false.

Python
n = 7label = "even" if n % 2 == 0 else "odd"print(label) items = 1print(f"{items} item{'' if items == 1 else 's'}")
Output
Press Run (⌘ Enter) to see what happens.

Keep these short. If you find yourself nesting one inside another, switch back to a normal if block.

Put it in order4 steps

Order these branches so each order gets the right shipping price.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

Letter grade

Write grade(score) that turns a score from 0 to 100 into a letter:

ScoreLetter
90 and up"A"
80 to 89"B"
70 to 79"C"
60 to 69"D"
below 60"F"
grade(95)  →  "A"
grade(80)  →  "B"
Python
def grade(score: int) -> str: # Check the highest band first. pass
ChallengeEasy

Leap year

Write is_leap(year) that returns True if year is a leap year in the Gregorian calendar.

The rule: a year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400.

is_leap(2024)  →  True
is_leap(1900)  →  False
is_leap(2000)  →  True
Python
def is_leap(year: int) -> bool: # divisible by 4, but not by 100 unless also by 400 pass
Key terms
truthy / falsy
How a value behaves in an if. Falsy: False, None, 0, 0.0, and empty collections. Everything else is truthy.
short-circuit
and/or stop as soon as the result is known, so the right side may never run.
elif
Another condition in an if chain. Only the first true branch runs.
chained comparison
a < b < c means a < b and b < c, with b evaluated once.
match / case
Compares a value against patterns. | means or, _ is the wildcard.
conditional expression
a if condition else b: picks one of two values in a single expression.