Logical Operators
Introduction
Logical operators let us combine or invert conditions. They are widely used in decision-making (e.g., if statements, loops). Logical expressions evaluate to True or False but can also take advantage of Python's truthy and falsy values.
Python treats values like (0, "", [], {}, None, False) as falsy and everything else is truthy. This makes logical operators powerful and intuitive. Python's logical operators use English words (and, or, not) making code more readable than symbols.
Concepts
- AND (
and)Trueif both conditions areTrue.- Example:
True and False→False.
- OR (
or)Trueif at least one condition isTrue.- Example:
True or False→True.
- NOT (
not)- Inverts the condition.
- Example:
not True→False.
- Short-circuiting:
- Stops evaluating when result is already known
a and b→ ifaisFalse,bis never checked.a or b→ ifaisTrue,bis never checked.
- Stops evaluating when result is already known
This is often used for default values and safe operations in Python.
Examples
age = 20
has_id = True
print(age >= 18 and has_id) # True
print(age < 18 or has_id) # True
print(not has_id) # False
# Using or for default values
username = ""
display_name = username or "Guest"
print(display_name) # Guest
# Short-circuiting with and
data = None
data and print("Processing data...") # Nothing happens
# Chaining comparisons (Python-specific feature)
score = 85
print(0 <= score <= 100) # True (elegant range check)
Challenges
1. Check if number between 10 and 20
- Write a condition that checks if a number is between 10 and 20 (inclusive).
💡 Show Answer
num = 15
print(10 <= num <= 20) # True (Python's chained comparison)
# Alternative with and
print(num >= 10 and num <= 20) # True
2. Driving check
- Check if a person can drive: must be at least 18 and have a driving license.
💡 Show Answer
age = 18
has_license = True
can_drive = age >= 18 and has_license
print(f"Can drive: {can_drive}") # True
# As a function
def can_drive(age, has_license):
return age >= 18 and has_license
print(can_drive(17, True)) # False
print(can_drive(20, False)) # False
print(can_drive(18, True)) # True
3. Welcome if logged in or guest
- Write a condition that prints
"Welcome"if a user has logged in or is a guest.
💡 Show Answer
is_logged_in = False
is_guest = True
if is_logged_in or is_guest:
print("Welcome")
# One-liner using conditional expression
message = "Welcome" if is_logged_in or is_guest else "Access denied"
print(message)
4. Flip boolean
- Use
notto flip the result of a boolean variableis_active.
💡 Show Answer
is_active = True
print(not is_active) # False
# Toggle a boolean
is_active = not is_active
print(f"is_active is now: {is_active}") # False
5. Secure data access
- Demonstrate short-circuiting with
andby writing a condition that only prints"Accessing secure data..."ifis_logged_inisTrue.
💡 Show Answer
is_logged_in = True
is_logged_in and print("Accessing secure data...")
# More Pythonic approach
if is_logged_in:
print("Accessing secure data...")
# With function call
def access_secure_data():
print("Accessing secure data...")
is_logged_in and access_secure_data()
6. Default with OR
- Use
orto assign a default value to a variable if it isNoneor empty.
💡 Show Answer
username = ""
display_name = username or "Guest"
print(display_name) # Guest
# More examples
config_file = None
config = config_file or "default_config.txt"
print(config)
# With various falsy values
values = ["", 0, [], {}, None, False]
for val in values:
result = val or "default"
print(f"{val} or 'default' = {result}")
7. Predict outputs
- Predict the output of these expressions:
💡 Show Answer
print(True or False and False) # True (and has higher precedence)
print(not (False or True)) # False
print("" or "Hello") # Hello
print("Hi" and "Bye") # Bye (and returns the last truthy value)
# More complex examples
print(0 or 5 or 10) # 5 (first truthy value)
print(1 and 2 and 3) # 3 (last value if all truthy)
print(1 and 0 and 3) # 0 (first falsy value)
print(not not "hello") # True (double negation)
8. Valid grade
- Write a function
is_valid_grade(grade)that returnsTrueifgradeis between 0 and 100.
💡 Show Answer
def is_valid_grade(grade):
return 0 <= grade <= 100
print(is_valid_grade(85)) # True
print(is_valid_grade(-5)) # False
print(is_valid_grade(105)) # False
# Test with various inputs
test_grades = [0, 50, 100, -10, 150, 99.5]
for grade in test_grades:
valid = is_valid_grade(grade)
print(f"Grade {grade}: {'Valid' if valid else 'Invalid'}")
9. Simple login
- Build a simple login system where the user must have the right username and password.
💡 Show Answer
def login(username, password):
return username == "admin" and password == "1234"
# Test the login
print(login("admin", "1234")) # True
print(login("user", "1234")) # False
print(login("admin", "wrong")) # False
# More complete login system
def secure_login(username, password):
valid_users = {
"admin": "1234",
"user": "password",
"guest": "guest123"
}
return username in valid_users and valid_users[username] == password
print(secure_login("admin", "1234")) # True
print(secure_login("user", "password")) # True
print(secure_login("hacker", "1234")) # False
10. Majority vote
- Write a function
majority_vote(a, b, c)that returnsTrueif at least two of the three boolean inputs areTrue.
💡 Show Answer
def majority_vote(a, b, c):
return (a + b + c) >= 2 # Works because True = 1, False = 0
print(majority_vote(True, True, False)) # True
print(majority_vote(True, False, False)) # False
print(majority_vote(False, False, False)) # False
# Alternative implementation
def majority_vote_alt(a, b, c):
return (a and b) or (a and c) or (b and c)
# More explicit implementation
def majority_vote_explicit(a, b, c):
count = sum([a, b, c]) # Count True values
return count >= 2
# Test all implementations
test_cases = [
(True, True, True),
(True, True, False),
(True, False, False),
(False, False, False)
]
for a, b, c in test_cases:
result1 = majority_vote(a, b, c)
result2 = majority_vote_alt(a, b, c)
result3 = majority_vote_explicit(a, b, c)
print(f"({a}, {b}, {c}): {result1} {result2} {result3}")