Lesson 4 of 52First steps
Conditions
Make decisions with comparisons, and/or/not, truthiness, if/elif/else, match, and one-line conditional expressions.
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.
| Operator | Means |
|---|---|
== | 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.
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.
What does this print?
x = 7 print(0 <= x < 10) print(1 < x > 5) print(3 < x < 5)
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.
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.
Is 14 >= 25? False, so skip this block and try the next condition.
What does this print?
n = 30
if n > 10:
print("big")
elif n > 20:
print("bigger")
else:
print("small")and, or, not
Combine conditions with the logical operators:
a and bis true only if both are true.a or bis true if at least one is true.not aflips true and false.
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:
FalseandNone- 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.
None picked yet
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".
What does this print?
print(0 or "" or "default")
print("a" and "b")
print(None or 0)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 == ...:
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, likeelse.- 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.
match statement, what does case _: do?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.
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.
Order these branches so each order gets the right shipping price.
- Tap the steps below in the right order.
Letter grade
Write grade(score) that turns a score from 0 to 100 into a letter:
| Score | Letter |
|---|---|
| 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"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- 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/orstop 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 < cmeansa < b and b < c, withbevaluated 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.