Logical Operators

Code Examples

Example 1

The and operator returns True only if both conditions are True. If either condition is False, the result will be False. This is useful when you need to ensure multiple requirements are met simultaneously.

# Basic usage of 'and'
is_sunny = True
is_warm = True
perfect_day = is_sunny and is_warm
print(perfect_day)  # Output: True

# Both conditions must be True
has_ticket = True
has_id = False
can_enter = has_ticket and has_id
print(can_enter)  # Output: False

# Using 'and' with comparison operators
age = 25
income = 50000
qualifies_for_loan = age >= 18 and income >= 40000
print(qualifies_for_loan)  # Output: True

Example 2

The or operator returns True if at least one of the conditions is True. It returns False only when both conditions are False. This is useful when you need to check if at least one of several conditions is met.

# Basic usage of 'or'
has_cash = False
has_card = True
can_pay = has_cash or has_card
print(can_pay)  # Output: True

# Only one condition needs to be True
is_weekend = False
is_holiday = False
day_off = is_weekend or is_holiday
print(day_off)  # Output: False

# Using 'or' with comparison operators
temperature = 25
is_raining = False
stay_inside = temperature > 35 or is_raining
print(stay_inside)  # Output: False

Example 3

The not operator inverts a Boolean value, changing True to False and False to True. It's useful when you need to check the opposite of a condition.

# Basic usage of 'not'
is_busy = True
is_available = not is_busy
print(is_available)  # Output: False

# Inverting a condition
is_logged_in = False
show_login_button = not is_logged_in
print(show_login_button)  # Output: True

# Using 'not' with comparison operators
temperature = 22
not_comfortable = not (15 <= temperature <= 25)
print(not_comfortable)  # Output: False

Example 4

You can combine multiple logical operators to create complex conditions. When doing so, it's important to understand the order of operations or use parentheses to make your intentions clear. In the examples above, we check several conditions to determine eligibility for different activities.

# Using multiple operators together
has_membership = True
has_coupon = False
items_in_cart = 5
free_shipping = (has_membership and items_in_cart >= 3) or has_coupon
print(free_shipping)  # Output: True

# More complex example
age = 16
has_license = False
with_adult = True
parent_consent = True

can_drive = (age >= 18 and has_license) or (age >= 16 and has_license and parent_consent)
can_ride = age >= 16 and has_license or with_adult
print(can_drive)  # Output: False
print(can_ride)  # Output: True