✅❌ True/False Values
Boolean values are Python's way of representing truth and falsehood - the fundamental building blocks of logical thinking in programming. Every decision your program makes, every condition it checks, and every yes-or-no question it answers relies on boolean logic.
Understanding booleans is essential for creating programs that can make decisions, respond to different conditions, and control program flow.
# Boolean basics
is_sunny = True
is_raining = False
temperature = 75
print(f"Sunny: {is_sunny}") # True
print(f"Raining: {is_raining}") # False
print(f"Nice weather: {is_sunny and temperature > 70}") # True
🎯 Boolean Fundamentals
Booleans represent one of two possible values: True
or False
. These values are the foundation of all logical operations in programming, from simple comparisons to complex decision-making algorithms.
Creating Boolean Variables
# Creating boolean variables
is_logged_in = True
has_permission = False
game_over = False
print(f"User logged in: {is_logged_in}")
print(f"Has permission: {has_permission}")
print(f"Game over: {game_over}")
Boolean Results from Comparisons
Comparison operations automatically return boolean values, forming the basis for decision-making in programs.
# Comparisons return booleans
age = 25
is_adult = age >= 18
is_senior = age >= 65
print(f"Age: {age}")
print(f"Is adult: {is_adult}") # True
print(f"Is senior: {is_senior}") # False
🔗 Logical Operators
Python provides three main logical operators: and
, or
, and not
. These operators let you combine multiple conditions and create complex logical expressions.
AND Logic - All Must Be True
# AND logic - all conditions must be true
age = 25
has_license = True
has_insurance = True
can_drive = age >= 18 and has_license and has_insurance
print(f"Can drive: {can_drive}") # True
# Example with false condition
has_car = False
can_drive_today = can_drive and has_car
print(f"Can drive today: {can_drive_today}") # False
OR Logic - At Least One Must Be True
# OR logic - at least one condition must be true
is_weekend = True
is_holiday = False
has_vacation = False
can_relax = is_weekend or is_holiday or has_vacation
print(f"Can relax: {can_relax}") # True
# Payment method example
has_cash = False
has_card = True
can_pay = has_cash or has_card
print(f"Can pay: {can_pay}") # True
NOT Logic - Reverse the Value
# NOT logic - reverses the boolean value
is_raining = False
is_sunny = not is_raining
print(f"Raining: {is_raining}") # False
print(f"Sunny: {is_sunny}") # True
# Access control example
is_banned = False
can_access = not is_banned
print(f"Can access: {can_access}") # True
Complex Boolean Expressions
# Complex boolean expressions
age = 25
is_student = True
has_id = True
is_member = False
# Complex eligibility check
eligible_for_discount = (age < 30 and is_student) or is_member
can_enter = age >= 18 and has_id
special_access = eligible_for_discount and can_enter
print(f"Eligible for discount: {eligible_for_discount}") # True
print(f"Can enter: {can_enter}") # True
print(f"Special access: {special_access}") # True
🎭 Truthiness and Falsy Values
In Python, values other than True
and False
can also be evaluated in boolean contexts. Understanding which values are "truthy" or "falsy" is essential for effective conditional logic.
# Testing truthiness of different values
values = [True, False, 1, 0, "hello", "", [1, 2], [], None]
for value in values:
result = "truthy" if value else "falsy"
print(f"{repr(value):10} is {result}")
Practical Truthiness Applications
# Practical truthiness examples
user_name = ""
shopping_cart = []
account_balance = 0
# Check if user has entered a name
if user_name:
print(f"Welcome, {user_name}")
else:
print("Please enter your name")
# Check if cart has items
if shopping_cart:
print(f"Cart has {len(shopping_cart)} items")
else:
print("Cart is empty")
# Check account balance
if account_balance:
print(f"Balance: ${account_balance}")
else:
print("Insufficient funds")
✅ Quick Boolean Practice
Let's practice working with boolean values and logical operations!
Hands-on Exercise
Practice creating boolean variables and using logical operators like 'and', 'or', and 'not'.
# Boolean Practice - Simple and clear!
# User information
age = 20
has_license = True
has_car = False
is_weekend = True
# Check if user can drive
can_drive = # TODO: Your code here (age >= 18 AND has_license)
# Check if it's a good day to relax
can_relax = # TODO: Your code here (is_weekend OR has_car)
# Check if user needs a ride
needs_ride = # TODO: Your code here (NOT has_car)
print(f"Can drive: {can_drive}")
print(f"Can relax: {can_relax}")
print(f"Needs ride: {needs_ride}")
Solution and Explanation 💡
Click to see the complete solution
# Boolean Practice - Simple solution
# User information
age = 20
has_license = True
has_car = False
is_weekend = True
# Check if user can drive
can_drive = age >= 18 and has_license # Both conditions must be True
# Check if it's a good day to relax
can_relax = is_weekend or has_car # At least one must be True
# Check if user needs a ride
needs_ride = not has_car # Reverse the boolean value
print(f"Can drive: {can_drive}")
print(f"Can relax: {can_relax}")
print(f"Needs ride: {needs_ride}")
Key Learning Points:
- 📌 and operator: Both conditions must be True
- 📌 or operator: At least one condition must be True
- 📌 not operator: Reverses the boolean value
- 📌 Comparisons:
age >= 18
creates a boolean result
🔧 Boolean Functions
Python provides several built-in functions that work with boolean values and return boolean results.
Comparison and Membership
# Boolean functions
numbers = [1, 5, 3, 8, 2]
text = "Hello World"
# Testing with all() and any()
all_positive = all(num > 0 for num in numbers)
any_large = any(num > 5 for num in numbers)
print(f"All positive: {all_positive}") # True
print(f"Any large (>5): {any_large}") # True
# Membership testing
valid_colors = ["red", "green", "blue", "yellow"]
user_choice = "green"
is_valid_color = user_choice in valid_colors
print(f"'{user_choice}' is valid: {is_valid_color}") # True
# String membership
email = "user@example.com"
has_at_symbol = "@" in email
print(f"Email has @ symbol: {has_at_symbol}") # True
Identity Testing
# Identity testing with 'is' and 'is not'
value = None
empty_string = ""
# Testing for None (important pattern)
is_none = value is None
is_not_none = empty_string is not None
print(f"Value is None: {is_none}") # True
print(f"Empty string is not None: {is_not_none}") # True
🔄 Common Boolean Patterns
Understanding common boolean patterns helps you solve logical problems effectively.
Input Validation
# Input validation pattern
def validate_password(password):
min_length = len(password) >= 8
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
is_valid = min_length and has_upper and has_lower and has_digit
return {
"valid": is_valid,
"min_length": min_length,
"has_upper": has_upper,
"has_lower": has_lower,
"has_digit": has_digit
}
# Test password validation
result = validate_password("MyPass123")
print(f"Password valid: {result['valid']}")
for check, passed in result.items():
if check != "valid":
status = "✓" if passed else "✗"
print(f"{check}: {status}")
Access Control
# Access control patterns
def check_access(user_role, action):
# Define permissions
permissions = {
"admin": ["read", "write", "delete"],
"editor": ["read", "write"],
"viewer": ["read"]
}
# Check permissions
user_permissions = permissions.get(user_role, [])
has_permission = action in user_permissions
is_authenticated = user_role is not None
can_access = is_authenticated and has_permission
return can_access
# Test access control
print(f"Editor can write: {check_access('editor', 'write')}") # True
print(f"Viewer can delete: {check_access('viewer', 'delete')}") # False
⭐ Boolean Best Practices
Clear Boolean Naming
# Good boolean naming practices
user_age = 25
account_balance = 150
last_login_days = 5
# Descriptive boolean names
is_adult = user_age >= 18
has_sufficient_funds = account_balance > 100
is_active_user = last_login_days <= 7
can_make_purchase = is_adult and has_sufficient_funds and is_active_user
print(f"Can make purchase: {can_make_purchase}")
Simplifying Complex Conditions
# Simplifying complex conditions
def check_loan_eligibility(age, income, credit_score):
# Break complex condition into clear parts
meets_age_requirement = 18 <= age <= 65
has_stable_income = income >= 30000
has_good_credit = credit_score >= 650
# Combine conditions clearly
is_eligible = (meets_age_requirement and
has_stable_income and
has_good_credit)
return is_eligible
# Test eligibility
eligible = check_loan_eligibility(30, 45000, 720)
print(f"Loan eligible: {eligible}")
🎯 Key Takeaways
🧠 Test Your Knowledge
Ready to test your understanding of true/false values?
🚀 What's Next?
Now that you understand boolean values and logical operations, you're ready to explore type conversion - how to transform data between different types like strings, numbers, and booleans.
Learn about Converting Types to master data transformation, or explore Math Operations for mathematical calculations and comparisons.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.