Control Flow and Logic
20 min read
Logical Operators
Logical Operators
Sometimes one condition is not enough.
You may want to check two or more conditions at the same time.
For example:
- Is the user 18 or older and has an ID?
- Is it Saturday or Sunday?
- Is the password not empty?
Python uses logical operators for this.
The Three Logical Operators
Python has three logical operators:
andornot
The and Operator
and means both conditions must be true.
age = 20
has_id = True
print(age >= 18 and has_id)
The result is True because both conditions are true.
Another and Example
score = 75
paid = True
print(score >= 50 and paid)
The or Operator
or means at least one condition must be true.
day = "Sunday"
print(day == "Saturday" or day == "Sunday")
The result is True because one condition is true.
The not Operator
not changes True to False, and False to True.
logged_in = False
print(not logged_in)
Using Logical Operators in If Statements
age = 22
has_ticket = True
if age >= 18 and has_ticket:
print("You may enter")
Code Along
weather = "rainy"
has_umbrella = True
if weather == "rainy" and has_umbrella:
print("You are ready to go outside")
Mini Challenge
Build an access checker.
Steps:
- Ask the user to enter their age
- Ask if they have an ID (
yesorno) - If age is 18 or more and they have an ID, print:
Access granted - Otherwise, print:
Access denied
Real World Use Case
Apps use logical operators for login checks, age rules, subscriptions, permissions, and many other decisions.
Quiz
- What does
andmean? - What does
ormean? - What does
notdo? - When does
andreturnTrue?
Assignment
Create a weekend checker.
- Ask the user to enter a day
- If the day is Saturday or Sunday, print
Weekend - Otherwise, print
Weekday
Summary
You learned how logical operators help Python check multiple conditions using and, or, and not.