Python • Control Flow

Boolean Expressions — Use boolean expressions and parentheses to control logic

Master the art of combining True and False values to make your programs think and decide.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Every time you unlock your phone with a passcode, a program is silently asking a question: "Does the entered code match the stored code?" The answer is either yes or no — True or False. This simple idea of two-valued logic powers every decision a computer makes, from filtering search results to launching rockets. The mathematical foundation behind it dates back nearly two centuries.

1847 • George Boole Publishes Boolean Algebra

English mathematician George Boole published The Mathematical Analysis of Logic, introducing an algebra where variables take only two values: true and false. He showed that logical reasoning could be expressed with mathematical equations.

1938 • Claude Shannon Links Logic to Circuits

Claude Shannon's MIT thesis demonstrated that Boolean algebra could model electrical switching circuits. This breakthrough connected abstract logic to real hardware, laying the groundwork for digital computing.

1991 • Python Is Released

Guido van Rossum released Python, a language that made Boolean expressions readable and intuitive. Python's built-in True, False, and, or, and not keywords read almost like English.

2000s–Today • Boolean Logic Powers Modern Software

From social media feed algorithms to self-driving car sensors, complex Boolean expressions control billions of decisions every second. Understanding how to combine and group these expressions is a foundational programming skill.

The core challenge is this: how do you combine multiple conditions into a single expression that evaluates to exactly the right answer? And when your expression grows complex, how do you use parentheses to make sure Python evaluates each part in the correct order? That is what this lesson is all about.

SECTION 2

Core Principles & Definitions

A Boolean expression is any piece of Python code that evaluates to either True or False. These expressions serve as the brain of control flow — they determine which branch of an if statement runs, how long a while loop continues, and much more. Before diving into complex combinations, you need to understand the building blocks.

1

Comparison Operators

Operators like ==, !=, <, >, <=, and >= compare two values and return a Boolean. For example, 5 > 3 evaluates to True.
2

Logical Operators: and, or, not

and requires both sides to be True. or requires at least one side to be True. not flips True to False and vice versa. These are the glue that combines simple comparisons into powerful conditions.
3

Operator Precedence

Python evaluates not first, then and, then or. This order matters because it can change the result. Knowing the precedence helps you predict what Python will do.
4

Parentheses Override Precedence

Parentheses ( ) force Python to evaluate the enclosed expression first, just like in math class. They let you group conditions exactly the way you intend, eliminating ambiguity and bugs.
✦

KEY TAKEAWAY

Think of Boolean operators like traffic signals at an intersection. and is like needing a green light on both roads to cross safely — if either light is red, you stop. or is like needing at least one green light. not simply swaps the light's color. Parentheses are the traffic cop who overrides the default signal timing and tells you which intersection to check first.

SECTION 3

Visual Explanation — Truth Table Diagram

The best way to understand how and, or, and not work is to see every possible combination of inputs laid out in a truth table. The following diagram maps out the results for two variables, A and B, across all three logical operators.

Truth Tables for and, or, notA and BABResultTrueTrueTrueTrueFalseFalseFalseTrueFalseFalseFalseFalseA or BABResultTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalsenot AAResultTrueFalseFalseTrueQuick Summaryand → True only when BOTH inputs are Trueor → True when AT LEAST ONE input is Truenot → Flips the value: True becomes False, False becomes True
The three truth tables above show every possible outcome of and, or, and not. Green results indicate True and red results indicate False. Notice that and produces only one True row, while or produces only one False row.

Study the tables carefully. The and operator is the strictest — it only returns True when every condition is met. The or operator is more lenient — just one True is enough. And not simply reverses whatever it receives. These three operators, combined with comparison operators, let you express any logical condition you can imagine.

SECTION 4

How It Works — Precedence & Parentheses

Just as math has an order of operations (PEMDAS), Python follows a specific operator precedence when evaluating Boolean expressions. Understanding this order is crucial because it determines what your expression actually means — and getting it wrong is one of the most common sources of bugs.

PYTHON BOOLEAN PRECEDENCE (HIGHEST → LOWEST)

()→not→and→or( ) → not → and → or

Parentheses are always evaluated first. Then not flips values. Next, and joins pairs. Finally, or combines what remains. Comparison operators like == and > are evaluated before any logical operator.

Consider the expression True or False and False. Without parentheses, Python evaluates and first: False and False becomes False. Then True or False becomes True. But if you write (True or False) and False, the parentheses force the or to run first: True or False becomes True, and then True and False becomes False. Same tokens, completely different answer.

EXAMPLE — NO PARENTHESES

TrueorFalseandFalse→Trueor(FalseandFalse)→TrueorFalse→TrueTrue or False and False → True or (False and False) → True or False → True

