This note is from 9 months ago. You're viewing content from a previous lesson.
Welcome to Designing Solutions Through Programming!!
Our plan for todays class:
Today you will learn three building blocks of programming:
Variables (storing information)
If/Then (making decisions)
Loops (repeating actions)
We’ll use Python. Type the examples exactly as shown. After each example, run the program and observe what changes.
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").
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
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
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.
Create variables: coins = 0, health = 10. Add 3 to coins, subtract 2 from health, print both.
Ask the user for a number, convert it to int, and print its double.
Predict the output, then run:
x = 2
x = x + 2
x = x * 3
print(x)
Programs decide what to do based on conditions. If a condition is true, do one thing; otherwise, do something else.
== equal to, != not equal
<, <=, >, >=
Combine with and, or, not
Indentation matters in Python. The code under if is indented.
# 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
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
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.")
Using = instead of == in conditions (assignment vs comparison).
Missing indentation after if, elif, or else.
Comparing strings without normalizing case/whitespace (.strip().lower() helps).
Ask for a number. If it’s even, print "even", else print "odd".
Ask for a username and a PIN. If both match stored values, print "login success", else print "login failed".
Extend Example D: print "scorching" when temp >= 35.
Loops repeat actions. Use loops to keep asking questions, count things, or process a list of values.
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.
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.
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
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
# 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
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.
Print numbers 1 to 10 using a for loop.
Ask the user for a target n and sum numbers 1..n with a while loop.
Create a loop that keeps asking for passwords until the user types the correct one or enters quit.
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.
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.
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”.
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.
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.