CHAPTER 09 · BEGINNER4 min read

Conditions and boolean logic

Translate rules into precise tests and choose branches that handle boundary cases correctly.

Python 3.12+Free to readModule 3 of 13
YOUR NEXT SMALL WINS

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.

compare_scores.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

score_category.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

entry_rules.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

presence_checks.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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.

02

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.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why does if role == 'admin' or 'owner': enter the body even when role is 'guest'?
02A score of 90 matches both >= 80 and >= 60. How many bodies run in one if/elif chain with those tests in that order?
03Which test distinguishes a missing score represented by None from a valid zero score?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

EXPECTED OUTPUT
Heavy
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

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.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.