Beginner Level • Lesson 2

🤔 Making Decisions

⏱️ 45 minutes 📚 Beginner 🎯 Conditional Logic
🤔

Making Decisions

Learn how to make your programs smart by teaching them to make decisions based on conditions!

What are Conditionals?

Conditionals let your program make decisions. Just like you decide "If it's raining, then I'll take an umbrella," programs can make similar choices using if statements.

💡 Real-World Example: When you use Grab, the app checks "If a driver is nearby, then show them on the map." That's a conditional statement!

The IF Statement

The if statement is the most basic way to make decisions in Python. It checks if a condition is True, and if it is, it runs some code.

Basic IF Statement

age = 12 if age >= 10: print("You are 10 or older!")

What happens: The program checks if age is 10 or greater. If it is, it prints the message.

Comparison Operators

To make decisions, you need to compare values. Python has several comparison operators:

=

Equal (==)

Checks if two values are the same

5 == 5 # True 5 == 3 # False

Not Equal (!=)

Checks if two values are different

5 != 3 # True 5 != 5 # False
>

Greater Than (>)

Checks if first value is larger

10 > 5 # True 5 > 10 # False
<

Less Than (<)

Checks if first value is smaller

5 < 10 # True 10 < 5 # False

Greater or Equal (>=)

Checks if first value is larger or equal

10 >= 10 # True 10 >= 5 # True

Less or Equal (<=)

Checks if first value is smaller or equal

5 <= 5 # True 5 <= 10 # True

IF-ELSE Statements

Sometimes you want to do one thing if the condition is True, and a different thing if it's False. That's where else comes in!

IF-ELSE Example

temperature = 25 if temperature > 30: print("It's hot! Turn on the fan.") else: print("It's cool. No fan needed.")

What happens:

  • If temperature is greater than 30, it prints the first message
  • Otherwise (else), it prints the second message

IF-ELIF-ELSE Statements

What if you have more than two choices? Use elif (short for "else if") to check multiple conditions!

IF-ELIF-ELSE Example

score = 85 if score >= 90: print("Grade: A - Excellent!") elif score >= 80: print("Grade: B - Good job!") elif score >= 70: print("Grade: C - Keep trying!") else: print("Grade: F - Study more!")

What happens: The program checks each condition in order. The first one that's True runs, and the rest are skipped.

Project: Temperature Monitor with LED Indicators

Let's build a temperature monitor that uses LEDs to show if it's hot, normal, or cold!

Materials Needed:

  • Raspberry Pi
  • Temperature sensor (DS18B20 or DHT11)
  • 3 LEDs (Red, Yellow, Green)
  • 3 Resistors (220Ω each)
  • Breadboard and jumper wires

Wiring Instructions:

  1. Red LED: Connect to GPIO 18 (for hot temperature)
  2. Yellow LED: Connect to GPIO 23 (for normal temperature)
  3. Green LED: Connect to GPIO 24 (for cold temperature)
  4. Temperature Sensor: Connect to GPIO 4 (for DS18B20) or GPIO 17 (for DHT11)
  5. Connect all LEDs' short legs to GND via resistors

The Code (Simplified Version):

import RPi.GPIO as GPIO import time # Set up GPIO pins GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Red LED GPIO.setup(23, GPIO.OUT) # Yellow LED GPIO.setup(24, GPIO.OUT) # Green LED # Simulate temperature reading (replace with actual sensor reading) temperature = 25 # This would come from your sensor try: while True: # Turn off all LEDs first GPIO.output(18, GPIO.LOW) GPIO.output(23, GPIO.LOW) GPIO.output(24, GPIO.LOW) # Make decision based on temperature if temperature > 30: GPIO.output(18, GPIO.HIGH) # Red LED on - Hot! print("Temperature: " + str(temperature) + "°C - HOT!") elif temperature >= 20: GPIO.output(23, GPIO.HIGH) # Yellow LED on - Normal print("Temperature: " + str(temperature) + "°C - Normal") else: GPIO.output(24, GPIO.HIGH) # Green LED on - Cold print("Temperature: " + str(temperature) + "°C - Cold") time.sleep(2) # Check every 2 seconds except KeyboardInterrupt: GPIO.cleanup()

