CodingNic

Control Flow and Logic

Logical Operators

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:

  • and
  • or
  • not

The and Operator

and means both conditions must be true.

python
age = 20
has_id = True

print(age >= 18 and has_id)

The result is True because both conditions are true.

Another and Example

python
score = 75
paid = True

print(score >= 50 and paid)

The or Operator

or means at least one condition must be true.

python
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.

python
logged_in = False

print(not logged_in)

Using Logical Operators in If Statements

python
age = 22
has_ticket = True

if age >= 18 and has_ticket:
    print("You may enter")

Code Along

python
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 (yes or no)
  • 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

  1. What does and mean?
  2. What does or mean?
  3. What does not do?
  4. When does and return True?

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.