Python Booleans
Python booleans represent one of two values: True or False. Every comparison you write produces a boolean, and booleans decide which way your program goes in if statements and loops. Note the capital letters: true without a capital is not valid Python.
Comparisons Return Booleans
print(10 > 9)
print(10 == 9)
print("apple" < "banana")
is_adult = 20 >= 18
print(is_adult, type(is_adult))True False True True <class 'bool'>
Booleans in if Statements
An if statement runs its block when the condition is True. Storing a condition in a well-named boolean variable often makes code easier to read.
stock = 0
in_stock = stock > 0
if in_stock:
print("Add to cart")
else:
print("Sold out")Sold out
Truthy and Falsy Values
Any value can be tested as a boolean. The bool() function shows the result. Empty or zero values are falsy; almost everything else is truthy.
print(bool(0), bool(0.0), bool(""), bool([]), bool({}), bool(None))
print(bool(5), bool("hi"), bool([0]), bool(" "))False False False False False False True True True True
Check if a List Is Empty
Because empty collections are falsy, the idiomatic way to check for an empty list or string is simply to use it as the condition.
tasks = []
if not tasks:
print("Nothing to do!")
tasks.append("Write report")
if tasks:
print("You have", len(tasks), "task")Nothing to do! You have 1 task
Booleans Are Numbers Too
In Python, bool is a subtype of int: True equals 1 and False equals 0. A neat use of this is counting how many items match a condition with sum().
print(True + True)
marks = [45, 80, 67, 30, 90]
passed = sum(m >= 50 for m in marks)
print(passed)2 3
Functions That Return Booleans
- isinstance(x, int) checks a type
- text.isdigit(), text.isalpha() and text.isupper() inspect strings
- any(list) is True if at least one item is truthy
- all(list) is True only if every item is truthy
Frequently asked questions
Is it True or true in Python?
It is True with a capital T, and False with a capital F. Lowercase true raises a NameError.
What values are falsy in Python?
False, None, 0, 0.0, empty strings, and empty collections such as [], (), {} and set(). Everything else is truthy.
How do I check if a list is empty in Python?
Use if not my_list:. An empty list is falsy, so this is the recommended, Pythonic way.