Understanding the Code:

  • if temperature > 30: If temperature is above 30°C, turn on red LED
  • elif temperature >= 20: If temperature is 20-30°C, turn on yellow LED
  • else: If temperature is below 20°C, turn on green LED
  • The program checks conditions in order and lights the appropriate LED

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Missing Colon: Don't forget the colon (:) after if, elif, and else
  • Wrong Indentation: Code inside if/else must be indented (use 4 spaces)
  • Using = instead of ==: Use == for comparison, = is for assignment
  • Wrong Order: Check conditions from most specific to least specific
  • Forgetting else: Sometimes you need to handle the "none of the above" case

Summary

You've learned:

  • ✅ Conditionals let programs make decisions
  • if statements check conditions and run code if True
  • else handles what happens when the condition is False
  • elif lets you check multiple conditions
  • ✅ Comparison operators (==, !=, >, <, >=, <=) compare values
  • ✅ You can use conditionals to control hardware like LEDs
🎉 Great Job! You've learned how to make your programs smart by teaching them to make decisions. In the next lesson, you'll learn about loops to repeat actions!

🎮 Try It: Practice Making Decisions!

Practice writing conditional statements. Try these challenges:

📝 Challenge 1: Age Checker

Write code that checks if someone is old enough to watch a movie (age 13+):

📝 Challenge 2: Grade Calculator

Write code that assigns a grade based on score:

  • 90 or above: "A"
  • 80-89: "B"
  • 70-79: "C"
  • Below 70: "F"

📝 Challenge 3: Number Comparison

Write code that compares two numbers and prints which is larger:

💡 Tip: Remember to use == for comparison, not =! And don't forget the colon (:) after if, elif, and else.

🎯 Activity: Temperature Monitor Project

What You'll Build:

Build a temperature monitor that uses different colored LEDs to show the temperature status!

Step-by-Step Instructions:

  1. Gather Materials: Get your Raspberry Pi, 3 LEDs (red, yellow, green), resistors, breadboard, and wires
  2. Wire the LEDs: Connect each LED to a different GPIO pin (18, 23, 24) with resistors
  3. Connect Temperature Sensor: Wire your temperature sensor (if you have one) or use a simulated value
  4. Write the Code: Use if-elif-else statements to control which LED lights up
  5. Test: Run the code and watch the LEDs change based on temperature
  6. Experiment: Try changing the temperature thresholds (30, 20) to different values

Testing Checklist:

  • ✅ Red LED lights when temperature > 30°C
  • ✅ Yellow LED lights when temperature is 20-30°C
  • ✅ Green LED lights when temperature < 20°C
  • ✅ Only one LED lights at a time
🏆 Bonus Challenge: Can you add a fourth LED (blue) that lights up when temperature is exactly 25°C? (Hint: use == for exact match)

💪 Practice Challenges

Challenge 1: Traffic Light Simulator

Write code that simulates a traffic light using if-elif-else:

  • If light is "red", print "STOP"
  • If light is "yellow", print "SLOW DOWN"
  • If light is "green", print "GO"
  • Otherwise, print "Invalid light color"

Challenge 2: Password Checker

Write code that checks if a password is strong enough:

  • If password length >= 8, print "Strong password"
  • If password length >= 5, print "Medium password"
  • Otherwise, print "Weak password"

Challenge 3: Number Type Checker

Write code that checks if a number is positive, negative, or zero:

# Example: number = -5 if number > 0: print("Positive") elif number < 0: print("Negative") else: print("Zero")

Challenge 4: LED Pattern with Conditionals

Modify the temperature monitor to:

  • Blink the red LED 3 times if temperature > 30
  • Blink the yellow LED 2 times if temperature is 20-30
  • Keep green LED on steady if temperature < 20

Challenge 5: Code Detective

What's wrong with this code? Find and fix the mistakes!

age = 15 if age = 18 print("You are 18!") else print("You are not 18")
Click to see the answer
age = 15 if age == 18: # Fixed: use == for comparison, add colon print("You are 18!") else: # Fixed: add colon print("You are not 18")