Python applies and before or by default, so the implicit grouping favors the and pair.

EXAMPLE — WITH PARENTHESES

(TrueorFalse)andFalse→TrueandFalse→False(True or False) and False → True and False → False

The parentheses force or to be evaluated first, changing the final result from True to False.

💡

Pro Tip

Even when parentheses aren't strictly needed, adding them makes your code easier to read. The expression (age >= 16) and (has_permit == True) is clearer than age >= 16 and has_permit == True, even though both produce the same result. Clear code is correct code.

SECTION 5

Detailed Breakdown — Operators in Action

Now let's see how Boolean expressions appear in real Python code. Each logical operator has a distinct personality, and combining them with parentheses gives you precise control over program behavior. The diagram below shows how Python evaluates a compound expression step by step.

Evaluation Flow: age >= 16 and (has_license or has_permit)Given: age = 17, has_license = False, has_permit = Trueage >= 16 and (has_license or has_permit)Step 1: Evaluate parentheses firsthas_license or has_permitStep 2: Substitute valuesFalse or True → TrueStep 3: Back to the full expressionage >= 16 and TrueStep 4: Evaluate comparison, then andTrue and True → TrueResult: True ✓
This flowchart traces Python's evaluation of age >= 16 and (has_license or has_permit). The parentheses force the or to be resolved before the and. Each colored border represents a different evaluation stage.
OperatorSyntax ExampleReturns True When...
andx > 0 and x < 100Both conditions are True. If the left side is False, Python never even checks the right side (short-circuit evaluation).
orday == "Sat" or day == "Sun"At least one condition is True. If the left side is True, Python skips the right side.
notnot is_rainingThe operand is False. It simply inverts any Boolean value.
Parentheses ( )(a or b) and cUsed to group sub-expressions and override default precedence order.

Boolean Operators Quick Reference

ℹ

Short-Circuit Evaluation

Python is efficient: with and, if the first operand is False, the whole expression must be False — Python skips the second operand. With or, if the first operand is True, the whole expression must be True. This is called short-circuit evaluation, and it can prevent errors like dividing by zero if you write x != 0 and 10 / x > 2.

SECTION 6

Worked Example — Theme Park Ride Eligibility

A theme park roller coaster has the following rules: riders must be at least 48 inches tall, AND they must be either at least 12 years old OR accompanied by an adult. Let's write a Boolean expression for this and trace its evaluation.

Can a 10-year-old who is 50 inches tall and accompanied by an adult ride?

  1. 1

    Step 1 — Identify the Variables

    We define three variables: height = 50, age = 10, and has_adult = True. The height is in inches and the age is in years.
  2. 2

    Step 2 — Write the Boolean Expression

    Translating the rules into Python: height >= 48 and (age >= 12 or has_adult). The parentheses are critical here — without them, and would bind height >= 48 to age >= 12 first, producing the wrong logic.
  3. 3

    Step 3 — Evaluate the Parenthesized Sub-expression

    Inside the parentheses: age >= 12 or has_adult becomes 10 >= 12 or True, which simplifies to False or True.
    False or True evaluates to True
  4. 4

    Step 4 — Evaluate the Full Expression

    Now the expression simplifies to height >= 48 and True, which is 50 >= 48 and True, which is True and True.
    True and True evaluates to True — the child can ride! 🎢
  5. 5

    Step 5 — What If We Removed the Parentheses?

    Without parentheses, height >= 48 and age >= 12 or has_adult would evaluate as (height >= 48 and age >= 12) or has_adult due to and having higher precedence than or. That would mean any adult companion could ride regardless of height — not the intended logic!
    Parentheses matter: they ensure the or groups age and adult status together, as the park intends.

SECTION 7

Common Patterns & Pitfalls

Knowing the operators is one thing — using them well is another. Below is a comparison of common Boolean patterns you'll encounter, along with mistakes beginners often make and how to fix them.

Pattern / MistakeIncorrect CodeCorrect Code
Range check (is x between 1 and 10?)1 < x < 10 (valid in Python, but…)x > 1 and x < 10 — explicit and portable
Using = instead of ==if x = 5: (SyntaxError)if x == 5: — double equals for comparison
Redundant True comparisonif is_valid == True:if is_valid: — the variable is already Boolean
Missing parentheses in mixed logica or b and c — and binds first(a or b) and c — if you intend or to happen first
Negating compound expressionsnot a and b — only negates anot (a and b) — negates the entire expression

Common Boolean Expression Patterns and Pitfalls

✦

KEY TAKEAWAY

When in doubt, add parentheses. They cost nothing in performance and can save you hours of debugging. Think of them like adding punctuation to a long sentence — without commas, the meaning gets muddled. Without parentheses, your logic gets muddled in the same way.

