Chapter 03 Logic and Flow Control - Bryantad/Sona GitHub Wiki
"Teaching your computer to make decisions is like giving it a brain. Suddenly, your programs become intelligent and can handle any situation you throw at them. This works for everyone - from 12-year-olds to 55+ professionals!"
You've mastered variables and data - now it's time to make your programs truly intelligent! In this chapter, we'll teach your code how to make decisions, repeat tasks efficiently, and handle different situations gracefully.
This chapter is designed for all learning styles and accessibility needs - whether you need step-by-step explanations, visual examples, or just want to jump into coding. We'll use plenty of real-world examples and thinking blocks to make everything clear.
By the end, you'll have built a complete guessing game and a smart home automation system that actually works!
Think of this chapter as teaching your programs to think: "If this happens, do that. If something else happens, do something different. Keep doing this until you're done."
By the end of this chapter, you'll be able to:
- ā Write programs that make intelligent decisions based on data
- ā Use loops to repeat tasks efficiently without writing duplicate code
- ā Build interactive programs that respond to user choices
- ā Handle errors gracefully with Sona's gentle error messages
- ā Create a complete guessing game with multiple difficulty levels
- ā Design a smart home automation system
- ā Use accessibility features to make complex logic easier to understand
Before we dive into code, let's think about how you make decisions in real life. This helps everyone understand, regardless of age or learning style:
š Getting Dressed in the Morning:
- Look outside ā If it's raining ā Grab an umbrella
- Check the temperature ā If it's cold ā Wear a jacket
- Check your calendar ā If you have a meeting ā Dress professionally
š Shopping for Groceries:
- Check your budget ā If you have enough money ā Buy the good brand
- Look at expiration dates ā If it expires soon ā Don't buy it
- Check your shopping list ā If you need milk ā Add it to your cart
š® Playing a Game:
- Check your score ā If you have enough points ā Buy an upgrade
- Look at your health ā If it's low ā Find a health potion
- See an enemy ā If it's stronger than you ā Run away
š§ For Neurodivergent Minds: Notice how all these follow the same pattern: Check something ā If condition is true ā Do action. This predictable pattern makes programming logic easier to understand.
Now let's see how this same decision-making works in Sona:
think "Making decisions like we do in real life"
# Weather decision
weather = "rainy"
when weather == "rainy":
show "Don't forget your umbrella!"
show "Wear a raincoat!"
# Budget decision
budget = 50
item_price = 30
when budget >= item_price:
show "You can afford this item!"
calculate remaining = budget - item_price
show "You'll have $" + remaining + " left"
# Game decision
player_health = 25
when player_health < 30:
show "Warning: Your health is low!"
show "Look for a health potion!"
think "Programming decisions work just like real-life decisions!"
šļø For Visual Learners:
# Use clear indentation to show what belongs together
when age >= 18:
show "You can vote!"
show "You can also get a driver's license!"
else:
show "You can't vote yet"
show "But you can still learn about politics!"
š§ For ADHD/Executive Function:
think "Checking if someone can drive"
age = 16
when age >= 16:
think "They're old enough to drive"
show "You can get a learner's permit!"
else:
think "They're too young to drive"
show "You can't drive yet, but you can ride a bike!"
š§ For Auditory Learners:
- Read your conditions out loud: "When age is greater than or equal to 18"
- Use descriptive variable names that sound clear when spoken
- Think blocks help you "talk through" your logic
Choosing What to Eat:
- Check the time ā If it's morning ā Consider breakfast options
- Look in the fridge ā If you have eggs ā Maybe make an omelet
- Check your budget ā If you're low on money ā Cook at home instead of ordering out
Programming decisions work exactly the same way! You check conditions and do different things based on what you find.
Here's how we translate real-life decisions into Sona code:
// Checking the weather
let temperature = 45
let is_raining = true
if temperature < 50 {
print("It's cold - wear a jacket!")
}
if is_raining {
print("Don't forget your umbrella!")
}
print("Have a great day!")
When you run this program, Sona checks each condition:
- Is temperature less than 50? Yes (45 < 50) ā Print the jacket message
- Is it raining? Yes (true) ā Print the umbrella message
- Always print "Have a great day!"
Sometimes you want to do one thing OR another, not both:
let age = 20
if age >= 18 {
print("You can vote!")
} else {
print("You're not old enough to vote yet.")
}
// Only ONE of these messages will print, never both
When you have more than two options:
let score = 87
if score >= 90 {
print("Excellent! You got an A!")
} else if score >= 80 {
print("Great job! You got a B!")
} else if score >= 70 {
print("Good work! You got a C!")
} else if score >= 60 {
print("You passed with a D.")
} else {
print("You need to study more for next time.")
}
Sona checks each condition in order and stops at the first one that's true.
let age = 25
let name = "Alex"
let score = 95
// Equality (exactly the same)
if age == 25 {
print("Age is exactly 25")
}
if name == "Alex" {
print("Hello, Alex!")
}
// Not equal
if score != 100 {
print("Not a perfect score")
}
// Greater than / less than
if age > 21 {
print("Can legally drink (in US)")
}
if score >= 90 {
print("Excellent score!")
}
if age < 65 {
print("Not retirement age yet")
}
if score <= 100 {
print("Score is within normal range")
}
Sometimes you need to check multiple things at once:
let age = 25
let has_license = true
let has_car = false
let is_weekend = true
// AND: Both conditions must be true
if age >= 16 && has_license {
print("Can legally drive")
}
// OR: At least one condition must be true
if has_car || is_weekend {
print("Good day for a road trip!")
}
// Complex combinations
if (age >= 25 && has_license) || (age >= 18 && has_car) {
print("Can rent a car")
}
// NOT: Flipping true/false
if !has_car {
print("Might need to take public transport")
}
// Smart home security system
let current_time = 22 // 10 PM (24-hour format)
let is_door_locked = false
let motion_detected = true
let owner_home = false
print("=== Home Security Check ===")
// Check if it's night time
if current_time >= 22 || current_time <= 6 {
print("š Night mode activated")
// Security checks for night time
if !is_door_locked {
print("ā ļø WARNING: Door is unlocked at night!")
print("š Automatically locking door...")
is_door_locked = true
}
if motion_detected && !owner_home {
print("šØ ALERT: Motion detected while away!")
print("š± Sending notification to phone...")
print("š¹ Recording security footage...")
}
} else {
print("āļø Day mode - normal monitoring")
}
// Always check door status
if is_door_locked {
print("ā
Door is secure")
} else {
print("šŖ Door is unlocked")
}
Imagine you wanted to print the numbers 1 through 10. Without loops, you'd have to write:
// ā The tedious way
print("1")
print("2")
print("3")
print("4")
print("5")
print("6")
print("7")
print("8")
print("9")
print("10")
What if you wanted to print 1 through 1000? You'd be typing for hours! Loops solve this problem elegantly.
// ā
The smart way
for i in range(1, 11) { // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
print(i)
}
This does exactly the same thing as the 10 lines above, but it's much more flexible:
// Want to count to 100? Just change one number!
for i in range(1, 101) {
print(i)
}
// Count by 2s?
for i in range(2, 21, 2) { // 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
print(i)
}
// Countdown?
for i in range(10, 0, -1) { // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
print(i)
}
print("Blast off! š")
// Calculate compound interest
let principal = 1000
let interest_rate = 0.05 // 5%
print("Year | Balance")
print("-----|--------")
for year in range(1, 11) {
principal = principal * (1 + interest_rate)
print("${year} | $${principal}")
}
// Generate a multiplication table
let number = 7
print("Multiplication table for ${number}:")
for i in range(1, 13) {
let result = number * i
print("${number} Ć ${i} = ${result}")
}
Sometimes you need to keep doing something until a condition changes:
// Keep asking until user gives valid input
let valid_input = false
let user_age = 0
while !valid_input {
print("Please enter your age:")
let age_input = input()
user_age = parse_number(age_input)
if user_age > 0 && user_age < 150 {
valid_input = true
print("Thank you! Age ${user_age} recorded.")
} else {
print("Please enter a valid age between 1 and 149.")
}
}
// Simple number guessing game setup
let secret_number = 42
let guess = 0
let attempts = 0
print("I'm thinking of a number between 1 and 100!")
while guess != secret_number {
print("What's your guess?")
let guess_input = input()
guess = parse_number(guess_input)
attempts = attempts + 1
if guess < secret_number {
print("Too low! Try again.")
} else if guess > secret_number {
print("Too high! Try again.")
} else {
print("Perfect! You got it in ${attempts} attempts!")
}
}
Let's build a complete, professional-quality guessing game that showcases everything we've learned:
// Number Guessing Game v1.0
print("šÆ Welcome to the Number Guessing Game! šÆ")
print("I'm thinking of a number between 1 and 100.")
print("Can you guess what it is?")
print("")
// Generate a random number (for now, we'll use a fixed number)
let secret_number = 67 // In a real game, this would be random
let guess = 0
let attempts = 0
let max_attempts = 7
while guess != secret_number && attempts < max_attempts {
print("Attempt ${attempts + 1} of ${max_attempts}")
print("Enter your guess:")
let guess_input = input()
// Validate input
if guess_input == "" {
print("Please enter a number!")
continue // Skip to next loop iteration
}
guess = parse_number(guess_input)
attempts = attempts + 1
// Check if guess is in valid range
if guess < 1 || guess > 100 {
print("Please guess a number between 1 and 100!")
attempts = attempts - 1 // Don't count invalid guesses
continue
}
// Provide feedback
if guess < secret_number {
let difference = secret_number - guess
if difference > 20 {
print("Way too low! š")
} else if difference > 10 {
print("Too low! š")
} else {
print("A little low! āļø")
}
} else if guess > secret_number {
let difference = guess - secret_number
if difference > 20 {
print("Way too high! š")
} else if difference > 10 {
print("Too high! š")
} else {
print("A little high! āļø")
}
} else {
print("š Congratulations! You guessed it! š")
print("The number was ${secret_number}")
print("You did it in ${attempts} attempts!")
break // Exit the loop early
}
print("") // Empty line for readability
}
// Check if player ran out of attempts
if guess != secret_number {
print("š
Game over! You ran out of attempts.")
print("The number was ${secret_number}")
print("Better luck next time!")
}
// Number Guessing Game v2.0 - Enhanced Edition
print("šÆ Enhanced Number Guessing Game! šÆ")
print("Choose your difficulty level:")
print("1. Easy (1-50, 10 attempts)")
print("2. Medium (1-100, 7 attempts)")
print("3. Hard (1-200, 5 attempts)")
print("4. Expert (1-500, 10 attempts)")
let difficulty_input = input()
let difficulty = parse_number(difficulty_input)
let max_number = 100
let max_attempts = 7
let difficulty_name = "Medium"
if difficulty == 1 {
max_number = 50
max_attempts = 10
difficulty_name = "Easy"
} else if difficulty == 2 {
max_number = 100
max_attempts = 7
difficulty_name = "Medium"
} else if difficulty == 3 {
max_number = 200
max_attempts = 5
difficulty_name = "Hard"
} else if difficulty == 4 {
max_number = 500
max_attempts = 10
difficulty_name = "Expert"
} else {
print("Invalid choice, using Medium difficulty.")
}
print("\nš® ${difficulty_name} Mode Selected!")
print("I'm thinking of a number between 1 and ${max_number}")
print("You have ${max_attempts} attempts. Good luck!")
print("")
// For demonstration, let's calculate the secret number based on difficulty
let secret_number = (max_number / 3) + (difficulty * 7) // Simplified random number
secret_number = secret_number % max_number + 1 // Keep it in range
let guess = 0
let attempts = 0
let hints_used = 0
let max_hints = 2
while guess != secret_number && attempts < max_attempts {
print("ā" * 40) // Visual separator
print("Attempt ${attempts + 1} of ${max_attempts}")
// Offer hints
if hints_used < max_hints && attempts > 2 {
print("š” Type 'hint' for a clue (${max_hints - hints_used} hints remaining)")
}
print("Enter your guess (1-${max_number}):")
let user_input = input()
// Handle hint request
if user_input.lower() == "hint" && hints_used < max_hints {
hints_used = hints_used + 1
print("š” Hint ${hints_used}:")
if hints_used == 1 {
// Give range hint
if secret_number <= max_number / 2 {
print("The number is in the lower half (1-${max_number / 2})")
} else {
print("The number is in the upper half (${max_number / 2 + 1}-${max_number})")
}
} else {
// Give odd/even hint
if secret_number % 2 == 0 {
print("The number is even")
} else {
print("The number is odd")
}
}
continue
}
// Validate and process guess
if user_input == "" {
print("ā Please enter a number!")
continue
}
guess = parse_number(user_input)
attempts = attempts + 1
if guess < 1 || guess > max_number {
print("ā Please guess between 1 and ${max_number}!")
attempts = attempts - 1
continue
}
// Provide intelligent feedback
if guess < secret_number {
let difference = secret_number - guess
let percentage_off = (difference * 100) / max_number
if percentage_off > 50 {
print("š„ Way too low! You're not even close!")
} else if percentage_off > 25 {
print("š Too low! But you're getting warmer...")
} else if percentage_off > 10 {
print("š A bit low! You're pretty close!")
} else {
print("š„ Very close! Just a little higher!")
}
} else if guess > secret_number {
let difference = guess - secret_number
let percentage_off = (difference * 100) / max_number
if percentage_off > 50 {
print("š„ Way too high! You're not even close!")
} else if percentage_off > 25 {
print("š Too high! But you're getting warmer...")
} else if percentage_off > 10 {
print("š A bit high! You're pretty close!")
} else {
print("š„ Very close! Just a little lower!")
}
} else {
// Winner!
print("š" * 20)
print("š CONGRATULATIONS! YOU WON! š")
print("š" * 20)
print("")
print("⨠The number was ${secret_number}")
print("š You guessed it in ${attempts} attempts!")
print("š” You used ${hints_used} hints")
// Calculate score
let base_score = 1000
let attempt_penalty = attempts * 50
let hint_penalty = hints_used * 100
let final_score = base_score - attempt_penalty - hint_penalty
print("šÆ Your score: ${final_score} points")
// Performance feedback
if attempts <= 3 {
print("š AMAZING! You're a guessing genius!")
} else if attempts <= 5 {
print("š Great job! Solid guessing skills!")
} else {
print("š Good work! Practice makes perfect!")
}
break
}
// Encouragement based on remaining attempts
let remaining = max_attempts - attempts
if remaining > 0 {
print("š ${remaining} attempts remaining")
}
}
// Game over handling
if guess != secret_number {
print("š" * 30)
print("š
Game Over!")
print("š" * 30)
print("")
print("šÆ The number was: ${secret_number}")
print("š You used all ${max_attempts} attempts")
print("šŖ Don't give up! Try again to improve!")
}
print("\nš® Thanks for playing! Come back anytime!")
Now let's build a practical smart home system that makes decisions based on multiple factors:
// Smart Home Automation System v1.0
print("š Smart Home Control System š ")
print("Initializing sensors and devices...")
print("")
// Sensor readings (in a real system, these would come from actual sensors)
let current_time = 19 // 7 PM
let outdoor_temperature = 35 // Fahrenheit
let indoor_temperature = 72
let occupancy_detected = true
let door_is_locked = false
let lights_are_on = false
let hvac_mode = "off" // off, heating, cooling
let security_armed = false
print("=== Current Status ===")
print("š Time: ${current_time}:00")
print("š”ļø Outdoor Temperature: ${outdoor_temperature}°F")
print("š Indoor Temperature: ${indoor_temperature}°F")
print("š„ Occupancy: ${occupancy_detected ? 'Detected' : 'Empty'}")
print("šŖ Door: ${door_is_locked ? 'Locked' : 'Unlocked'}")
print("š” Lights: ${lights_are_on ? 'On' : 'Off'}")
print("āļø HVAC: ${hvac_mode}")
print("š Security: ${security_armed ? 'Armed' : 'Disarmed'}")
print("")
print("=== Smart Automation Decisions ===")
// Lighting automation
if current_time >= 18 || current_time <= 7 { // Evening or early morning
if occupancy_detected && !lights_are_on {
lights_are_on = true
print("š” Turning on lights (evening/night mode)")
}
} else { // Daytime
if lights_are_on && !occupancy_detected {
lights_are_on = false
print("š” Turning off lights (daytime, no occupancy)")
}
}
// Temperature control
let target_temperature = 70
let temperature_tolerance = 3
if occupancy_detected {
if indoor_temperature < (target_temperature - temperature_tolerance) {
if hvac_mode != "heating" {
hvac_mode = "heating"
print("š„ Starting heating system")
}
} else if indoor_temperature > (target_temperature + temperature_tolerance) {
if hvac_mode != "cooling" {
hvac_mode = "cooling"
print("āļø Starting cooling system")
}
} else {
if hvac_mode != "off" {
hvac_mode = "off"
print("š”ļø Temperature comfortable, turning off HVAC")
}
}
} else {
// Energy saving when nobody's home
if hvac_mode != "off" {
hvac_mode = "off"
print("š° Energy save mode: Turning off HVAC (no occupancy)")
}
}
// Security automation
if current_time >= 22 || current_time <= 6 { // Night time
if !door_is_locked {
door_is_locked = true
print("š Auto-locking door (night mode)")
}
if occupancy_detected && !security_armed {
print("š Family is home, keeping security disarmed")
} else if !occupancy_detected && !security_armed {
security_armed = true
print("š”ļø Auto-arming security (away at night)")
}
} else {
// Daytime security logic
if !occupancy_detected && !security_armed {
security_armed = true
print("š”ļø Arming security (away during day)")
} else if occupancy_detected && security_armed {
security_armed = false
print("š Disarming security (occupancy detected)")
}
}
// Advanced Smart Home Scenarios
print("\n=== Advanced Scenario Detection ===")
// Determine current scenario
let current_scenario = "normal"
if current_time >= 22 || current_time <= 6 {
current_scenario = "night"
} else if current_time >= 6 && current_time <= 9 {
current_scenario = "morning"
} else if current_time >= 17 && current_time <= 21 {
current_scenario = "evening"
} else {
current_scenario = "day"
}
print("š Current scenario: ${current_scenario}")
// Scenario-based automation
if current_scenario == "morning" {
print("āļø Morning routine activated:")
if occupancy_detected {
print(" ā Starting coffee maker")
print(" š» Playing morning news")
if outdoor_temperature < 40 {
print(" š„ Pre-heating car")
}
// Gradual lighting
print(" š” Gradually increasing light brightness")
}
} else if current_scenario == "evening" {
print("š
Evening routine activated:")
if occupancy_detected {
print(" š” Setting mood lighting")
print(" šŗ Turning on entertainment system")
if outdoor_temperature < indoor_temperature - 10 {
print(" š„ Pre-warming bedroom")
}
}
} else if current_scenario == "night" {
print("š Night routine activated:")
print(" š Enabling silent mode")
print(" š” Dimming all lights")
print(" š Securing all entry points")
if indoor_temperature > 75 {
print(" āļø Cooling for better sleep")
}
}
// Weather-based decisions
print("\n=== Weather-Based Automation ===")
if outdoor_temperature <= 32 {
print("š§ Freezing weather detected:")
print(" š§ Protecting pipes from freezing")
print(" š Recommending car warm-up")
if indoor_temperature < 68 {
print(" š„ Boosting heating for comfort")
}
} else if outdoor_temperature >= 85 {
print("š„ Hot weather detected:")
print(" šØ Pre-cooling house")
print(" šæ Activating plant watering system")
print(" āļø Closing smart blinds")
}
// Energy optimization
print("\n=== Energy Optimization ===")
let energy_mode = "normal"
// Determine if we should be in energy-saving mode
if !occupancy_detected {
energy_mode = "saving"
} else if current_time >= 14 && current_time <= 19 {
energy_mode = "peak" // Peak electricity hours
}
if energy_mode == "saving" {
print("š° Energy saving mode:")
print(" š± All non-essential devices to standby")
print(" š”ļø Relaxing temperature targets")
print(" š” Minimum lighting only")
} else if energy_mode == "peak" {
print("ā” Peak hours detected:")
print(" ā° Delaying non-urgent tasks")
print(" š Using battery backup when possible")
print(" š”ļø Pre-cooling/heating before peak rates")
}
// Interactive home control system
print("\n" + "=" * 50)
print("š® Interactive Home Control")
print("=" * 50)
let user_wants_control = true
while user_wants_control {
print("\nWhat would you like to control?")
print("1. š” Lighting")
print("2. š”ļø Temperature")
print("3. š Security")
print("4. š View Status")
print("5. šŖ Exit")
let choice_input = input()
let choice = parse_number(choice_input)
if choice == 1 {
print("\nš” Lighting Control:")
print("Current status: ${lights_are_on ? 'On' : 'Off'}")
print("Toggle lights? (yes/no)")
let light_choice = input().lower()
if light_choice == "yes" {
lights_are_on = !lights_are_on
print("š” Lights are now ${lights_are_on ? 'ON' : 'OFF'}")
}
} else if choice == 2 {
print("\nš”ļø Temperature Control:")
print("Current temperature: ${indoor_temperature}°F")
print("Target temperature: ${target_temperature}°F")
print("HVAC mode: ${hvac_mode}")
print("Set new target temperature (60-80):")
let temp_input = input()
let new_temp = parse_number(temp_input)
if new_temp >= 60 && new_temp <= 80 {
target_temperature = new_temp
print("šÆ Target temperature set to ${target_temperature}°F")
// Immediate HVAC adjustment
if indoor_temperature < target_temperature - 2 {
hvac_mode = "heating"
print("š„ Starting heating system")
} else if indoor_temperature > target_temperature + 2 {
hvac_mode = "cooling"
print("āļø Starting cooling system")
}
} else {
print("ā Please enter a temperature between 60 and 80°F")
}
} else if choice == 3 {
print("\nš Security Control:")
print("Door locked: ${door_is_locked ? 'Yes' : 'No'}")
print("Security armed: ${security_armed ? 'Yes' : 'No'}")
print("1. Toggle door lock")
print("2. Toggle security system")
print("3. Back to main menu")
let security_choice = parse_number(input())
if security_choice == 1 {
door_is_locked = !door_is_locked
print("šŖ Door is now ${door_is_locked ? 'LOCKED' : 'UNLOCKED'}")
} else if security_choice == 2 {
security_armed = !security_armed
print("š”ļø Security is now ${security_armed ? 'ARMED' : 'DISARMED'}")
}
} else if choice == 4 {
print("\nš Current System Status:")
print("ā" * 30)
print("š Time: ${current_time}:00")
print("š”ļø Indoor: ${indoor_temperature}°F | Target: ${target_temperature}°F")
print("š” Lights: ${lights_are_on ? 'On' : 'Off'}")
print("āļø HVAC: ${hvac_mode}")
print("šŖ Door: ${door_is_locked ? 'Locked' : 'Unlocked'}")
print("š”ļø Security: ${security_armed ? 'Armed' : 'Disarmed'}")
print("š Scenario: ${current_scenario}")
print("ā” Energy Mode: ${energy_mode}")
} else if choice == 5 {
user_wants_control = false
print("š Goodbye! Your smart home is still monitoring and automating.")
} else {
print("ā Invalid choice. Please select 1-5.")
}
}
Error 1: Using = instead of ==
// ā This assigns, doesn't compare!
if age = 18 {
print("Can vote")
}
// ā
This compares
if age == 18 {
print("Can vote")
}
Error 2: Infinite Loops
// ā This runs forever!
let counter = 1
while counter <= 10 {
print(counter)
// Forgot to increment counter!
}
// ā
This stops at 10
let counter = 1
while counter <= 10 {
print(counter)
counter = counter + 1
}
Error 3: Logical Operator Confusion
// ā This is wrong - uses OR instead of AND
if age >= 18 || has_permission {
print("Can enter") // Either condition allows entry
}
// ā
This requires both conditions
if age >= 18 && has_permission {
print("Can enter") // Must satisfy both
}
1. Add Print Statements to See What's Happening
let x = 10
let y = 5
print("Before calculation: x = ${x}, y = ${y}") // Debug output
if x > y {
print("x is greater") // Debug: which branch executes?
let result = x * 2
print("Result calculated: ${result}") // Debug: what's the result?
} else {
print("y is greater or equal")
}
2. Break Complex Conditions into Steps
// ā Hard to debug
if (age >= 18 && has_license && insurance_valid) || (age >= 16 && has_permit && adult_present) {
print("Can drive")
}
// ā
Easier to debug
let is_adult_driver = (age >= 18 && has_license && insurance_valid)
let is_student_driver = (age >= 16 && has_permit && adult_present)
print("Adult driver qualified: ${is_adult_driver}") // Debug info
print("Student driver qualified: ${is_student_driver}") // Debug info
if is_adult_driver || is_student_driver {
print("Can drive")
}
3. Test Edge Cases
// Test your logic with extreme values
let test_ages = [0, 17, 18, 19, 65, 150]
for age in test_ages {
if age >= 18 {
print("Age ${age}: Can vote")
} else {
print("Age ${age}: Cannot vote")
}
}
Congratulations! You've learned how to make your programs intelligent and interactive. This is where programming really starts to feel magical - your code can now think and respond!
ā Conditional Logic: Making decisions with if/else statements ā Comparison Operators: Testing relationships between values (==, !=, <, >, <=, >=) ā Logical Operators: Combining conditions with AND (&&), OR (||), and NOT (!) ā for Loops: Repeating code a specific number of times ā while Loops: Repeating code until a condition changes ā Complex Program Flow: Building interactive applications with multiple decision points ā Error Prevention: Validating input and handling edge cases gracefully
- Write programs that make intelligent decisions based on user input
- Use loops to eliminate repetitive code and handle collections of data
- Build interactive applications that respond to user choices
- Validate user input and provide helpful error messages
- Debug logical errors in conditional statements and loops
- Create complex applications with multiple features and scenarios
- Enhanced Number Guessing Game: Complete game with difficulty levels, hints, and scoring
- Smart Home Automation System: Multi-scenario automation with sensor-based decisions
- Interactive Control Interfaces: User-friendly menus and control systems
- User Experience Design: Creating intuitive interfaces and helpful feedback
- Input Validation: Ensuring programs handle invalid data gracefully
- Modular Logic: Breaking complex decisions into manageable components
- Testing Strategies: Verifying program behavior with various inputs
- Error Handling: Anticipating and managing potential problems
Ready to test your skills? Try these challenges:
Create a calculator that:
- Supports multiple operations in sequence
- Has memory functions (store, recall, clear)
- Provides a history of calculations
- Handles division by zero gracefully
- Offers both simple and scientific modes
Build a program that:
- Analyzes spending patterns
- Recommends budget adjustments
- Calculates savings goals timelines
- Provides investment advice based on age and income
- Tracks progress toward financial goals
Develop a system that:
- Manages a video game collection
- Tracks completion status and ratings
- Recommends games based on preferences
- Calculates collection statistics
- Manages wishlist and purchase planning
In the next chapter, "Organizing Your Code - Functions and Modules," we'll learn how to break our programs into reusable pieces. You'll discover:
- How to write custom functions that solve specific problems
- When and why to create functions instead of repeating code
- Advanced function techniques like default parameters and return values
- Organizing code into modules for larger projects
- Building a comprehensive personal utility library
Make sure you can confidently:
- Write conditional statements that handle multiple scenarios appropriately
- Use loops effectively to eliminate repetitive code
- Combine logical operators to create complex decision-making logic
- Validate user input and handle errors gracefully
- Debug logical errors using systematic approaches
- Build interactive programs with user-friendly interfaces
š Major Milestone Achieved: Your programs can now think and make decisions!
You've transformed from writing simple, linear programs to creating intelligent applications that can:
- Respond differently to various situations
- Handle user interaction gracefully
- Repeat tasks efficiently
- Validate and process complex input
- Provide engaging user experiences
This is a huge leap forward. You're now writing programs that feel alive and responsive - the kind of software that people actually want to use!
Ready for Chapter 4? Let's learn how to organize our code like professional developers!
"Logic is the beginning of wisdom, not the end. Now that your programs can think, let's teach them to be organized and reusable!" - Andre