Every decision a computer makes comes down to a single question: True or False? A Boolean expression is any expression that can only produce one of these two values. Booleans are named after the mathematician George Boole, who developed the algebra of logic in the 1800s. Today his ideas power every decision in every program ever written.
The Boolean Type
In Python, the Boolean type is called bool and has exactly two values:
is_raining = True
has_umbrella = False
print(type(is_raining)) # <class 'bool'>
Boolean values can be stored in variables, passed to functions, and used directly in conditions.
Comparison Expressions
Any comparison expression produces a Boolean:
x = 10
print(x > 5) # True
print(x == 3) # False
print(x != 10) # False
print(x <= 10) # True
These are Boolean expressions — you could store the result in a variable:
is_adult = age >= 18
is_correct = user_answer == expected_answer
Boolean variables are often named with words like is_, has_, or can_ to signal that they hold a True/False value. Examples: is_logged_in, has_permission, can_fly.
Truthy and Falsy Values
Python has an interesting feature: almost any value can be used as a Boolean. Some values are considered "falsy" — they behave like False in a condition:
| Falsy values | Truthy values |
|---|---|
0 | Any non-zero number |
"" (empty string) | Any non-empty string |
[] (empty list) | Any non-empty list |
None | Almost everything else |
name = ""
if name:
print("Name provided.")
else:
print("No name given.") # runs because "" is falsy
Using truthiness makes code more readable. if items: is cleaner than if len(items) > 0: — they mean the same thing but the first reads more naturally.
Comparing Strings
Strings can be compared with == and !=:
colour = "red"
if colour == "red":
print("Stop!")
if colour != "green":
print("Not go.")
String comparisons in Python are case-sensitive. "Alice" == "alice" is False. If you want a case-insensitive comparison, convert both strings to the same case first: name.lower() == "alice".
Storing and Using Boolean Results
Because comparison expressions are just values, you can use them anywhere:
def is_even(number):
return number % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
for n in range(1, 11):
if is_even(n):
print(f"{n} is even")
Storing the comparison result in a function makes the code more readable and reusable.
Practice Problems
What is the output of: x = 7; print(x > 5 and x < 10)? Explain each step.
Show answer
Why does if username: work as a check for whether the user has entered a value?