Python Basics
Python Booleans
A boolean is a data type with only two possible values, True or False, and it's the backbone of decision-making in your programs.
True and False
In Python, True and False are the two boolean values, and they must be written with a capital first letter since Python is case-sensitive.
is_student = True
is_working = False
print(is_student, is_working)
print(type(is_student))Comparisons Produce Booleans
Comparison operators like ==, !=, >, < always return a boolean value, which is why they are so often used inside if statements.
age = 20
print(age == 18) # False
print(age >= 18) # True
print(age != 20) # FalseTruthy and Falsy Values
Every value in Python can be evaluated as True or False in a boolean context, even if it isn't literally True or False. Empty or zero-like values are considered "falsy", while most other values are "truthy".
| Falsy Values | Truthy Values |
|---|---|
| 0, 0.0 | Any non-zero number |
| "" (empty string) | "hello" (non-empty string) |
| [], (), {} | [1, 2] and other non-empty collections |
| None | Almost everything else |
The bool() Function
You can check whether Python treats a value as truthy or falsy using the built-in bool() function.
print(bool(0)) # False
print(bool(5)) # True
print(bool("")) # False
print(bool("hi")) # True
print(bool([])) # FalseTruthy and falsy checks are very common in if conditions, such as if my_list: to check whether a list has any items.
Understanding booleans well will make conditional statements and loops much easier when you reach those lessons.
