Learn Python: The Fundamentals

Logical operators help your program make smarter decisions by combining or inverting conditions. You can check for multiple things at once, require all to be true, or flip results with a single keyword.

 

  • and → All conditions must be true
  • or → At least one condition must be true
  • not → Flips a condition (True becomes False, and vice versa)

 

Use parentheses to group conditions clearly. It’s not just good style — it also avoids bugs from misunderstood order of operations.

 

Combining Conditions

Let’s say we want to check if someone can enter a concert. They need to be at least 18 with ID, or be with a parent:

 

age = 20
has_id = True
with_parent = False

if (age >= 18 and has_id) or with_parent:
    print("Access granted.")
else:
    print("Access denied.")

 

Because of the parentheses, Python first checks if the person is 18+ and has ID. If not, it checks if they’re with a parent.

 

Readable Boolean Logic

It’s tempting to cram everything into one line, but clear logic wins every time — especially when things get more complex. Try breaking it into parts like this:

 

is_student = True
has_discount_code = False
cart_total = 39.50

qualifies_by_role = is_student or has_discount_code
qualifies_by_cart = cart_total >= 50
eligible = qualifies_by_role or qualifies_by_cart

print("Eligible for discount:", eligible)

 

This version is easier to read and debug later — especially if more rules are added.

 

Interactive Exercise: Discount Eligibility

Now let’s put it all together. Test different combinations of values to see who qualifies for a discount. Then, try adding a special VIP flag that overrides all rules.

 


is_student = True
has_discount_code = False
cart_total = 39.50
is_vip = False

# Rule: student OR discount code qualifies; OR cart >= 50; OR VIP always qualifies
eligible = (is_student or has_discount_code) or (cart_total >= 50) or is_vip

print("Eligible for discount:", eligible)

# Try toggling:
# is_student = False
# has_discount_code = True
# cart_total = 55
# is_vip = True

 
Use parentheses to group related checks and avoid logic errors.
 

Logical operators are the heart of decision-making in Python. Mastering them will make your programs more flexible, accurate, and easier to reason about — no matter how complex the rules get.