General
Beginner
Control Structures: Making Decisions in Code
69 views
25 min read
Table of Contents
Teaching Programs to Make Decisions
Control structures allow programs to make decisions and repeat actions. They're like the decision-making brain of your program!
Conditional Statements (If/Then/Else)
Conditional statements let your program choose different paths based on conditions, just like how you make decisions in real life.
Basic If Statement
age = 18
if age >= 18:
print("You can vote!")
else:
print("You cannot vote yet.")
// Real-life equivalent:
// IF you are 18 or older, THEN you can vote
// OTHERWISE, you cannot vote yet
Multiple Conditions
Sometimes you need to check multiple conditions:
Multiple If Statements
temperature = 75
if temperature > 80:
print("It's hot! Wear shorts.")
else if temperature > 60:
print("It's nice! Perfect weather.")
else if temperature > 40:
print("It's cool. Bring a jacket.")
else:
print("It's cold! Bundle up!")
Comparison Operators
These help you compare values:
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to
Logical Operators
Combine multiple conditions:
AND- Both conditions must be trueOR- At least one condition must be trueNOT- Opposite of the condition
Logical Operators Example
age = 25
hasLicense = true
// Using AND
if age >= 18 AND hasLicense == true:
print("You can drive!")
// Using OR
if age < 13 OR age > 65:
print("Special ticket pricing available!")
// Using NOT
if NOT gameOver:
print("Keep playing!")
Real-World Decision Making
Programs make decisions constantly:
- ATM: "If PIN is correct, show account balance"
- Game: "If player health is 0, game over"
- Website: "If user is logged in, show dashboard"
- Weather App: "If it's raining, suggest umbrella"
🎯 Decision Making Exercise
Write conditional logic for these scenarios:
- A program that checks if someone can watch an R-rated movie (age 17+)
- A grade calculator that assigns letter grades based on scores
- A simple login system that checks username and password
Nested Conditions
You can put conditions inside other conditions:
Nested If Example
weather = "sunny"
temperature = 75
if weather == "sunny":
if temperature > 70:
print("Perfect day for the beach!")
else:
print("Sunny but a bit cool.")
else:
print("Maybe stay inside today.")
Best Practices
- Keep conditions simple and readable
- Use meaningful variable names
- Consider all possible cases
- Test your conditions with different values