Logical Operators

Combine conditions with and, or and not.

Syntaxa and b a or b not a

Python spells its logical operators as words, which keeps code readable.

  • and — True only if both sides are True.
  • or — True if at least one side is True.
  • not — inverts True to False and vice versa.

Python is lazy: with and it stops as soon as one side is False, and with or it stops at the first True.

Example

Example · python
age = 25
print(age > 18 and age < 65)
print(age < 13 or age > 60)
print(not (age > 18))

name = ''
print(name or 'Guest')

# Output:
# True
# False
# False
# Guest

When to use it

  • A form validator requires both username and password to be non-empty using 'and'.
  • A content filter blocks users who are either banned or under 18 using 'or'.
  • A toggle function inverts a boolean flag with 'not' when a user clicks a switch.

More examples

and, or, not operators

Combines boolean expressions with 'and', 'or', and 'not' to evaluate compound conditions.

Example · python
x = 10
print(x > 5 and x < 20)  # True
print(x < 5 or x > 8)    # True
print(not x == 10)        # False

Short-circuit evaluation

Shows short-circuit evaluation: 'and' skips the right side when the left is already False.

Example · python
def expensive():
    print('called expensive')
    return True

# 'and' stops early if left side is False:
result = False and expensive()  # expensive() never runs
print(result)  # False

Logical operators in access control

Uses 'or' to grant access if any one of several permission conditions is True.

Example · python
is_admin = False
is_owner = True
resource_public = False

can_access = is_admin or is_owner or resource_public
print(can_access)  # True

Discussion

  • Be the first to comment on this lesson.