04

Phase 1 - Level 4: Logical Operators & Compound Statements

Chapter 4 • Intermediate

60 min

Phase 1 - Level 4: Logical Operators & Compound Statements

Introduction

Logical operators allow you to combine multiple conditions into complex decision-making logic. This is essential for real-world programming scenarios.

Logical Operators Deep Dive

AND Operator

  • Returns True only if ALL conditions are True
  • Short-circuits: stops evaluating if first condition is False
  • Use when ALL conditions must be satisfied

OR Operator

  • Returns True if ANY condition is True
  • Short-circuits: stops evaluating if first condition is True
  • Use when AT LEAST ONE condition must be satisfied

NOT Operator

  • Reverses the boolean value
  • Use to negate conditions
  • Helps improve readability

Operator Precedence

  1. not (highest)
  2. and
  3. or (lowest)

Use parentheses to clarify intent when mixing operators.

Common Patterns

  • FizzBuzz: Divisible by 3 AND/OR 5
  • Password Validation: Multiple conditions with AND
  • Eligibility Checks: Age AND income requirements
  • Range Validation: Number within range using AND

Best Practices

  1. Use parentheses for clarity
  2. Order conditions by likelihood (short-circuit optimization)
  3. Break complex conditions into variables for readability
  4. Use De Morgan's laws: not (A and B) = (not A) or (not B)

Hands-on Examples

FizzBuzz Problem

# Take a number
num = int(input("Enter a number: "))

# Check divisibility
if num % 3 == 0 and num % 5 == 0:
    print("FizzBuzz")
elif num % 3 == 0:
    print("Fizz")
elif num % 5 == 0:
    print("Buzz")
else:
    print(num)

Check for both conditions first (divisible by 3 AND 5), then individual conditions. Order matters!