🐍 Python Course 9: Combining Conditions

🎯 Learning Objectives

After completing this section, you will understand:

⚡ Prerequisites

  • Understanding of basic conditions
  • Knowledge of if statements
  • Basic comparison operators

1. Logical Operators

Python provides three logical operators to combine conditions:

Basic Logical Operators

# Using and age = 25 income = 50000 if age >= 21 and income >= 40000: print("Loan approved") # Using or day = "Saturday" if day == "Saturday" or day == "Sunday": print("It's the weekend!") # Using not is_working = False if not is_working: print("Time to relax")

2. Combining Conditions

You can combine multiple conditions to create complex logical expressions:

# Multiple conditions age = 25 has_license = True has_insurance = True if age >= 18 and has_license and has_insurance: print("You can rent a car") # Mixing and/or is_sunny = True temperature = 75 is_weekend = True if (is_sunny and temperature > 70) or is_weekend: print("Let's go to the beach!")

Tips for combining conditions:

3. Order of Operations

Logical operators have a specific order of evaluation:

Operator Precedence

  1. not (highest precedence)
  2. and
  3. or (lowest precedence)
# Order matters x = 5 y = 10 z = 15 # These are different: if x < y and y < z: # Evaluated as: (x < y) and (y < z) print("Numbers in order") if not x > y or z > y: # Evaluated as: (not (x > y)) or (z > y) print("At least one condition is true")

4. Common Patterns

Here are some common patterns when combining conditions:

Range Checks

# Check if number is in range number = 75 if number >= 0 and number <= 100: print("Valid percentage")

Multiple Options

# Check multiple valid options color = "red" if color == "red" or color == "blue" or color == "green": print("Primary color")
📝 Exercise: Login System

Create a simple login system with username and password:

# Valid credentials VALID_USERNAME = "admin" VALID_PASSWORD = "secret123" # Get user input username = input("Username: ") password = input("Password: ") # Check credentials if username == VALID_USERNAME and password == VALID_PASSWORD: print("Access granted!") else: print("Access denied!")
📝 Exercise: Temperature Classifier

Classify temperature based on multiple conditions:

temp = float(input("Enter temperature: ")) if temp < 0: print("Freezing!") elif temp >= 0 and temp < 20: print("Cold") elif temp >= 20 and temp < 30: print("Pleasant") else: print("Hot!")

🎉 Summary

You've learned about:

⬅️ Previous

Course 8: Simple Loops

➡️ Next

Course 10: More Loops