In Python, a Boolean (or bool) is a fundamental data type that represents one of two possible states: True or False.
Think of it like a light switch—it is either on or off. Booleans are the foundation of logic in programming. They allow your code to make decisions, compare values, and control the flow of your program.
Important Note: In Python, Booleans are case-sensitive. They must always start with a capital letter (
TrueandFalse). Using lowercasetrueorfalsewill result in an error.
Here are 10 examples showing how Booleans work and how they are used in Python:
1. Direct Assignment
You can assign a Boolean value directly to a variable to track a state or condition.
Python
is_logged_in = True
has_errors = False
print(is_logged_in) # Output: True
2. Equality Operator (==)
Comparing two values using == evaluates whether they are the same, resulting in a Boolean.
Python
user_guess = 5
correct_answer = 5
print(user_guess == correct_answer) # Output: True
3. Mathematical Comparisons (>, <)
Using operators like greater than (>), less than (<), or greater than/equal to (>=) always returns a Boolean.
Python
temperature = 30
print(temperature > 100) # Output: False
4. Logical and
The and operator checks if both conditions are true. If even one is false, the whole statement is false.
Python
has_ticket = True
is_vip = False
print(has_ticket and is_vip) # Output: False
5. Logical or
The or operator checks if at least one condition is true.
Python
is_weekend = True
is_holiday = False
print(is_weekend or is_holiday) # Output: True
6. Logical not
The not operator reverses the Boolean value. True becomes False, and False becomes True.
Python
is_raining = False
print(not is_raining) # Output: True
7. Evaluating Numbers (Truthy/Falsy)
You can use the bool() function to evaluate any Python object. For numbers, 0 is always False, and any other number (positive or negative) is True.
Python
print(bool(1)) # Output: True
print(bool(0)) # Output: False
print(bool(-42)) # Output: True
8. Evaluating Strings and Collections
For strings, lists, or dictionaries, empty ones are False, and ones with content are True.
Python
print(bool("Hello")) # Output: True
print(bool("")) # Output: False (empty string)
print(bool([])) # Output: False (empty list)
9. The Membership Operator (in)
You can check if a specific item exists inside a string, list, or other collection. This check returns a Boolean.
Python
vowels = ['a', 'e', 'i', 'o', 'u']
print('a' in vowels) # Output: True
print('z' in vowels) # Output: False
10. Using Booleans in Conditional Statements
Booleans are most commonly used to control if statements. The code indented under the if block only runs if the condition evaluates to True.
Python
battery_level = 15
# battery_level < 20 evaluates to True, so the print statement runs
if battery_level < 20:
print("Please charge your device!")