Conditionals & boolean logic
Write if/elif/else branches with combined conditions and no redundant checks.
By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.
In short
Conditionals let a program choose what to do. Python checks if, then each elif, top to bottom, and runs only the first branch whose condition is true; else catches everything left.
Explained simply
Programs make choices all the time. Is the password right? Is the cart empty? Is the user old enough? An if statement runs a block of code only when its condition is True. Python marks the block with indentation, usually 4 spaces, instead of curly braces.
A condition is any expression that can be judged true or false. You build them from comparisons (==, !=, <, >, <=, >=), membership tests (in, not in) and the logic words and, or and not. They read almost like English: if age >= 18 and has_ticket.
elif (short for "else if") adds more options and else catches everything left over. Python checks the branches from top to bottom and runs only the first one whose condition is True. So the order of your branches matters.
Any value can be used as a condition, not just True and False. Zero, empty text, empty lists and None count as false; almost everything else counts as true. This lets you write if items: instead of if len(items) > 0:, which is shorter and is the normal Python style.
Press Play on a diagram to walk through it one step at a time.
- Step 1Check if
True? Run this block and skip the rest
- Step 2Check each elif
Only reached when every earlier test was False
- Step 3Fall to else
Runs when no condition matched
- Step 4Continue after
Exactly one branch ran, or none without else
- Comparison
- x == y, x != y
- 0 <= x < 10
- Membership
- x in items
- key in my_dict
- Identity
- x is None
- x is not None
- Truthiness
- if items:
- if not name:
- Combined
- a and b, a or b, not a
- any(...), all(...)
- True only if both sides are
- Stops at the first falsy value
- Returns that value or the last one
- True if either side is
- Stops at the first truthy value
- Returns that value or the last one
- Flips truthiness
- Always returns True or False
- Binds tighter than and and or
In depth
Short-circuiting, and what and/or really return
and and or are lazy. a and b looks at a first: if a is falsy, the answer is already known, so Python returns a without even looking at b. a or b returns a straight away if a is truthy. This is called short-circuit evaluation.
They also return one of the two values, not necessarily True or False. "" or "guest" gives "guest", and 0 and crash() gives 0 without calling crash(). That enables two common patterns. The guard: if user and user.is_admin: never touches user.is_admin when user is None. The default: name = name or "Anonymous". Be careful with the second one: it also replaces 0 and empty strings, which may be valid values.
Precedence is not, then and, then or. So a or b and c means a or (b and c). When you mix them, add parentheses; readers should never have to remember the rule.
- 1Evaluate a
Work out the left side first
- 2Is a falsy?
0, "", None, empty, or False
- 3Yes: return a
b is never evaluated
- 4No: evaluate b
Only now is the right side run
- 5Return b
The result is b itself, not a bool
Comparisons: chaining, ==, is and in
Python lets you chain comparisons the way you write them in maths: 0 <= x < 10 means 0 <= x and x < 10, with x evaluated only once.
== asks "are these values equal?" while is asks "are these the same object?". Use is only for None (and other single objects like True or a sentinel); use == for numbers, strings and everything else. 1 == 1.0 is True even though the types differ.
Strings compare letter by letter by their Unicode number, so "apple" < "banana" is True, but so is "Zebra" < "apple", because capital letters come first. Compare lower() versions when case should not matter. Ordering a string against a number with < raises TypeError, while == simply returns False.
in on a string checks for a substring: "py" in "python" is True. On a list it scans item by item; on a set or dict it is almost instant, which matters once the collection is large.
- x == 1 or x == 2 can become x in (1, 2)
- "10" == 10 is False: different types are never equal here
- not x in items works, but x not in items reads better
Simplifying redundant and nested checks
Because an elif only runs when every earlier test failed, it never needs to repeat them. After if score >= 90, the next branch can be elif score >= 75; adding and score < 90 is dead weight that can drift out of sync later.
Other simplifications come up all the time. Return a comparison directly: return n % 2 == 0 instead of an if that returns True or False. Write if is_valid: instead of if is_valid == True:. Use not to flip a test, and De Morgan's rule to tidy it: not (a and b) is the same as not a or not b.
Deep nesting is the other enemy. Guard clauses check the bad cases first and leave the function early with return or raise, so the main logic sits at the left edge instead of four levels deep. Code with fewer levels has fewer places for bugs to hide.
- if user: then if user.active: then if order:
- Main logic 3 levels deep
- else branches far from their if
- Hard to see every exit
- if not user: return early
- if not user.active: return early
- Main logic at the left edge
- Each problem handled in one line
Conditional expressions, any() and all()
When you only need to choose between two values, a conditional expression fits on one line: label = "even" if n % 2 == 0 else "odd". Read it as "even, if n is even, otherwise odd". Keep it to simple cases; nesting one inside another quickly becomes unreadable.
When a condition depends on many items, any() and all() replace a loop with a flag. any(c.isdigit() for c in password) is True if at least one character is a digit. all(score >= 50 for score in scores) is True only if every score passes. Both stop as soon as the answer is known. Note that all() of an empty collection is True, which can surprise you.
For long chains of if x == "a" ... elif x == "b" that only pick a value, a dictionary lookup is often clearer: prices.get(size, 0) does in one line what five branches did.
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Write if/elif/else branches~30m
- 2Combine conditions with and, or, not~30m
- 3Compare values and check membership~30m
- 4Simplify redundant checks~30m
Key points
- Only the first true branch runs, so order conditions from most specific to least.
- Combine tests with and, or, not; chain comparisons like 0 <= x < 10.
- Use in to test membership: if color in ("red", "green").
- Empty strings, 0, None and empty collections are falsy; most other values are truthy.
Key terms
Tap a card to flip it. 0/5 known
Examples
score = 72
if score >= 90:
grade = "A"
elif score >= 75: # no need to also check score < 90
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(grade) # C
name = ""
if not name:
print("Name is empty")Shipping rules without repeated checks
A shop charges 15.00 outside its home countries, ships free at home for orders of 50 or more, charges 4.99 otherwise, and adds 10 for express. Step 1: reject impossible input first with a guard clause. Step 2: test the most special case (abroad) first, so later branches do not need to repeat it. Step 3: the elif for free shipping only runs for home orders, so it needs no country check. Step 4: express is independent of the rest, so it gets its own if, not an elif.
def shipping_cost(total, country, express=False):
if total <= 0:
raise ValueError("total must be positive")
if country not in ("DE", "FR", "NL"):
cost = 15.0
elif total >= 50:
cost = 0.0
else:
cost = 4.99
if express:
cost += 10
return cost
print(shipping_cost(60, "DE"), shipping_cost(20, "FR", True)) # 0.0 14.99Checking a password with guard clauses and any()
Each rule is checked in its own short if that returns a clear message as soon as something fails. Step 1: check the length. Step 2: any() looks for at least one digit and stops at the first one it finds. Step 3: the same for letters. Step 4: compare a lower-cased copy with a few known weak passwords using in. Step 5: if nothing failed, the function reaches the final return. There is no nesting at all, and adding a rule means adding one more if.
def check_password(pw):
if len(pw) < 12:
return "Too short: use at least 12 characters"
if not any(c.isdigit() for c in pw):
return "Add at least one digit"
if not any(c.isalpha() for c in pw):
return "Add at least one letter"
if pw.lower() in ("password1234", "qwerty123456"):
return "Too common"
return "OK"
print(check_password("hunter2")) # Too short: ...
print(check_password("correct-horse-42")) # OKQuick reference
- 0 <= x < 10 is a chained comparison: the same as 0 <= x and x < 10
- Test for None with x is None, never x == None
- x in ("a", "b") replaces x == "a" or x == "b"
- a or b returns a if a is truthy, else b: name = name or "guest"
- Precedence: not first, then and, then or; add parentheses when mixing them
- return n > 0 instead of if n > 0: return True else: return False
- label = "even" if n % 2 == 0 else "odd" chooses a value in one line
- any(...) is True if one item passes; all(...) if every item passes (all([]) is True)
Common mistakes
- Writing if x == 1 or 2 — it is always true; write x == 1 or x == 2, or x in (1, 2).
- Using = (assignment) where you meant == (comparison).
- Repeating checks an earlier branch already ruled out.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Classify a temperature t: below 0 is "freezing", below 15 is "cold", below 25 is "mild", anything else is "hot". Write it with no redundant checks.
- Exercise 2medium
Write is_leap(year) as a single return expression. A year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400. Test 1900, 2000, 2024 and 2026.
- Exercise 3hard
Write ticket_price(age, member=False): under 3 is free, under 12 pays 5, 65 and over pays 7, everyone else pays 12. Members get 2 off any price that is not free. A negative age raises ValueError. Use guard clauses and no nesting.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Python have a switch statement?
- Since Python 3.10 it has match/case, which covers switch and more. For simple value-to-result mappings, a dictionary lookup like prices.get(size, 0) is often shorter.
- Why does Python use indentation instead of braces?
- Indentation is part of the syntax: the lines indented under an if form its block. Use 4 spaces per level and never mix tabs and spaces, or you get IndentationError or TabError.
- What is the difference between == and is?
- == checks whether two values are equal; is checks whether two names point to the very same object. Use is for None and == for everything else.
- Can I write an if statement on one line?
- if x: print(x) is valid, but style guides discourage it. To choose between two values, use a conditional expression instead: y = a if condition else b.