Booleans and Comparisons
Programs constantly ask yes-or-no questions: Is the password correct? Is the user old enough? Is the cart empty? In Python, the answer to such a question is a boolean: either True or False.
True and False
True and False are values of type bool. Note the capital letters: true and TRUE are just unknown names, and give a NameError. Don't put them in quotes either. "True" is a string, not a boolean.
is_raining = True has_umbrella = False print(is_raining) print(type(has_umbrella))
Comparison operators
Comparison operators compare two values and give back True or False:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
< |
Less than | 3 < 5 |
True |
> |
Greater than | 3 > 5 |
False |
<= |
Less than or equal to | 5 <= 5 |
True |
>= |
Greater than or equal to | 4 >= 5 |
False |
age = 17 print(age == 18) print(age != 18) print(age < 18) print(age >= 18)
Watch out:
=assigns a value, while==compares two values. Mixing them up is one of the most common beginner mistakes.
Comparing values of different types needs care, especially with input, which is always text:
| Comparison | Result | Why |
|---|---|---|
5 == 5.0 |
True |
an int and a float compare by value |
5 == "5" |
False |
a number is never equal to a string, even if it looks the same |
5 < "10" |
TypeError |
Python can't order a number and a string |
So convert input with int() or float() before comparing it to a number.
You can store the result of a comparison in a variable:
age = 20 is_adult = age >= 18 print(is_adult)
Chaining comparisons
Python lets you chain comparisons the way you would in maths:
temperature = 22 # is it between 18 and 25? print(18 <= temperature <= 25) print(0 < temperature < 10)
18 <= temperature <= 25 means exactly the same as 18 <= temperature and temperature <= 25 (you'll meet and below). It's True only when both parts are true.
Comparing strings
Strings can be compared too. == checks for an exact match, and it's case-sensitive:
print("python" == "python")
print("Python" == "python")
print("python" == "Python".lower())Going deeper: Comparing text with < and > optional
< and > compare strings alphabetically, character by character. One surprise: all capital letters come before all lowercase letters, so "Zebra" comes before "apple":
print("apple" < "banana")
print("cat" > "car")
print("Zebra" < "apple")Convert both sides with .lower() first if you want a true alphabetical comparison.
Going deeper: Comparing decimal numbers optional
Because floats aren't always exact (remember 0.1 + 0.2 from the Numbers and Math lesson?), comparing them with == can surprise you. The math module has isclose(), which checks whether two numbers are close enough:
import math print(0.1 + 0.2 == 0.3) print(math.isclose(0.1 + 0.2, 0.3))
Logical operators: and, or, not
Combine several conditions with and, or and not:
a and bisTrueonly if both areTrue.a or bisTrueif at least one isTrue.not aflipsTruetoFalseand back.
age = 25 has_ticket = True # both are true print(age >= 18 and has_ticket) # neither is true print(age < 12 or age > 65) print(not has_ticket)
Here's how they work for every combination:
a |
b |
a and b |
a or b |
not a |
|---|---|---|---|---|
True |
True |
True |
True |
False |
True |
False |
False |
True |
False |
False |
True |
False |
True |
True |
False |
False |
False |
False |
True |
Watch out: each side of
and/ormust be a complete condition. In English you might say "x is 1 or 2", but in Pythonx == 1 or 2doesn't do that. It means(x == 1) or 2, and2on its own counts as true (see Truthiness below), so the result is neverFalse. Writex == 1 or x == 2. Likewise,age > 12 and < 20is aSyntaxError; writeage > 12 and age < 20, or12 < age < 20.
When you mix them, not is applied first, then and, then or. Use parentheses to make longer conditions easy to read:
is_weekend = True is_holiday = False is_raining = True go_to_park = (is_weekend or is_holiday) and not is_raining print(go_to_park)
Python works it out in steps:
- The parentheses first:
is_weekend or is_holidayisTrue or False, which isTrue. not is_rainingisnot True, which isFalse.- Finally
True and False, which isFalse. No park today.
Truthiness
Python can treat any value as true or false. Use bool() to see how a value is treated:
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False: empty string
print(bool("hi")) # True
print(bool(None)) # False
print(bool(0.0)) # FalseThe rule is simple. Zero, empty values and None are "falsy", which just means Python treats them like False. Almost everything else is "truthy", treated like True.
Falsy (treated as False) |
Truthy (treated as True) |
|---|---|
False |
True |
0 and 0.0 |
any other number, including negatives like -1 |
"" (an empty string) |
any non-empty string, even " " or "False" |
None |
Watch the strings: only a string with nothing in it is falsy. A single space, "0" and "False" all contain characters, so they're truthy. This becomes very handy with if statements in the next lesson.
Going deeper: Booleans are numbers too optional
Under the hood, True behaves like 1 and False like 0. That lets you count how many conditions are true by adding them up:
passed_math = True passed_science = False passed_english = True print(passed_math + passed_science + passed_english)
Going deeper: Checking for None with is optional
To check whether a variable holds None, Python programmers write is None rather than == None:
result = None print(result is None) print(result is not None)
== asks "do these have the same value?", while is asks "are these the very same object?". There's only ever one None, so is is the precise way to check for it. You'll see is None in later lessons, for example in Function Arguments.
Use is only for None. For numbers, strings and everything else, compare values with ==.
Exercises
Exercise 1: Voting age
Print True if age is 18 or over, otherwise False. Try changing age to check both cases.
age = 16
Use the >= operator to compare age with 18.
Exercise 2: In range
Print True if score is between 0 and 100 (inclusive). Use a chained comparison.
score = 87
Python lets you chain comparisons, like 0 <= score <= 100.
Exercise 3: Login check
A login succeeds when the username is "admin" and the password is "secret123". Print whether the login succeeds. The username check should ignore capital letters.
username = "Admin" password = "secret123"
Use .lower() on the username before comparing it with "admin".
Both checks must be true, so join them with and.
Exercise 4: Predict the output
Before you run this, predict what each line prints. Then run it to check.
print(10 > 5 and 3 > 7)
print(10 > 5 or 3 > 7)
print(not 10 > 5)
print(bool("False"))
print("abc" == "ABC".lower())Work out each line on its own: and needs both sides to be true, or needs just one.
Any non-empty string is truthy, even the text "False".
Summary
- A boolean is
TrueorFalse, and its type isbool. - Comparison operators
==,!=,<,>,<=and>=produce booleans. Don't confuse==with=. - Comparisons can be chained:
0 <= x <= 100. and,orandnotcombine conditions. Use parentheses for clarity.- Zero, empty strings and
Noneare falsy. Most other values are truthy.
Know something worth teaching? Write your own tutorial with runnable examples and share it.