
Boolean Data in Python
Let's dive into the world of boolean data in Python. This topic may seem simple, but it's incredibly important — after all, it's with boolean values that your programs will make decisions! 🧠
What is boolean data? 🤔
In everyday life, we often ask questions with "yes" or "no" answers.
For example: "Is it raining today?", "Do you like pizza?", "Is 2 + 2 = 5?".
In Python, there's a special data type for such answers — bool, which can only take two values:
- True (truth, "yes") ✅
- False (falsehood, "no") ❌
# Creating boolean variables >>> is_raining = True # Yes, it's raining >>> likes_pizza = True # Yes, I like pizza >>> print(type(is_raining)) # <class 'bool'>
<class 'bool'>
💡 Important: True and False are always written with a capital letter. If you write true or false, Python won't understand and will raise an error!
Boolean operators: how to combine conditions 🧩
In life, we often combine multiple conditions.
For example: "I'll go to the beach if it's sunny AND warm" or "I'll buy this phone if it's beautiful OR inexpensive".
Python gives us three main logical operators:
1. The and operator (logical AND)
Returns True only if both values are true:
>>> sunny = True # It's sunny >>> warm = True # It's warm # I'll go to the beach if it's sunny AND warm >>> going_to_beach = sunny and warm >>> print(f"Sunny: {sunny}, Warm: {warm}") >>> print(f"Going to the beach? {going_to_beach}")
Sunny: True, Warm: TrueGoing to the beach? True# What if the weather changes? >>> warm = False # It got cold >>> going_to_beach = sunny and warm >>> print(f"Sunny: {sunny}, Warm: {warm}") >>> print(f"Going to the beach? {going_to_beach}")Sunny: True, Warm: FalseGoing to the beach? False
2. The or operator (logical OR)
Returns True if at least one value is true:
>>> phone_is_beautiful = True # The phone is beautiful >>> phone_is_cheap = False # But not cheap # I'll buy the phone if it's beautiful OR inexpensive >>> will_buy_phone = phone_is_beautiful or phone_is_cheap >>> print(f"Phone is beautiful: {phone_is_beautiful}, Phone is cheap: {phone_is_cheap}") >>> print(f"Will buy the phone? {will_buy_phone}")
Phone is beautiful: True, Phone is cheap: FalseWill buy the phone? True
Truth table for the or operator:
>>> print("True or True =", True or True)
True or True = True>>> print("True or False =", True or False)True or False = True>>> print("False or True =", False or True)False or True = True>>> print("False or False =", False or False)False or False = False
3. The not operator (logical NOT)
Inverts the value: True becomes False, and vice versa:
>>> have_homework = True >>> print(f"I have homework: {have_homework}")
I have homework: True>>> print(f"I DON'T have homework: {not have_homework}")I DON'T have homework: False# Another example: if it's not raining, we go for a walk >>> is_raining = False >>> going_for_a_walk = not is_raining >>> print(f"Is it raining? {is_raining}")Is it raining? False>>> print(f"Going for a walk? {going_for_a_walk}")Going for a walk? True
Comparing values 🔍
Boolean values often appear as a result of comparison:
# Comparing numbers >>> my_age = 25 >>> friend_age = 30 >>> print(f"My age: {my_age}, friend's age: {friend_age}")
My age: 25, friend's age: 30>>> print(f"Our ages are the same? {my_age == friend_age}")Our ages are the same? False>>> print(f"Our ages are different? {my_age != friend_age}")Our ages are different? True>>> print(f"Am I younger? {my_age < friend_age}")Am I younger? True>>> print(f"Am I older? {my_age > friend_age}")Am I older? False# Comparing strings (alphabetically) >>> print("String comparison:")String comparison:>>> print(f"'apple' < 'banana': {'apple' < 'banana'}")'apple' < 'banana': True>>> print(f"'python' == 'Python': {'python' == 'Python'}")'python' == 'Python': False# Comparing lists >>> my_scores = [90, 85, 95] >>> friend_scores = [90, 85, 95] # Same list, but different object >>> same_list = my_scores # The same object >>> print("List comparison:")List comparison:>>> print(f"Contents the same? {my_scores == friend_scores}")Contents the same? True>>> print(f"Is it the same object? {my_scores is friend_scores}")Is it the same object? False>>> print(f"Is same_list the same object as my_scores? {my_scores is same_list}")Is same_list the same object as my_scores? True
Operator precedence: what gets calculated first? 📊
Operators are executed in the following order (from highest to lowest):
- not (highest priority)
- and
- or (lowest priority)
# Example with priorities >>> has_ticket = True >>> has_passport = False >>> has_visa = True >>> print(f"Have ticket: {has_ticket}")
Have ticket: True>>> print(f"Have passport: {has_passport}")Have passport: False>>> print(f"Have visa: {has_visa}")Have visa: True# Can we travel abroad? # Need a ticket AND (passport OR visa) >>> can_travel = has_ticket and (has_passport or has_visa) >>> print("\nCan we travel abroad?")Can we travel abroad?>>> print(f"has_ticket and (has_passport or has_visa) = {can_travel}")has_ticket and (has_passport or has_visa) = True# Let's break down the calculation step by step: >>> step1 = has_passport or has_visa # First, the expression in parentheses is calculated >>> print(f"\nStep 1: has_passport or has_visa = {step1}")Step 1: has_passport or has_visa = True>>> step2 = has_ticket and step1 # Then the and operator is applied >>> print(f"Step 2: has_ticket and (result of step 1) = {step2}")Step 2: has_ticket and (result of step 1) = True
💡 Tip: If you're unsure about the order of execution, use parentheses! They make the code clearer and precisely control the order of calculations.
Converting to boolean type: what counts as true? 🔄
The bool function
Python can convert any value to a boolean type:
print(bool(100))
Trueprint(bool(0))Falseprint(bool("Hello"))Trueprint(bool(""))False
What counts as true and false? 🤔
In Python, most values are considered true (True).
Only the following are considered false (False):
- False (the logical "no")
- None (absence of value)
- Zeros: 0, 0.0, 0j
- Empty containers: "", (), [], {}
# Examples in conditions money = 0 if money: print("I have money!") else: print("My wallet is empty :(") # This will be printed name = "Alex" if name: print(f"Hello, {name}!") # This will be printed else: print("Hello, stranger!")
Understanding check 🎯
Let's check how well you've understood the material:
What will the following expression return?
result = (False or True) and not (False and True or True)
Now you know how boolean data works in Python. Although they can only take two values — True and False, their importance in programming cannot be overstated.