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.")
Output
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.")
Output
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!")
Output
Please log in first.

Truth Table

A B A and B A or B not A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

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.")
Output
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_empty over is_empty == False
  • Keep conditions readable — split very long conditions across multiple lines

Common Mistakes

  • Using && or || instead of and / or (Python uses words, not symbols)
  • Forgetting operator precedence: not runs before and, which runs before or
  • Writing if x == 1 or 2: instead of if x == 1 or x == 2:

Practice Exercises

  1. Ask for a username and password. Print "Access granted" only if both are correct.
  2. Check if a number is between 1 and 100 (inclusive) using and.
  3. 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.