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.
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.
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 print(18 <= temperature <= 25) # is it between 18 and 25? print(0 < temperature < 10)
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 print(age >= 18 and has_ticket) # both true print(age < 12 or age > 65) # neither is true 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 |
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)
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. 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.