Conditionals
12 min
if / elif / else branch on conditions, checked top to bottom — the
first True branch runs, and the rest are skipped entirely, even if they'd
also be True.
def sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
Order matters: 'elif age < 20' only runs if age >= 13 already failed, so it effectively means 13 <= age < 20.
Python doesn't require a boolean — any value can be used in an if, and
each type has a notion of "truthy" or "falsy." Falsy values: 0, 0.0,
"" (empty string), [], {}, set(), and None. Everything else is
truthy, including non-empty containers, non-zero numbers, and the string
"False" (a non-empty string is always truthy, regardless of its
contents).
items = []
if items:
print("has items")
else:
print("empty") # this runs — empty list is falsy
Write a function `grade(score)` that returns a letter grade string for a 0-100 score: 'A' for 90+, 'B' for 80+, 'C' for 70+, 'D' for 60+, otherwise 'F'.
Write a function `classify(x)` that returns 'zero' if x is 0, 'positive even' if x is a positive even number, 'positive odd' if x is a positive odd number, and 'negative' if x is negative.
Which of these values is falsy in Python (evaluates as False in an if-statement)?
You can chain if/elif/else conditions and know which Python values are truthy vs falsy.