Skip to course content
Free course

Python Foundations / Module 4 / Boolean Logic for Clear Rules

Module 4 lesson

Boolean Logic for Clear Rules

Unit ID: M04-U01 Estimated active time: 22-30 minutes

Build one condition at a time

record_id = "R1"
hours = 8

id_is_text = type(record_id) is str
id_has_content = record_id.strip() != ""
hours_is_integer = type(hours) is int
hours_in_range = 0 <= hours <= 40

Each name answers one question. Combined rules become easier to read:

record_is_valid = (
    id_is_text
    and id_has_content
    and hours_is_integer
    and hours_in_range
)

The parentheses allow a readable multi-line expression.

and, or, and not

  • and requires both sides to be truthy.
  • or requires at least one side to be truthy.
  • not reverses truthiness.
is_available = True
is_planned = False
can_view = is_available or is_planned

Beware of meaning changes

These rules differ:

hours >= 0 and hours <= 40
hours >= 0 or hours <= 40

The second is true for almost every number because a number usually satisfies at least one side. Use and for a value that must satisfy both range boundaries.

Truthiness is not always validation

record_id = "   "
print(bool(record_id))

The result is True because the string is non-empty, even though it contains only spaces. A task-specific check is stronger:

id_has_content = record_id.strip() != ""

Exact integer type

In Python, bool is related to int, so isinstance(True, int) is true. If a rule requires an actual integer and should reject booleans, use:

hours_is_integer = type(hours) is int

This is a deliberate validation rule, not a universal replacement for isinstance().

Practice

Create booleans for a fictional score that must:

  • have exact type int;
  • be from 0 through 10; and
  • be at least 8 to pass.

Test 8, 0, 10, 11, "8", and True. Predict each result before running.

Takeaway

Good boolean names expose each rule. Combine conditions only after their separate meanings are correct. Next, branches will choose an action from those boolean results.