🧠 Logic Operations
Logical operators are essential tools for combining multiple conditions and creating complex decision-making logic in your programs. They work with boolean values and help you build sophisticated conditional statements that can handle multiple criteria simultaneously.
Python provides three main logical operators: and
, or
, and not
. These operators follow the principles of boolean logic and are fundamental to programming control flow and decision-making processes.
# Basic logical operations
is_sunny = True
is_warm = True
is_weekend = False
# Using logical operators
good_day = is_sunny and is_warm # True (both conditions met)
can_go_out = is_sunny or is_weekend # True (at least one condition met)
not_working = not is_weekend # True (opposite of False)
print(f"Good day for picnic: {good_day}")
print(f"Can go out: {can_go_out}")
print(f"Not working: {not_working}")
🤝 The AND Operator
The and
operator returns True
only when all operands are true. It's used when you need all conditions to be satisfied for something to happen.
# AND operator examples
age = 25
has_license = True
has_car = True
# All conditions must be true
can_drive = age >= 18 and has_license and has_car
print(f"Can drive: {can_drive}") # True
# Login example
username = "admin"
password = "secret123"
is_logged_in = username == "admin" and password == "secret123"
print(f"Login successful: {is_logged_in}") # True
# Short-circuit evaluation demo
result = False and print("This won't print!") # Short-circuits at False
print(f"Short-circuit result: {result}") # False
🔄 The OR Operator
The or
operator returns True
when at least one operand is true. It's used when you have alternative conditions where any one being true is sufficient.
# OR operator examples
is_weekend = False
is_holiday = True
is_vacation = False
# Any condition can be true
can_relax = is_weekend or is_holiday or is_vacation
print(f"Can relax today: {can_relax}") # True
# Alternative payment methods
has_cash = False
has_card = True
has_mobile_pay = False
can_pay = has_cash or has_card or has_mobile_pay
print(f"Can make payment: {can_pay}") # True
# Short-circuit evaluation demo
result = True or print("This won't print!") # Short-circuits at True
print(f"Short-circuit result: {result}") # True
❌ The NOT Operator
The not
operator reverses the boolean value of its operand. It converts True
to False
and False
to True
.
# NOT operator examples
is_raining = False
is_sunny = True
# Negating conditions
not_raining = not is_raining
not_sunny = not is_sunny
print(f"Not raining: {not_raining}") # True
print(f"Not sunny: {not_sunny}") # False
# Using NOT in conditions
user_logged_in = False
if not user_logged_in:
print("Please log in to continue")
# Double negation
print(f"not not True: {not not True}") # True
🎯 Operator Precedence and Complex Expressions
Logical operators have their own precedence order: not
(highest), and
(middle), or
(lowest). Understanding this helps you write complex expressions correctly.
# Precedence examples
print("=== PRECEDENCE EXAMPLES ===")
# Without parentheses - follows precedence rules
result1 = False or True and False
print(f"False or True and False = {result1}") # False
# With parentheses for clarity
result2 = (False or True) and False
print(f"(False or True) and False = {result2}") # False
# NOT has highest precedence
result3 = not False or True
print(f"not False or True = {result3}") # True
# Complex expression
age = 25
has_permission = True
is_blocked = False
can_access = age >= 18 and has_permission and not is_blocked
print(f"Can access: {can_access}") # True
💼 Practical Applications
Logical operators are essential for creating intelligent programs that respond to different conditions. They're used in decision-making, validation, filtering data, and controlling program flow.
# Practical logical operations
print("=== PRACTICAL EXAMPLES ===")
# Age group classification
age = 22
is_child = age < 13
is_teen = 13 <= age < 20
is_adult = age >= 20
is_senior = age >= 65
print(f"Age {age}: Child={is_child}, Teen={is_teen}, Adult={is_adult}")
# Access control system
user_role = "admin"
is_authenticated = True
has_valid_session = True
admin_access = (user_role == "admin") and is_authenticated and has_valid_session
print(f"Admin access granted: {admin_access}")
# Weather decision making
temperature = 22 # Celsius
is_sunny = True
is_windy = False
good_weather = (temperature > 20) and is_sunny and not is_windy
print(f"Good weather for outdoor activity: {good_weather}")
# Shopping cart validation
item_count = 3
total_price = 45.99
has_coupon = True
can_checkout = (item_count > 0) and (total_price > 0) and (has_coupon or total_price < 50)
print(f"Can proceed to checkout: {can_checkout}")
🧠 Quick Logic Practice
Let's practice combining conditions using logical operators!
Hands-on Exercise
Practice using logical operators 'and', 'or', and 'not' to combine multiple conditions.
# Logic Practice - Simple combinations!
# Student information
age = 20
has_id = True
is_student = True
is_banned = False
# Check if can enter library (must be 18+ AND have ID)
can_enter = # TODO: Your code here (age >= 18 and has_id)
# Check if gets discount (must be student OR senior 65+)
gets_discount = # TODO: Your code here (is_student or age >= 65)
# Check if account is active (NOT banned)
is_active = # TODO: Your code here (not is_banned)
print(f"Can enter library: {can_enter}")
print(f"Gets student discount: {gets_discount}")
print(f"Account is active: {is_active}")
Solution and Explanation 💡
Click to see the complete solution
# Logic Practice - Simple solution
# Student information
age = 20
has_id = True
is_student = True
is_banned = False
# Check if can enter library (must be 18+ AND have ID)
can_enter = age >= 18 and has_id # Both conditions must be True
# Check if gets discount (must be student OR senior 65+)
gets_discount = is_student or age >= 65 # At least one must be True
# Check if account is active (NOT banned)
is_active = not is_banned # Reverses the boolean value
print(f"Can enter library: {can_enter}")
print(f"Gets student discount: {gets_discount}")
print(f"Account is active: {is_active}")
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
- 📌 Combining conditions: Makes complex logic simple
📊 Truth Tables
Understanding how logical operators work with different input combinations:
A | B | A and B | A or B | not A |
---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
These truth tables show all possible combinations and their results, helping you understand logical operator behavior.
🎯 Key Takeaways
Understanding logical operations prepares you for decision making with if statements and working with loops. These operators are also essential for data filtering and function conditions.
Test Your Knowledge
🚀 What's Next?
Now that you understand how to combine conditions using logical operators, you're ready to learn about efficient ways to update variables using assignment operators.
In the next lesson, we'll explore Value Assignment, where you'll learn shortcuts for updating variables and performing calculations.
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.