This page explains the
bool (boolean –
False) data type in Python, its basic characteristics, typical use cases, and common operations.
bool is short for boolean, meaning true/false.
There are only two possible values of the bool type:
False are case-sensitive and start with uppercase letter.
True (with capital T) is different from
true (woth lowercase t), which is not a bool and can be used freely as a variable or function name (though not recommended for code readability).
False are not strings, so we don't write quotes around them.
True is a bool, but
"True" (with quotes) is just a string.
bool data type is built-in and you don't need to import any module to use it.
Typical use cases
Like in other programming languages, the bool data type is mainly used for program logic – to control the flow of execution based on different variables being true or false.
A typical use of bool is in conditional statements:
if a variable is
True, do something,
else (if it is
False) do something else.
Which variables are True/False
The following variables are
True in Python:
- Any number other than zero (positive or negative
- Non-empty sequence (e.g. a list, tuple, set, or dict with at least one item)
Conversely, these are
- The number zero in another numeric type (e.g.
- Empty sequence (e.g. a
dictwith no items)
How to create a True/False variable
The simplest way to create a
bool variable is to just assign it to
a = True b = False
Remember that the first letter (T/F) is uppercase and there are no quotes (otherwise it is a string).
We can also assign a variable to be the outcome of a comparison operator. For example:
limit = 10 a = 8 b = 11 a_above_limit = a > limit b_above_limit = b > limit
In the above code,
b are integers, while
b_above_limit are of the bool data type.
False, because 8 is not greater than 10.
Item in a sequence
cities_visited = ['London', 'Paris', 'Rome', 'Berlin'] city = 'Prague' if city in cities_visited: print("I have been to " + city) else: print("I must visit " + city)
In the above code,
cities_visited is a list of strings (city names),
city is a string (a city name which may or may not be in the list). The entire condition
city in cities_visited after
if is in fact a bool. In this case for
'Prague' it is
False, because Prague is not in the list of visited cities. For
'Rome' it would be
This piece of code is simplistic, as it only prints "I have been to" / "I must visit" + city name based on the condition, but if we replace the prints with another code, we can create a program which does something for a city already visited (such as find our photos) and something else if not (such as plan itinerary).
Python bool() function
Another way to create a
bool variable or to check whether a variable is
False is the Python
bool() function. For example:
>>> bool(123) True >>> bool(0) False >>> bool('Hello') True >>> bool('') False
bool data type:
Truth value testing: