Logical Operators
Week 1 — Python Basics Revision
Introduction
Sometimes one condition is not enough. You might need to check if a user is both logged in AND has admin access. Or check if the input is less than 0 OR greater than 100. Logical operators let you combine multiple conditions into one expression.
The and Operator
The and operator returns True only when both conditions are True.
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
else:
print("You cannot drive.")
You can drive.
The or Operator
The or operator returns True when at least one condition is True.
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No school today!")
else:
print("Time for class.")
No school today!
The not Operator
The not operator flips a boolean value. True becomes False, and False becomes True.
is_logged_in = False
if not is_logged_in:
print("Please log in first.")
else:
print("Welcome back!")
Please log in first.
Truth Table
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Real-World Example
A loan eligibility checker that combines multiple conditions.
age = 28
income = 45000
has_debt = False
if age >= 21 and income >= 30000 and not has_debt:
print("Loan approved!")
else:
print("Loan denied.")
Loan approved!
How This Connects to OOP
In OOP, methods frequently use logical operators to validate data. A User.can_access() method might check self.is_active and self.is_admin. These operators are used inside methods to enforce business rules.
Best Practices
- Use parentheses to make complex conditions clear:
(a and b) or c - Prefer
not is_emptyoveris_empty == False - Keep conditions readable — split very long conditions across multiple lines
Common Mistakes
- Using
&&or||instead ofand/or(Python uses words, not symbols) - Forgetting operator precedence:
notruns beforeand, which runs beforeor - Writing
if x == 1 or 2:instead ofif x == 1 or x == 2:
Practice Exercises
- Ask for a username and password. Print "Access granted" only if both are correct.
- Check if a number is between 1 and 100 (inclusive) using
and. - Write a program that checks if a year is a leap year (divisible by 4 and not 100, or divisible by 400).
Summary
You can now combine conditions to make smarter decisions. Next up: for loops, where you will learn to repeat actions across sequences.