What is a boolean expression?
Ask a friend: "Is 5 bigger than 3?" There are only two honest answers: yes or no. A boolean expression is exactly that kind of question, written in code. When Python reads one, it acts like a judge - it looks at the evidence and hands down one of two verdicts: True or False.
True and False are special values in Python with their own type, called a boolean (or bool for short). A boolean is never a number and never text - it is a yes-or-no answer, and nothing else.
light_on = True print(type(light_on))
<class 'bool'>
Most of the time you won't type True or False yourself. Instead, you'll write a comparison, and Python will produce the boolean for you. The most common comparison is ==, which asks: "are these two values equal?"
print("Does five equal the result of 3 + 2?") print(5 == (3 + 2)) print("Does five equal six?") print(5 == 6)
Does five equal the result of 3 + 2? True Does five equal six? False
Capitalization counts! Python only recognizes True and False with a capital first letter and no quotes. Lowercase true is an error, and "True" in quotes is just text.
The six comparison operators
Python has six comparison operators. Each one asks a different question about the two values on either side of it, and each one always answers with a boolean:
Are the two values equal?
7 == 7 True
Are the two values different?
3 != 3 False
Is the left side greater?
10 > 4 True
Is the left side smaller?
10 < 4 False
Greater than or equal to?
5 >= 5 True
Less than or equal to?
6 <= 5 False
Notice the pair at the bottom: >= and <= give the value a second way to win. 5 > 5 is False (five is not bigger than itself), but 5 >= 5 is True, because "or equal to" counts.
== vs = (the classic trap)
This is the number one beginner mistake, so let's settle it early:
- A single = assigns: it stores a value in a variable. age = 18 means "make age hold 18."
- A double == compares: it asks a question and produces a boolean. age == 18 means "is age equal to 18?"
Mix them up inside a condition and Python throws the case out of court. It even suspects what you meant:
age = 18 if age = 18: print("You can vote!")
File "main.py", line 2
if age = 18:
^^^^^^^^
SyntaxError: invalid syntax. Maybe you
meant '==' or ':=' instead of '='?
age = 18 if age == 18: print("You can vote!")
You can vote!
Memory trick: one = puts something in. Two == checks if two things match - two symbols, two things being compared.
Comparing strings
Comparisons aren't just for numbers - strings can take the stand too. Two strings are equal only if they match exactly, character for character. That makes string comparisons case sensitive: "Dog" and "dog" are different strings, because D and d are different characters.
You can even use < and > with strings. Python compares them in alphabetical order, like words in a dictionary: "apple" < "banana" is True because "apple" comes first.
print("Dog" == "dog") # case matters! print("apple" < "banana") # alphabetical order print("5" == 5) # a string vs a number...
False True False
Look at that last line. "5" == 5 is False! The string "5" is a piece of text, and the number 5 is a number. They may look alike, but they are different types of value, so Python rules them not equal. This bites everyone who forgets that input() always gives you a string.
The expression courtroom
Time to hold court. Enter two values - numbers like 42 or strings in quotes like "cat" - pick one of the six operators, and the judge will strike the gavel and stamp a verdict, exactly the way Python would rule.
Expression Courtroom
numbers, or strings in quotesStoring verdicts in variables
Since every boolean expression produces a value, you can save that value in a variable - just like saving a number or a string. The pattern is variable = expression: the comparison on the right runs first, and the True or False it produces gets stored on the left.
For example, is_tall = height > 60 asks "is height greater than 60?" and files the verdict away in is_tall for later. Here's a whole program built on that pattern:
# are you Karel? name = "Tracy" is_karel = name == "Karel" print("Are you Karel? " + str(is_karel)) # can you vote? age = 19 can_vote = age >= 18 print("Can you vote? " + str(can_vote)) # is the bag oversized? weight = 75 is_oversized = weight > 60 print("Is the bag oversized? " + str(is_oversized))
Are you Karel? False Can you vote? True Is the bag oversized? True
Read the first one carefully: is_karel = name == "Karel" uses both symbols correctly. The == compares and produces False (Tracy is not Karel), then the single = stores that False in is_karel.
Where boolean expressions get used
So why do we care about True and False? Because boolean expressions are how programs make decisions. Two of the most important tools in Python are built entirely around them:
if statements
An if statement runs code only when its boolean expression is True:
if age >= 18: print("You can vote!")Learn Python conditionals
while loops
A while loop keeps repeating as long as its expression stays True:
while lives > 0: play_round()Learn while loops
And when one question isn't enough, Python lets you combine boolean expressions with the logical operators and, or, and not. That's the next tutorial: Booleans and Logical Operators in Python.
Practice
Reading boolean expressions and predicting their verdicts is a skill. Two cases for you to try:
Predict the Verdict
Before pressing Run, read each expression and predict True or False. Watch out for the string cases! Then run the program and see how many you got right.
print(12 >= 12) print(3 + 4 == 8) print("cat" != "Cat") print("10" == 10) print("melon" < "pear")
True False True False True
- 12 >= 12: "or equal to" counts, so this is True.
- 3 + 4 == 8: the math runs first. 7 == 8 is False.
- "cat" != "Cat": lowercase c and capital C are different characters, so the strings are different: True.
- "10" == 10: a string is never equal to a number: False.
- "melon" < "pear": alphabetically, m comes before p: True.
Write the Expressions
Now go the other direction: turn each everyday question into a boolean expression stored in a variable. The first one is done for you:
- Is the player tall enough for the ride (over 60 inches)?
is_tall = height > 60 - Did the student get a perfect score of 100?
- Is the password NOT equal to "1234"?
- Can the movie fit on the drive (its size is at most 700 MB)?
# 2) "equal to" means ==, never a single = is_perfect = score == 100 # 3) "not equal" is the != operator is_safe = password != "1234" # 4) "at most 700" means 700 is still OK: use <= fits_on_drive = size_mb <= 700
Your variable names can be different - what matters is picking the right operator. Notice how "at most" maps to <= and "over" maps to >.
Quick quiz
1. What does 10 != 10 evaluate to?
2. You want to check whether score equals 50, without changing it. Which line does that?
3. What does "7" == 7 evaluate to?
Keep learning Python
You can now put any two values on trial and predict the verdict. Next, learn to combine verdicts with and, or, and not - then use them to steer your programs with conditionals.