Chapter 03 Logic and Flow Control - Bryantad/Sona GitHub Wiki

🌟 Chapter 3: Making Decisions - Logic and Flow Control

"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!"

Welcome to Program Intelligence! 🧠

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

Understanding Decision Making in Programming

Real-Life Decision Making

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.

šŸ“ The Same Logic in Sona

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!"

šŸŽÆ Accessibility Features for Decision Making

šŸ‘ļø 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.

Your First Decision: The if Statement

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:

  1. Is temperature less than 50? Yes (45 < 50) → Print the jacket message
  2. Is it raining? Yes (true) → Print the umbrella message
  3. Always print "Have a great day!"

Adding Alternative Actions: if/else

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

Multiple Choices: if/else if/else

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.

Comparison Operators: How to Check Conditions

Basic Comparisons

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")
}

Combining Conditions with AND (&&) and OR (||)

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")
}

Real-World Example: Smart Security System

// 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")
}

Introducing Loops: Doing Things Repeatedly

The Problem Loops Solve

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 for Loop: When You Know How Many Times

// āœ… 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! šŸš€")

Real-World for Loop Examples

// 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}")
}

The while Loop: When You Don't Know How Many Times

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.")
    }
}

while Loop for Game Logic

// 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!")
    }
}

Building Your First Complete Game: Number Guessing

Let's build a complete, professional-quality guessing game that showcases everything we've learned:

Version 1: Basic Game

// 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!")
}

Version 2: Enhanced Game with Difficulty Levels

// 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!")

Project: Smart Home Automation Logic

Now let's build a practical smart home system that makes decisions based on multiple factors:

Part 1: Basic Automation

// 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)")
    }
}

Part 2: Advanced Automation with Scenarios

// 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")
}

Part 3: Interactive Home Control

// 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.")
    }
}

Understanding and Fixing Errors

Common Logic Errors

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
}

Debugging Strategies

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")
    }
}

Chapter 3 Summary

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!

Key Concepts Mastered

āœ… 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

Skills You Can Now Demonstrate

  • 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

Real Projects You Built

  • 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

Professional Skills Developed

  • 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

Advanced Practice Challenges

Ready to test your skills? Try these challenges:

Challenge 1: Advanced Calculator

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

Challenge 2: Personal Finance Advisor

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

Challenge 3: Game Collection Manager

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

Looking Ahead to Chapter 4

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

Before Moving On - Self-Check

Make sure you can confidently:

  1. Write conditional statements that handle multiple scenarios appropriately
  2. Use loops effectively to eliminate repetitive code
  3. Combine logical operators to create complex decision-making logic
  4. Validate user input and handle errors gracefully
  5. Debug logical errors using systematic approaches
  6. Build interactive programs with user-friendly interfaces

Your Programming Journey Progress

šŸŽ‰ 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

āš ļø **GitHub.com Fallback** āš ļø