Boolean
Expressions
Master True, False, and the logical operators that power every decision your Python programs make.
What Is a Boolean?
A Boolean is the simplest data type in Python. It can hold exactly one of two values: True or False. Every time your program makes a decision, it evaluates a Boolean expression behind the scenes.
Expressions That Return True or False
A Boolean expression is any expression that Python evaluates to True or False. Comparison operators are the most common way to build them.
Why Booleans Matter
Without Boolean expressions, programs would run the same way every time. Booleans give programs the ability to branch, loop, and react to different inputs.
The Three Logical Operators
Python provides three keywords to combine or invert Boolean expressions. These are the building blocks of complex logic.
Truth Tables for and, or, not
Truth tables show every possible outcome. Memorize these patterns: they never change.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
and vs or: The Key Difference
| and | or | |
|---|---|---|
| Returns True when | Both operands are True | At least one is True |
| Returns False when | Any operand is False | Both are False |
| Real-world analogy | "You need a ticket and an ID" | "Cash or credit card" |
| Short-circuits at | First False | First True |
Parentheses Control Logic
Just like in math, parentheses override the default evaluation order. Python evaluates not first, then and, then or. Parentheses let you force any grouping you want.
Operator Precedence
Python evaluates operators in a strict order from highest to lowest precedence. Parentheses always win.
How to Evaluate Step by Step
Follow this checklist every time you read or write a compound Boolean expression:
Example 1: Simple Expression
Example 2: Parentheses Change the Result
Then or: False or False → False
Then and: True and False → False
Example 3: not with Compound Logic
Example 4: Nested Parentheses
Common Mistakes
Summary Reference
| Operator | Syntax | Returns True when | Precedence |
|---|---|---|---|
| Comparisons | == != < > <= >= | Condition is met | Highest |
| not | not x | x is False | High |
| and | x and y | Both x, y are True | Medium |
| or | x or y | At least one is True | Low |
| ( ) | (expression) | Forces grouping | Overrides all |
Question 1 of 5
What does the following expression evaluate to?
\( \text{not } (\text{True and False}) \)
Question 2 of 5
Given \( x = 7 \), what does this return?
\( x > 5 \text{ or } x < 3 \text{ and } x == 7 \)
Question 3 of 5
Which operator has the highest precedence among the logical operators?
Question 4 of 5
What is the output of this code?
Question 5 of 5
Which line of code correctly checks if score is between 80 and 100 inclusive?