SECTION 8

Connection to Advanced Concepts

The Boolean expressions you've learned here are the foundation for much more powerful programming patterns. As you advance, you'll encounter scenarios where Boolean logic becomes part of larger, more sophisticated structures. The table below previews how today's concepts connect to advanced topics.

This LessonAdvanced ConceptHow They Connect
if x > 0 and x < 100:List comprehension filtersYou can use Boolean expressions inside [item for item in list if condition] to filter data sets.
not operatorDe Morgan's LawsFormal rules like not (A and B) == (not A) or (not B) let you simplify and refactor complex conditions.
Short-circuit evaluationGuard clauses and defensive programmingShort-circuiting lets you write safe checks like obj is not None and obj.value > 0 — the second part only runs if the first is True.
Combining and/orBoolean functions and lambdasYou can encapsulate complex Boolean logic in functions: def is_eligible(age, height): return age >= 12 and height >= 48

From Basics to Advanced Applications

As you move into topics like exception handling, database queries, and machine learning, you'll find that every one of them relies on the same Boolean logic you've practiced here. The expressions get longer and the stakes get higher, but the core rules — and, or, not, and parentheses — never change.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why not (True and False) evaluates to True. Break down each step of the evaluation process.
Show answer
First, Python evaluates the expression inside the parentheses: True and False. Since and requires both operands to be True and one is False, the result is False. Then not flips False to True. The parentheses are essential here — without them, not True and False would evaluate as (not True) and False, giving False and False = False, a completely different answer.

Question 2: BASIC CALCULATION

What does the following expression evaluate to? x = 7; y = 3; x > 5 and y < 10. Show each step.
Show answer
Step 1: Evaluate the comparison operators first. x > 5 becomes 7 > 5 which is True. Step 2: y < 10 becomes 3 < 10 which is True. Step 3: True and True evaluates to True. Remember, comparison operators always run before logical operators, so no parentheses were needed here.

Question 3: INTERMEDIATE

Given a = True, b = False, c = True, evaluate both a or b and c and (a or b) and c. Do they produce the same result? Explain why or why not.
Show answer
For a or b and c: Python evaluates and first. b and c = False and True = False. Then a or False = True or False = True. For (a or b) and c: Parentheses first. a or b = True or False = True. Then True and c = True and True = True. In this specific case, both produce True. However, they follow different evaluation paths and would differ with other inputs — for instance, if a = True, b = False, c = False, the first returns True but the second returns False.

Question 4: APPLIED

A movie streaming service offers a discount if a user is a student OR if they are a senior (age ≥ 65), AND they must have an active subscription. Write a Boolean expression using variables is_student, age, and is_active. Then evaluate it for is_student = False, age = 70, is_active = True.
Show answer
The expression is: (is_student or age >= 65) and is_active. The parentheses group the discount eligibility conditions (student OR senior) together, and then and ensures the subscription is active. Evaluating: (False or 70 >= 65) and True → (False or True) and True → True and True → True. The user qualifies for the discount. Without parentheses, is_student or age >= 65 and is_active would still give the correct answer here, but only by coincidence — the intent would be unclear to other programmers reading your code.

Question 5: CRITICAL THINKING

De Morgan's Law states that not (A and B) is equivalent to (not A) or (not B). Verify this by building a truth table for both expressions with all four combinations of A and B. Then explain why this law is useful when refactoring complex conditions in a program.
Show answer
Truth table: When A=True, B=True: not (True and True) = not True = False; (not True) or (not True) = False or False = False. ✓ When A=True, B=False: not (True and False) = not False = True; False or True = True. ✓ When A=False, B=True: same result — True. ✓ When A=False, B=False: not (False and False) = True; True or True = True. ✓ All rows match, confirming the law. This is useful in programming because sometimes it's clearer to say "not hungry or not thirsty" instead of "not (hungry and thirsty)" — De Morgan's Law lets you choose the form that makes your code most readable without changing its behavior.

SUMMARY

Lesson Summary

Summary

A Boolean expression is any Python expression that evaluates to True or False. You build them using comparison operators like ==, >, and <, then combine them with the logical operators and (both must be True), or (at least one must be True), and not (flips the value).

Python follows a strict operator precedence: not is evaluated first, then and, then or. Parentheses override this default order and force Python to evaluate grouped sub-expressions first. Even when not strictly necessary, parentheses improve readability and prevent subtle bugs. Combined with short-circuit evaluation — where Python skips unnecessary checks — Boolean expressions give you precise, efficient control over your program's logic.

Varsity Tutors • Python • Boolean Expressions — Use boolean expressions and parentheses to control logic