Booleans and Comparisons in Python
A boolean is a value that is either True or False, and a comparison such as 5 > 3 produces one. The six operators that compare values, ==, !=, >, <, >= and <=, are how a program asks a yes-or-no question before it decides what to do next.
Key facts
TrueandFalseare capitalized. Lowercasetrueis an undefined name.boolis a subtype ofint, soTrue == 1andTrue + Trueis2.bool()returnsFalseforFalse,None, zero of any number type, and empty strings and collections. Almost everything else isTrue.==compares values andiscompares identity. UseisforNonechecks, not to compare values.
What is a boolean in Python?
A boolean is one of two values, True or False. Its type is bool, and a comparison such as 5 > 3 produces one without you typing True or False.
is_open = True
is_full = False
print(is_open)
print(type(is_open))
print(5 > 3)
print(type(5 > 3))True <class 'bool'> True <class 'bool'>
What are the 6 comparison operators in Python?
Equal, not equal, greater than, less than, greater than or equal, and less than or equal. Each one answers True or False when the two values can be compared, and the Python language reference also counts is, is not, in and not in as comparison operators.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 7 == 7 | True |
!= | Not equal to | 7 != 7 | False |
> | Greater than | 7 > 7 | False |
< | Less than | 7 < 7 | False |
>= | Greater than or equal to | 7 >= 7 | True |
<= | Less than or equal to | 7 <= 7 | True |
x = 7
print(x == 7)
print(x != 7)
print(x > 7)
print(x < 7)
print(x >= 7)
print(x <= 7)True False False False True True
Two equals signs compare. One equals sign assigns. Python has no ===, the strict equality operator of JavaScript and PHP, and Python's == never turns a string into a number the way JavaScript's == does.
Is True equal to 1 in Python?
Yes. bool is a subtype of int, with True worth 1 and False worth 0. That is why you can add booleans to count how many conditions held.
print(True == 1)
print(False == 0)
print(True + True)
print(isinstance(True, int))True True 2 True
How does bool() work in Python?
bool() converts any value to True or False. False, None, zero and empty values count as False, and almost everything else counts as True. Values that count as True are called truthy, and values that count as False are called falsy. Python applies the same rule whenever a value is used as a condition, as in the if statement of the next lesson.
Counts as False | Counts as True |
|---|---|
False, None, 0, 0.0, "", [], (), {}, set() | Almost every other value, including "0", " " and [0] |
print(bool(0), bool(42))
print(bool(""), bool("hi"))
print(bool([]), bool([1, 2]))
print(bool(None))False True False True False True False
What is the difference between == and is?
== asks whether two values are equal, and is asks whether they are the same object in memory. Two separate lists with the same contents are equal but not identical. Beginners mostly need is for one job, checking for None, because there is only ever one None object.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
nothing = None
print(nothing is None)True False True
Can I chain comparisons and compare strings?
Yes to both. 18 <= age < 65 means 18 <= age and age < 65, so both comparisons must be true. Strings compare one character at a time by each character's number in Unicode, the standard that numbers every character. That gives alphabetical order for unaccented letters of the same case and puts capitals first.
age = 25
print(18 <= age < 65)
print("apple" < "banana")
print("Zebra" < "apple")
print("abc" == "ABC")True True True False
"Zebra" < "apple" is True because the capitals A to Z come before the lowercase a to z in the Unicode table. Compare lower() versions when case shouldn't matter.
Common mistakes with booleans in Python
Two of these boolean mistakes come down to a single character. One is a missing = and the other a lowercase t, which is why they hide so well.
- SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? A single
=in a condition. Python 3.10 and later suggest==, which is the fix. The other suggestion,:=, stores a value instead of comparing, so the condition would pass whenever that value counts as True. - NameError: name 'true' is not defined. Did you mean: 'True'? The boolean is
Truewith a capital T. - TypeError: '<' not supported between instances of 'str' and 'int'. Text from
input()compared with a number. Convert withint()first. - Comparing with
== Truein a condition. For a real boolean,if x:does the same job and is the usual style. For other values the two can differ.if 2:runs, but2 == TrueisFalse, while1 == Trueand1.0 == Trueare bothTrue.
An if line runs the indented line under it only when its condition counts as True, and the next lesson covers it in full. Run both examples to see the errors.
x = 5
if x = 5:
print("five") File "main.py", line 2
if x = 5:
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?print("10" < 9)Traceback (most recent call last):
File "main.py", line 1, in <module>
print("10" < 9)
^^^^^^^^
TypeError: '<' not supported between instances of 'str' and 'int'Exercise
Complete the two print lines. The first prints whether age is at least 18, which is False. The second uses one chained comparison to print whether age is between 13 and 19 inclusive, which is True.
age = 17
print()
print()
False True
Show the solution
age = 17
print(age >= 18)
print(13 <= age <= 19)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
print(True + True + False)Booleans are integers underneath, so True counts as 1 and False as 0.
-
2What does this program print?
print(bool("False"))A string counts as False only when it is empty. "False" is a non-empty string, so bool() returns True.
-
3Which operator checks that two values are NOT equal?
!= is the not-equal operator. <> was removed in Python 3 and the others were never valid.
-
4What does this program print?
x = 10 print(5 < x < 15)Chained comparisons work in Python. 5 < x < 15 means 5 < x and x < 15, and both hold.
-
5Which None check does PEP 8 recommend?
x == None also gives True when x is None, but PEP 8 recommends is None, because there is only one None object. x = None assigns a value instead of checking one.