Booleans
There are exactly two literal boolean values in Python: True and False.
However, a large number of Python expressions can evaluate to True or False.
Comparison
Comparison operators are used to test equality (==), inequality (!=) and strict inequality (>, >=, <, <=):
>>> 3 == 3
True
>>> 3 < 3
False
>>> 5 >= 4
True
>>> 'apple' < 'banana'
True
= vs ==
= binds a variable to a value. E.g. x = 5
== compares two values for equality, return True if they are equal, and False otherwise.
Using = where == is expected is a very common error and Python will often flag it.
Comparing non-numeric values
You can compare things that are not numbers, such as strings or user-defined objects. This often requires supplying a comparison criterion or predicate.
By default, strings are compared alphabetically character by character. If you wanted
to based the comparison on string length instead, then you would have to be explicit
about it: len('apple') < len('banana')
Logical expressions
You can combine multiple boolean expressions using the logical operators and, or and not
to produce more complex expressions.
>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> x = 3
>>> x > 0 and x <= 5
True
>>> 0 < x <= 5 # same as above
True
>>> not x > 5
True
>>> age = 25
>>> income = 40_000
>>> if age >= 18 and income > 30_000: # BOTH must be true
... print("eligible")
...
eligible
>>> day = "Sun"
>>> if day == "Sat" or day == "Sun": # EITHER is enough
... print("weekend")
...
weekend
>>> logged_in = False
>>> if not logged_in: # flip a boolean
... print("please log in")
...
please log in
Truthiness
Python allows you to use any value in conditional statements.
The following values are considered falsy:
- zero:
0,0.0 - empty string
- empty containers:
[],(),{} None
Everything else (non-zero numbers, non-empty strings, ...) are considered truthy.
>>> name = input("Please enter your name: ")
>>> Please enter your name: Ada
>>> if name: # true if non-empty
... print("Hi", name)
...
Ada
>>> items = []
>>> if not items: # same as `len(items) == 0` but cleaner
... print("Empty")
...
Empty
Short-circuit evaluation
Python stops evaluation logical expressions as soon as the final outcome can be determined. This allows some useful idioms:
- Conditional execution without if statements:
age < 18 and print("You are too young") - Default value assignment:
user_name = user_input or 'Anonymous User' -
Sentinel: guard against errors by ensuring a given operation is allowed. For example, the following code will produce an
AttributeErrorifuseris not set:if not user.is_admin(): print("Access denied")To prevent the
AttributeError, ensureuseris set:if user is not None and not user.is_admin(): print("Access denied")
Other ways of getting booleans
is, the identity operator. Test if two variables reference the same object. Often used to test forNone- Predicates:: functions or methods that return
TrueorFalse. For example, string values have a method.isdigit()that returnsTrueif all the characters in the string are digits, orFalseotherwise. Useful for testing valid user inputs. See More on strings