Course Progress16% complete
🐍 Python Basics Topic 16 / 100
⏱ 8 min read

Logical Operators

and, or, not — combining conditions together to build smarter, more expressive program logic.

"A single comparison asks one question. Logical operators let you ask several at once — the way real decisions actually work."

— ShurAI

Why Logical Operators?

Real decisions rarely depend on just one condition. A website does not let you in if the password is correct — it lets you in if the password is correct and the account is active and you are not banned. Logical operators let you combine conditions into one compound check.

Python has three: and, or, and not. They work on boolean values — either on literal True/False, or on the results of comparison expressions.

and
Both conditions must be True to get True
T and T → True
T and F → False
F and T → False
F and F → False
or
At least one must be True to get True
T or T → True
T or F → True
F or T → True
F or F → False
not
Flips True to False and vice versa
not True → False
not False → True

and — Both Must Be True

python
age     = 22
has_id  = True
is_vip  = False

# Both conditions must be True
print(age >= 18 and has_id)      # True  — both met
print(age >= 18 and is_vip)      # False — is_vip is False
print(age >= 25 and has_id)      # False — age < 25

# Real use: entry check
if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")

or — At Least One Must Be True

python
is_student = True
is_senior  = False
is_vip     = False

# At least one must be True for discount
print(is_student or is_senior)   # True  — is_student is True
print(is_senior or is_vip)       # False — both are False

# Multiple or conditions
discount = is_student or is_senior or is_vip
print(f"Discount applies: {discount}")   # True

not — Flip the Result

python
is_banned    = False
is_logged_in = True

# not flips the boolean
print(not is_banned)        # True  — not False = True
print(not is_logged_in)     # False — not True = False

# Reads naturally
if not is_banned:
    print("Welcome!")

# not with comparison
score = 45
if not (score >= 60):
    print("Score is below 60")

Combining All Three

python
age           = 24
has_account   = True
is_banned     = False
balance       = 500
amount        = 200

# Full access check
can_transact = (
    age >= 18
    and has_account
    and not is_banned
    and balance >= amount
)

if can_transact:
    print(f"Transaction of Rs.{amount} approved.")
else:
    print("Transaction denied.")

Operator Precedence — not Before and Before or

When you mix operators, Python evaluates them in order: not first, then and, then or. Use brackets to make intent clear and avoid surprises:

python
a = True
b = False
c = True

# not evaluated first, then and, then or
print(a or b and not c)
# = a or (b and (not c))
# = True or (False and False)
# = True or False
# = True

# Use brackets to be explicit and readable
print((a or b) and (not c))
# = True and False
# = False  — very different result!
When in Doubt, Use Brackets

Rather than memorise precedence rules, wrap conditions in brackets () to make your intent explicit. (age >= 18) and (not is_banned) is clearer than relying on precedence. Code clarity beats cleverness.

Short-Circuit Evaluation

Python is smart — it stops evaluating as soon as the result is certain. This is called short-circuit evaluation:

python
# With 'and' — if first is False, skip second entirely
# (result is already definitely False)
print(False and print("never runs"))  # False — second skipped

# With 'or' — if first is True, skip second entirely
# (result is already definitely True)
print(True or print("never runs"))   # True — second skipped

# Practical: check if variable exists before using it
name = ""
# If name is empty (falsy), the second part never runs
if name and name.startswith("A"):
    print("Name starts with A")
else:
    print("Name is empty or doesn't start with A")

Real Example — Loan Eligibility Checker

python
print("=== Loan Eligibility Check ===")
age        = int(input("Age            : "))
income     = int(input("Monthly income : "))
credit     = int(input("Credit score   : "))
has_job    = input("Employed? (yes/no): ").lower() == "yes"

# All conditions must be met for loan approval
age_ok     = 21 <= age <= 60
income_ok  = income >= 25000
credit_ok  = credit >= 700

approved = age_ok and income_ok and credit_ok and has_job

print()
if approved:
    print("✅ Loan APPROVED")
else:
    print("❌ Loan DENIED")
    if not age_ok:
        print("  - Age must be between 21 and 60")
    if not income_ok:
        print("  - Minimum income Rs.25,000/month required")
    if not credit_ok:
        print("  - Minimum credit score 700 required")
    if not has_job:
        print("  - Must be currently employed")

"and, or, not — three little words that give your programs the ability to reason. All real-world logic is built from combinations of these three."

— ShurAI

🧠 Quiz — Question 1

What does True and False evaluate to?

🧠 Quiz — Question 2

What does False or True evaluate to?

🧠 Quiz — Question 3

In Python's precedence order, which logical operator is evaluated first?

🧠 Quiz — Question 4

A user must be over 18 and not banned to log in. Which condition expresses this correctly?