Past Lesson Note

This note is from 9 months ago. You're viewing content from a previous lesson.

Daily Note for August 26, 2025 Past Lesson

Welcome to Designing Solutions Through Programming!!

Our plan for todays class:

  1. Welcome here. We are learning to code today! There are three big ideas:
     
    1. Variables
    2. Control flow: if / then statements
    3. Control flow: loops

Today you will learn three building blocks of programming:

  1. Variables (storing information)

  2. If/Then (making decisions)

  3. Loops (repeating actions)

We’ll use Python. Type the examples exactly as shown. After each example, run the program and observe what changes.


1) Variables

What is a variable?

A variable is a named box that stores a value. You give the box a name (like score), and put something inside (like 10 or "hello").

Python basics

  • Use = to put a value into a variable: score = 10

  • Names: letters, numbers, and underscores; must start with a letter or underscore
    Examples: total, player_name, level2
    Not allowed: 2level, player-name, class (reserved word)

  • Common types:

    • int (integer): 3, -12

    • float (decimal): 3.14, 0.5

    • str (string/text): "hello", 'Alice'

    • bool (true/false): True, False

Example A: creating and updating variables

# Example A
score = 0        # start at zero
lives = 3        # player has 3 lives
player_name = "Ada"

print("Name:", player_name)
print("Score:", score)
print("Lives:", lives)

# update values
score = score + 5
lives = lives - 1

print("After update -> Score:", score, "Lives:", lives)

Trace it mentally: score goes 0 → 5, lives goes 3 → 2.

Example B: reading input and converting types

# Example B
name = input("Enter your name: ")      # input returns a string
age_text = input("Enter your age: ")
age = int(age_text)                    # convert text to an integer

print("Hello", name, "next year you will be", age + 1)

If you forget int(...), age + 1 will crash, because "15" + 1 is invalid. Conversion fixes that.

Quick practice

  1. Create variables: coins = 0, health = 10. Add 3 to coins, subtract 2 from health, print both.

  2. Ask the user for a number, convert it to int, and print its double.

  3. Predict the output, then run:

    x = 2
    x = x + 2
    x = x * 3
    print(x)
    

2) Control Flow: If/Then (decisions)

What is an if/then?

Programs decide what to do based on conditions. If a condition is true, do one thing; otherwise, do something else.

Conditions and comparisons

  • == equal to, != not equal

  • <, <=, >, >=

  • Combine with and, or, not

  • Indentation matters in Python. The code under if is indented.

Example C: simple if/else

# Example C
score = int(input("Enter your score: "))

if score >= 10:
    print("You unlocked the Bronze Badge!")
else:
    print("Keep going—you can reach 10.")

Example D: if/elif/else (multiple branches)

# Example D
temp = int(input("Temperature (C): "))

if temp >= 30:
    print("It's hot.")
elif temp >= 15:
    print("It's mild.")
else:
    print("It's cold.")

Example E: string comparison and logical operators

# Example E
password = input("Enter password: ")

if password == "opensesame":
    print("Access granted.")
else:
    print("Access denied.")

# combining conditions
age = int(input("Age: "))
has_ticket_text = input("Do you have a ticket? (yes/no): ").strip().lower()
has_ticket = (has_ticket_text == "yes")

if age >= 13 and has_ticket:
    print("Welcome to the show!")
else:
    print("Sorry, requirements not met.")

Common mistakes

  • Using = instead of == in conditions (assignment vs comparison).

  • Missing indentation after if, elif, or else.

  • Comparing strings without normalizing case/whitespace (.strip().lower() helps).

Quick practice

  1. Ask for a number. If it’s even, print "even", else print "odd".

  2. Ask for a username and a PIN. If both match stored values, print "login success", else print "login failed".

  3. Extend Example D: print "scorching" when temp >= 35.


3) Control Flow: Loops (repetition)

Why loops?

Loops repeat actions. Use loops to keep asking questions, count things, or process a list of values.

Two loop types you’ll use now

  • while loop: repeat while a condition is true (good for “keep going until X happens”).

  • for loop: repeat a fixed number of times or over items in a collection.

Example F: while as a game loop

# Example F
lives = 3

while lives > 0:
    print("Lives left:", lives)
    action = input("Type 'hit' to lose a life, or 'quit' to stop: ").strip().lower()
    if action == "hit":
        lives = lives - 1
    elif action == "quit":
        break
    else:
        print("Unknown action.")
print("Loop ended.")

This continues until lives reach 0 or you break by typing quit.

Example G: for with range

# Example G
# range(5) -> 0,1,2,3,4 (five times)
total = 0
for i in range(5):
    total = total + i
    print("i:", i, "total:", total)
print("Final total:", total)

Example H: counting with user input until sentinel (“quit”)

# Example H
count = 0
while True:
    text = input("Enter anything (or 'quit' to stop): ").strip().lower()
    if text == "quit":
        break
    count = count + 1
    print("You have entered", count, "items so far.")
print("You entered", count, "items in total.")

Example I: combine variables + if/then + loop (mini-challenge)

# Example I
# Goal: reach score >= 5 before lives run out
score = 0
lives = 3

while True:
    print("Score:", score, "| Lives:", lives)
    action = input("Action (search/hit/quit): ").strip().lower()

    if action == "quit":
        print("Goodbye.")
        break

    if action == "search":
        score = score + 1
        print("You found a point!")
    elif action == "hit":
        lives = lives - 1
        print("Ouch! -1 life.")
    else:
        print("Unknown action.")

    # win/lose checks
    if score >= 5:
        print("You win!")
        break
    if lives <= 0:
        print("Game over.")
        break

Common mistakes

  • Infinite loops when the condition never becomes false. Always update variables that control the loop.

  • Off-by-one errors when using range. Remember range(n) goes up to n-1.

Quick practice

  1. Print numbers 1 to 10 using a for loop.

  2. Ask the user for a target n and sum numbers 1..n with a while loop.

  3. Create a loop that keeps asking for passwords until the user types the correct one or enters quit.


Mini-Exercises (apply all three ideas)

  1. Scorekeeper

  • Start score = 0.

  • Loop asking the user to type + or -.

  • + increases score by 2, - decreases score by 1.

  • If score >= 10, print “Win” and stop. If score <= -5, print “Lose” and stop.

  1. Even or Odd Counter

  • Loop: prompt for a number or quit.

  • Use if to detect even vs odd and keep two counters: even_count, odd_count.

  • On quit, print both counters.

  1. Three Tries Login

  • Stored: user = "admin", pin = "1234".

  • Allow up to 3 attempts in a while loop.

  • If both match, print “login success” and stop; else print attempts left.

  • After 3 failures, print “locked”.


Self-Check (IB-style command terms)

  • Identify three variables in your code and state their roles.

  • Describe how your loop controls when the program stops.

  • Explain how your if/then logic changes the program’s behavior based on user input.

  • Evaluate one improvement to your mini-challenge (e.g., different win condition) and justify why it’s better.

Troubleshooting Guide

  • Program crashes on math with input: You probably forgot to convert text to int or float.
    Use value = int(input("...")).

  • if doesn’t run: Check your condition and indentation. Use print(...) to see variable values before the if.

  • Loop never ends: Ensure something inside the loop changes the condition (e.g., decrement lives, or break on quit).

  • Comparing text fails: Normalize input with .strip().lower().


If you can complete the mini-exercises, you’ve used all three core ideas to build small but real programs.