Conditions and boolean logic
Translate rules into precise tests and choose branches that handle boundary cases correctly.
By the end, you’ll be able to…
- Use comparisons and boolean operators to express a rule.
- Distinguish an if/elif chain from independent if statements.
- Reason about truthiness, short-circuit evaluation, and boundary values.
01Ask a question that has a precise answer
A comparison produces a boolean value: True or False. Use == for equal values, != for unequal values, and <, <=, >, or >= for ordered comparisons. One equals sign assigns; two compare. Before writing a condition, state exactly what qualifies. 'At least ten' includes ten and therefore uses >=, while 'more than ten' excludes it and uses >.
Boundary values make useful checks. If a passing score begins at 60, inspect scores 59, 60, and 61. Testing only a comfortably passing score can hide the wrong operator. Python also supports chained comparisons such as 0 <= score <= 100, which expresses a closed interval directly. Comparisons do not validate every assumption; the score should still be the intended kind of value.
02Let indentation show the selected branch
An if statement runs its indented body when its condition is true. A colon ends the header. Use four spaces consistently for each indentation level; the indentation groups instructions rather than merely decorating them. An optional else handles the remaining case. Code aligned after the whole statement runs regardless of which branch was selected.
An if/elif/else chain chooses the first matching branch, then skips the rest of the chain. Put a narrower high-score rule before a broader passing rule. Separate if statements are different: each condition is checked independently, so several bodies can execute. Choose the structure based on whether your categories are exclusive or whether several independent actions may all be appropriate.
03Combine complete conditions
Use and when both conditions must hold, or when either is sufficient, and not to reverse truth. Write both comparisons in full: role == 'admin' or role == 'owner'. The tempting expression role == 'admin' or 'owner' does not ask whether the role matches either label; the nonempty string 'owner' is truthy by itself. Membership, role in {'admin', 'owner'}, expresses that choice clearly.
and and or short-circuit: they skip a later operand when the answer is already determined. A guard such as divisor != 0 and total / divisor > 2 avoids division when the divisor is zero. These operators return one of their operands, which is not always a bool. With comparison operands, as in this lesson's rules, the operands themselves are booleans and the result is straightforward.
04Use truthiness when presence is the question
Python can test a value directly in a condition. Empty strings and collections, numeric zero, None, and False are falsey. Nonempty strings and collections are truthy. Thus if tasks asks whether there is at least one task, while if score asks whether a score is nonzero. The latter is not equivalent to checking whether a score was supplied: zero may be a valid score.
Use is None when absence is the specific condition you intend. Use a direct collection condition when emptiness is the question. Naming intermediate booleans, such as can_enter, can make a long rule easier to review. As a final self-check, explain the result for one boundary input, one ordinary input, and one empty or missing input before considering the condition finished.
The ideas worth keeping.
- Write complete comparisons and test the exact boundary values.
- An if/elif chain selects one branch; independent if statements can select several.
- Use truthiness for emptiness and explicit None checks for missing values.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Choose a shipping band
For weight = 5, set band to Light when weight is at most 2, Standard when it is above 2 and at most 5, and Heavy otherwise. Print the band. Use one if/elif/else chain.
Explore a worked solution
weight = 5if weight <= 2: band = "Light"elif weight <= 5: band = "Standard"else: band = "Heavy"print(band)The output is Standard. Reaching elif already means weight was above 2, and <= includes the upper boundary of 5.
Express an access rule
Access is allowed when the user has a ticket and at least one seat is free, or when the role is admin. Use role = 'guest', has_ticket = True, and seats = 0. Print Allowed or Wait using an explicit boolean rule.
Explore a worked solution
role = "guest"has_ticket = Trueseats = 0can_enter = (has_ticket and seats > 0) or role == "admin"if can_enter: print("Allowed")else: print("Wait")A ticket alone is insufficient when seats is zero, so the output is Wait. Parentheses emphasize that the seat condition applies to the ticket route, while an administrator has a separate route.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Choose a shipping band
For weight = 5, set band to Light when weight is at most 2, Standard when it is above 2 and at most 5, and Heavy otherwise. Print the band. Use one if/elif/else chain.
Heavy
Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
One chapter closer.
Reading is a start. Trying it yourself makes the connection.