>_Intro to Python Workbook
A Workbook From

Code For ME

INTRO TO PYTHON
What is Code For ME?

Code For ME is a student-led coding program based in Maine, created to make computer science more accessible, practical, and fun for students.

Through Code For ME, students learn how to code by building things, solving problems, experimenting, and learning one step at a time. This workbook is designed to help you build a strong foundation in Python programming and give you the skills to create your own projects.

Visit Code For ME ↗
In This Workbook

As you work through this workbook, you'll learn how to:

  • Understand the basics of Python
  • Write and run your own programs
  • Use variables, strings, numbers, and other data
  • Make decisions with conditional statements
  • Repeat actions using loops
  • Create your own functions
  • Use what you learn to build your own projects
Your Workbook

This workbook belongs to:

Started on:    Class:

PAGE 2Start Here

How To Use This Notebook

This is a workbook to use while you code. Keep it beside you as you work, flip back to earlier pages when you need a reminder, and use the examples and notes to help you solve problems.

Two color systems are used everywhere

1. The colored tab on the edge of every page tells you which section you're in - flip the notebook sideways and you'll see stripes of color, like binder tabs.

2. The colored boxes tell you what kind of information you're looking at - the color means the same thing on every single page, no matter the topic:

Box colorWhat it means
DefinitionA term is being explained for the first time.
Common MistakeSomething beginners get wrong - including you, and that's fine.
RememberA rule worth memorizing. If you forget everything else, don't forget this.
Try ItA tiny practice question. Actually write the answer in the blank.
Think Of It Like...A real-world comparison to help the idea stick.
Can You Predict This?Read code before running it and guess the output.
Where You'd Use ThisConnects the concept to a real game or art project.
Remember

If you don't remember what something means- a float, a loop, a bug- don't worry. Flip back to the page where it was introduced. This notebook is here to be your reference as you code, so use it whenever you need a quick reminder.

PAGE 3Start Here

Table of Contents

First Steps

  1. Code, Program & Syntax p4
  2. print() p5
  3. print() practice p6
  4. input() p7
  5. Converting input p8

Data & Variables

  1. Variables - the box p9
  2. Naming rules p10
  3. The Data Type Map p11
  4. String basics p12
  5. Strings: quotes & joining p13
  6. String indexing p14
  7. Negative index & len() p15
  8. String methods p16
  9. String mistakes+practice p17
  10. Integer p18
  11. Float p19
  12. Arithmetic operators p20
  13. Compound assignment p21
  14. Type conversion p22
  15. Boolean & comparisons p23
  16. and / or / not p24
  17. None p25
  18. Data types review p26

Control Flow

  1. if statements p27
  2. if / elif / else p28
  3. Nested conditions p29
  4. Control flow practice p30

Loops

  1. What is a loop? p31
  2. for loops, piece by piece p32
  3. range() reference p33
  4. while loops p34
  5. Loop mistakes+practice p35

Functions

  1. What is a function? p36
  2. Defining & calling p37
  3. Parameters vs arguments p38
  4. Return values p39
  5. Functions practice p40

Turtle & Visual Art

  1. Meet turtle p41
  2. Movement commands p42
  3. Coordinate system p43
  4. Color & style p44
  5. Square & triangle p45
  6. Polygons & stars p46
  7. Spirals & flowers p47
  8. Patterns & randomness p48

Randomness

  1. The random module p49
  2. Randomness practice p50

Lists

  1. What is a list? p51
  2. Indexing & changing p52
  3. List methods p53
  4. Lists in games p54

Game Logic

  1. Game state p55
  2. The game loop p56
  3. Game vocabulary I p57
  4. Game vocabulary II p58
  5. Tracing a mini game p59

Debugging

  1. Types of bugs p60
  2. The Bug Detective p61
  3. The Error Museum p62
  4. Debugging checklist p63

Code Reading

  1. Tracing variables p64
  2. What does this do? p65

Project Design

  1. Game Design Blueprint p66
  2. Planning worksheet p67

Toolbox

  1. Symbols cheat sheet p68
  2. Vocabulary A-L p69
  3. Vocabulary M-Z p70
  4. "When do I use this?" p71
  5. Visual analogies p72
  6. Capstone checklist p73
PAGE 4First Steps

Code, Program & Syntax

Here's a list of some of the programming terms you'll see throughout this course!

Definition

Code - written instructions that tell a computer what to do, written in a language it understands (like Python).

Definition

Program - a complete set of code that does something useful when it runs, start to finish. A game is a program. So is a calculator.

Definition

Programming - the act of writing code to build a program. That's what you're learning.

Definition

Syntax - the exact spelling, punctuation, and grammar rules of a language. Miss a colon or a quote mark and Python won't understand you, even if a human would.

Think Of It Like...

Syntax is like spelling and grammar in English. "I are hungry" is understandable to a person but wrong. Python is far less forgiving than a person - one missing symbol and it refuses to run at all.

YOU WRITE CODE  ->  PYTHON READS IT  ->  PYTHON RUNS IT  ->  SOMETHING HAPPENS
   (syntax matters here) ^
Remember

Python runs your code top to bottom, one line at a time, unless something (like a loop or a function) tells it to jump around.

Bonus: Comments

A comment is a note in your code that Python completely ignores - it's for humans, not the computer. Start one with #.

# this line does nothing when the program runs
print("Score:", score)  # this part is a comment too

Use comments to remind future-you why a tricky line exists. You don't need many yet - just know the symbol when you see it.

PAGE 5First Steps

print() - Talking to the Screen

Definition

print() is a built-in Python function (a reusable action) that displays text or values on the screen.

  YOUR CODE            PYTHON PROCESSES IT         SCREEN OUTPUT
print("Hello!")   ------------>  runs  ------------>   Hello!
READY TO CODE?

Try it in the Code For ME Python Sandbox

Write your own Python code and see the output instantly.

Open Python Sandbox →

Syntax

print("some text")

The parentheses () hold what you want to print. Text must be wrapped in quotation marks - this makes it a string (see p12).

print("Hello, world!")
print("Score:")
print(10)
Common Mistake

Forgetting quotation marks around text:

print(Hello)   # ERROR - Python thinks Hello is a variable name

Fix: print("Hello")

Common Mistake

Forgetting a closing parenthesis:

print("Hello!"

Python will wait forever for the ) that never comes.

Try It

Write a line of code that prints your name:

PAGE 6First Steps

print() - More Ways To Use It

Printing multiple things with commas

Separate items with commas - Python automatically puts a space between them.

score = 10
print("Score:", score)   # Score: 10

Printing numbers directly (no quotes needed)

print(5)
print(5 + 2)     # 7  - Python does the math first

f-strings - building a sentence with variables inside

Put an f right before the opening quote, then wrap a variable in { } to drop it into the sentence.

name = "Ava"
score = 42
print(f"{name} scored {score} points!")
# Ava scored 42 points!
Think Of It Like...

An f-string is a fill-in-the-blank sentence. The { } are the blanks; Python fills them in with whatever the variable holds right now.

Can You Predict This?
lives = 3
print(f"Lives left: {lives}")

Output:

Try It

Fix this line so it actually prints the value of score instead of the word "score":

score = 5
print("score")

My fix:

PAGE 7First Steps

input() - Listening to the User

Definition

input() pauses the program, shows an optional message, and waits for the user to type something and press Enter.

name = input("What is your name? ")
print("Hello,", name)
Remember

input() always gives back a string - even if the user types numbers. "25" is text, not the number 25.

   USER TYPES "25"
          v
      input()
          v
     STRING "25"      <- this is what Python actually stores
          v
   (still just text - you can't do math with it yet)
Common Mistake
age = input("How old are you? ")
print(age + 1)    # ERROR - can't add a number to a string

See p8 for the fix.

Where You'd Use This

Asking a player's name before a game starts, asking for a guess in a guessing game, asking "play again? (y/n)".

Try It

Write a line that asks the user "What's your favorite color?" and stores it in a variable called color:

PAGE 8First Steps

Converting input() Into Numbers

Since input() always gives a string, you have to convert it before doing math. Full details on p22 - here's the pattern you'll use constantly.

   USER
    v
  input()
    v
  STRING "25"
    v
  CONVERSION  ->  int("25")
    v
  INTEGER 25   <- now you can do math
Without conversion
age = input("Age? ")
print(age + 1)
# ERROR: can only
# concatenate str
# (not "int") to str
With conversion
age = int(input("Age? "))
print(age + 1)
# works! prints
# age + 1

The three converters you'll use most

FunctionTurns text into...Example
int()a whole numberint("7") -> 7
float()a decimal numberfloat("3.5") -> 3.5
str()text (goes the other way)str(7) -> "7"
Remember

You can convert while asking, in one line: int(input("...")). Read it inside-out: get input -> then convert it.

PAGE 9Data & Variables

Variables - The Labeled Box

Definition

A variable is a name that stores a value so you can use it later. Value just means "a piece of data" - a number, some text, etc.

Think Of It Like...

A variable is a labeled storage box. The label is the variable name. Whatever you put inside is the value. You can look inside anytime, and you can swap out what's inside later.

score = 100

+-------------+
|   score     |   <- the label (variable name)
+-------------+
|    100      |   <- what's inside (the value)
+-------------+

Changing what's in the box

score = 100
score = 150
BEFORE                 AFTER
+-------------+        +-------------+
|   score     |   ->    |   score     |
+-------------+        +-------------+
|    100      |        |    150      |   <- old value is gone, overwritten
+-------------+        +-------------+
Remember

In Python, = means "store this value in this box," not "equals" like in math class. It's called assignment. To check if two things are mathematically equal, you use == (see p23).

Can You Predict This?
score = 5
score = score + 1
print(score)

Output:   (hint: Python reads the right side first, then stores the result)

PAGE 10Data & Variables

Variable Naming Rules

RuleExample
Can use letters, numbers, underscoresplayer_1
Can't start with a number1player (invalid)
No spaces - use underscores insteadhigh_score not high score
Case-sensitiveScore and score are different variables
Can't use Python's reserved wordsfor, if, print (invalid)

Good names vs. bad names

Good
  • lives
  • player_score
  • enemy_x
  • is_game_over
Bad (works, but confusing)
  • x (what is x?)
  • thing2
  • data
  • l (looks like the number 1)
Remember

Good variable names describe what the value means, not what type it is. Six months from now, enemy_health will make sense. e won't.

Try It

Circle the valid variable names:   2lives   player_name   high-score   isAlive   for

PAGE 11Data & Variables

The Data Type Map

Every value in Python has a data type - a category that tells Python what kind of thing it is and what you're allowed to do with it. Here's the whole map you'll learn:

                              DATA
                               |
        +-----------+---------+---------+--------------+
        |           |         |         |              |
      TEXT       NUMBERS   TRUE/FALSE  COLLECTIONS    EMPTY
        |           |         |         |              |
     STRING    +----+----+ BOOLEAN    LIST          NONE
      (str)    |         |  (bool)   (list)        (NoneType)
             INTEGER   FLOAT
              (int)   (float)
TypePython nameExampleAsk yourself
Stringstr"Ava"Is it in quotes?
Integerint7Whole number, no decimal?
Floatfloat7.0Has a decimal point?
BooleanboolTrueIs it a yes/no answer?
Listlist[1,2,3]In square brackets?
NoneNoneTypeNoneIs it "nothing on purpose"?
Definition

A data type (or "type") is the category a value belongs to. Python needs to know the type so it knows what operations make sense - you can add two numbers, but "adding" two Booleans doesn't mean anything.

Try It

Find out any value's type by wrapping it in type():

print(type(5))        # <class 'int'>
print(type("5"))      # <class 'str'>
PAGE 12Data & Variables

String - What Is Text Data?

Definition

A string (str) is text - any sequence of characters wrapped in quotation marks. Letters, numbers, symbols, spaces - all of it counts as a string once it's in quotes.

Think Of It Like...

A string is like beads on a string (that's actually where the name comes from) - each character is a bead, threaded in order.

Examples (strings)Not examples
"hello"hello (no quotes - Python treats this as a variable name)
"42"42 (no quotes - this is an integer)
"Game Over!"True (this is a Boolean)
"" (empty string - still a string!) 

How to create one

message = "You win!"
player_name = "Jordan"
Where You'd Use This

Games: player names, messages ("Game Over"), item names. Visual coding: labels, color names passed to turtle like "red".

Common Mistake
score = "10"
total = score + 5   # ERROR - "10" is text, not a number

Python has no idea how to add a number to text. This is the #1 beginner string bug.

PAGE 13Data & Variables

Strings: Quotes & Joining

Single vs. double quotes

Python doesn't care which you use, as long as you start and end with the same kind.

greeting = 'Hello'
greeting = "Hello"     # identical to Python
Remember

Use double quotes when your text contains an apostrophe: "it's a trap". Using single quotes there ('it's a trap') breaks the string early.

Concatenation - joining strings with +

first = "Ava"
last = "Chen"
full = first + " " + last
print(full)      # Ava Chen
Common Mistake

Forgetting the space string in between -> "AvaChen". The + doesn't add spaces for you.

Repeating strings with *

line = "-" * 10
print(line)     # ----------
Where You'd Use This

Building a divider line, repeating a character for a loading bar, stacking a player's name onto their score in one printed line.

Can You Predict This?
word = "ha"
laugh = word * 3
print(laugh)

Output:

PAGE 14Data & Variables

String Indexing

Definition

Indexing means grabbing one character out of a string by its position number. Python starts counting positions at 0, not 1.

            "PYTHON"

         P    Y    T    H    O    N
         0    1    2    3    4    5     <- index numbers
word = "PYTHON"
print(word[0])     # P
print(word[2])     # T
Remember

Square brackets [ ] after a variable = "give me the character at this position." Counting starts at 0. This trips up every beginner at least once - it's not just you.

Common Mistake
word = "PYTHON"
print(word[6])   # ERROR - index out of range

The last valid index is length - 1. "PYTHON" has 6 letters, so valid indexes are 0-5.

Try It

For word = "GAME", what is word[1]?  

PAGE 15Data & Variables

Negative Indexing & len()

Python also lets you count backward from the end, using negative numbers. -1 is always the last character.

            "PYTHON"

         P    Y    T    H    O    N
        -6   -5   -4   -3   -2   -1    <- negative index numbers
word = "PYTHON"
print(word[-1])    # N  (last letter)
print(word[-2])    # O  (second to last)
Definition

len() returns how many characters are in a string (its length).

word = "PYTHON"
print(len(word))    # 6
Remember

len(word) - 1 always equals the index of the last character. That's why word[-1] is such a handy shortcut - no counting required.

Can You Predict This?
name = "ROBOT"
print(len(name))
print(name[-1])

Output: and

PAGE 16Data & Variables

String Methods

Definition

A method is an action attached to a value, called with a dot: value.method(). String methods never change the original string - they hand back a brand-new one.

MethodWhat it doesExample
.upper()ALL CAPS"hi".upper() -> "HI"
.lower()all lowercase"HI".lower() -> "hi"
.strip()removes spaces from the ends" hi ".strip() -> "hi"
.replace(a,b)swaps all of a for b"cat".replace("c","b") -> "bat"
name = "  Ava  "
clean = name.strip()
print(clean.upper())     # AVA
Where You'd Use This

.upper() for a "GAME OVER" banner. .strip() to clean up messy typed input. .lower() so "YES" and "yes" both count as a valid answer.

Try It

"play again".replace("play", "quit") ->

PAGE 17Data & Variables

String Roundup: Mistakes & Practice

Common Mistake

Mismatched quotes: "hello' - Python needs the same quote type on both ends.

Common Mistake

Treating a number-looking string as a number: "3" + "4" gives "34" (joined text), not 7.

Common Mistake

Off-by-one indexing: expecting word[1] to be the first letter. It's actually the second.


Mini Practice

1

What is the data type of "42"?

2

word = "SPACE" - what is word[0]?   What is word[-1]?

3

What does "go" * 3 print?

4

Find the bug: print('It's a bug') - what's wrong and how would you fix it?

PAGE 18Data & Variables

Integer - Whole Numbers

Definition

An integer (int) is a whole number with no decimal part. It can be positive, negative, or zero.

              INTEGER
                 v
           WHOLE NUMBER
        +--------+--------+
     positive    zero    negative
        5          0        -12
IntegersNot integers
5, 0, -12, 1003.14 (has a decimal)  -  "5" (it's text)
Where You'd Use This

Games: score, lives, age, number of enemies, number of repetitions in a loop. Visual coding: pixel coordinates, number of sides on a shape, turtle turn angles.

score = 10
lives = 3
Common Mistake
score = "10"    # this is a STRING, not an integer!

The quotation marks make it text. Python won't let you do math with it until you convert it with int() (p22).

Can You Predict This?
lives = 3
lives = lives - 1
print(lives)

Output:

PAGE 19Data & Variables

Float - Decimal Numbers

Definition

A float (float, short for "floating-point number") is any number with a decimal point.

Think Of It Like...

If an integer is a counting number (how many whole cookies), a float is a measuring cup - it captures the part in between whole numbers.

FloatsNot floats
3.14, 0.5, -2.0, 100.03 (no decimal - that's an int)  -  "3.14" (text)
Where You'd Use This

Games: health percentages, speed, gravity, timers counting down in seconds. Visual coding: smooth turtle movement speeds, precise angles, fading colors.

health = 87.5
turtle_speed = 1.5
Common Mistake
price = 10
print(price / 3)     # 3.3333333333333335

Dividing two integers with / in Python still gives you a float back - division almost never stays a clean whole number.

Can You Predict This?
x = 5
y = 2.0
print(x + y)

Output:   (mixing int + float always produces a float)

PAGE 20Data & Variables

Arithmetic Operators Chart

SymbolNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division (always gives a float)5 / 22.5
//Floor division (rounds down, drops remainder)5 // 22
%Modulo (the leftover remainder)5 % 21
**Exponent (power)5 ** 225
Game Examples
score = score + 10        # add points
lives = lives - 1         # lose a life
is_even_turn = turn % 2   # 0 if even, 1 if odd
Think Of It Like...

% (modulo) is what's left over after you divide as evenly as you can - like dealing 13 cards to 4 players: everyone gets 3, and 13 % 4 = 1 card is left over.

Can You Predict This?
print(10 // 3)
print(10 % 3)

Output: and

PAGE 21Data & Variables

Compound Assignment Operators

A shortcut for "take a variable, change it, and store it back in itself."

ShortcutMeans the same as
score += 10score = score + 10
lives -= 1lives = lives - 1
size *= 2size = size * 2
health /= 2health = health / 2
score = 0
score += 10
score += 10
print(score)     # 20
Remember

Read += as "plus-equals." It always means: do the math, then save the result back into the same box.

Where You'd Use This

Nearly every game uses these constantly: adding points on a hit, subtracting a life on damage, doubling a power-up's strength.

Try It

Rewrite lives = lives - 1 using a compound operator:

PAGE 22Data & Variables

Type Conversion - Full Reference

Definition

Type conversion means changing a value from one data type to another using int(), float(), or str().

"25"  --int()-->   25          text -> whole number
"3.14"--float()>  3.14         text -> decimal number
 25  --str()--->  "25"         number -> text
FunctionConverts toFails if...
int(x)integerx isn't a whole number, e.g. int("hi")
float(x)floatx isn't a valid number at all
str(x)stringalmost never fails - everything can become text
Why This Matters In Games

Every value typed by a player arrives as a string. Want to compare a guess to a random number? Convert first. Want to show a number inside a sentence with + instead of an f-string? Convert the number to a string first.

guess = int(input("Guess the number: "))
score = 10
message = "Score: " + str(score)   # must convert to join with +
Common Mistake
print("Score: " + 10)   # ERROR - can't + a string and an int

Fix: print("Score: " + str(10)) or just use an f-string (p6).

PAGE 23Data & Variables

Boolean & Comparison Operators

Definition

A Boolean (bool) is a value that is either True or False. Nothing in between.

Think Of It Like...

A Boolean is a light switch - only ON or OFF. There's no dimmer setting.

Comparison operators compare two values and always produce a Boolean.

SymbolMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 3True
>greater than5 > 3True
<less than5 < 3False
>=greater or equal5 >= 5True
<=less or equal5 <= 3False
   5 > 3          5 == 3
     v               v
   True            False
Common Mistake

Using = (assignment) when you mean == (comparison). if score = 10: is a syntax error - use if score == 10:.

Can You Predict This?
lives = 0
print(lives == 0)
print(lives > 0)

Output: and

PAGE 24Data & Variables

and / or / not

These combine multiple Boolean values into one Boolean answer.

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse
and -> both must be true or -> at least one must be true not -> flips it (True <-> False)
has_key = True
door_unlocked = False
print(has_key and door_unlocked)   # False - needs BOTH
print(has_key or door_unlocked)    # True - needs just ONE
print(not has_key)                 # False - flipped
Where You'd Use This

if lives > 0 and time_left > 0: - game only continues if both are true. if answer == "y" or answer == "yes": - accept either spelling.

Try It

print(not False) ->

PAGE 25Data & Variables

None - The Empty Value

Definition

None is a special value meaning "nothing, on purpose." Its type is NoneType. It is not 0, not an empty string, not False - it's the absence of a value entirely.

Think Of It Like...

An empty inventory slot isn't "zero items sitting there" - it's a slot with nothing assigned to it yet. That's None.

winner = None       # no winner yet
selected_item = None

if winner is None:
    print("Game still going")
Remember

Compare to None using is None, not == None. Not required to know why yet - just the habit to build now.

Where You'd Use This

A "current target" variable before the player selects an enemy. A "high score" before any score has been recorded. A function that hasn't returned anything yet.

Common Mistake

Confusing None with 0 or "". All three are "falsy," but they mean different things - 0 is a real number, None is the absence of one.

PAGE 26Data & Variables

Data Types Review Roundup

1 - Name the type
"7"
7
7.0
True
None
2 - Predict the output
a = 4
b = "4"
print(a == b)

Output: (different types are never equal, even if they look alike)

3 - Fix the bug
age = input("Age: ")
next_year = age + 1
print(next_year)

What's wrong, and how would you fix line 2?

sketch: draw your own data type map from memory
PAGE 27Control Flow

if Statements - Making Decisions

Definition

A condition is a statement that's either True or False. An if statement runs a block of code only if its condition is True.

Definition

Indentation (the spaces at the start of a line) is how Python knows which lines belong inside the if statement. Python uses indentation instead of curly braces - it's not optional, it's syntax.

if lives > 0:
    print("Keep playing!")
if lives > 0 :
 |    |    |  |
 |    |    |  +-- colon - always ends the if line
 |    |    +----- condition being checked
 |    +---------- the variable
 +--------------- keyword that starts the decision
Common Mistake
if lives > 0
    print("Keep playing!")   # missing colon after condition
Common Mistake
if lives > 0:
print("Keep playing!")   # not indented - Python doesn't know it's inside the if
Try It

Write an if statement that prints "Level up!" when score >= 100:

PAGE 28Control Flow

if / elif / else

KeywordMeans
ifCheck this condition first.
elif"Else if" - if the first one was False, check this one instead.
elseIf none of the above were True, do this. No condition needed.
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Keep practicing")
Flowchart
          PLAYER HAS KEY?
                 |
          +------+------+
         YES            NO
          |              |
      OPEN DOOR      "LOCKED"
          |              |
        (done)         (done)
if has_key:
    print("The door opens.")
else:
    print("Locked. Find a key.")
Remember

Python checks conditions top to bottom and stops at the first True one. Once one branch runs, the rest are skipped - even if they'd also be True.

Can You Predict This?
score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 80:
    print("also B?")

Output:

PAGE 29Control Flow

Nested Conditions & Game Examples

Definition

Nesting means putting one if statement inside another. The inner condition is only even checked if the outer one was True.

if has_key:
    if enemies_defeated:
        print("The treasure room opens!")
    else:
        print("Door is jammed by enemies.")
else:
    print("You need a key first.")
       HAS KEY?
      +---+---+
     YES      NO -> "need a key"
      |
  ENEMIES DEFEATED?
   +---+---+
  YES      NO -> "jammed"
   |
"treasure room opens!"
Remember

Each level of nesting = one more level of indentation. If your indentation gets messy, your logic usually is too - that's a sign to simplify.

Where You'd Use This

Checking win conditions (if lives > 0 and flag_captured:), checking multiple requirements to unlock a level, checking difficulty tiers.

Try It

Rewrite the nested example above using and instead of nesting, for the "treasure room" case only:

PAGE 30Control Flow

Control Flow Practice

1 - Predict
health = 0
if health > 0:
    print("Alive")
else:
    print("Game Over")

Output:

2 - Find the bug
if score > 10
    print("You win!")

What's wrong?

3 - Write it

Write code: if coins >= 5, print "Buy a power-up!", otherwise print "Keep collecting."

Vocabulary Check

Fill in: a statement that is either True or False is called a ______. Code that only runs when a condition is True lives inside an ______ statement.

PAGE 31Loops

What Is a Loop?

Definition

A loop repeats a block of code multiple times, so you don't have to write it over and over by hand. Each repetition is called an iteration.

Think Of It Like...

A loop is a conveyor belt. The same action happens to every item that comes down the belt, one at a time, until the belt stops.

       START
         |
   REPEAT 4 TIMES <----+
         |             |
    DRAW SIDE          |
         |             |
       TURN             |
         |             |
    done yet? --NO------+
         |
        YES
         |
        DONE
Where You'd Use This

Drawing all 4 sides of a square. Checking every enemy on screen. Running the whole game over and over until the player quits. Counting down a timer.

Remember

Python has two kinds of loops: for (repeat a set number of times, or once per item) and while (repeat as long as a condition stays True). Both coming up next.

PAGE 32Loops

for Loops - Every Piece Explained

for i in range(4):
    print("side drawn")
for   i   in   range(4)  :
 |    |    |       |      |
 |    |    |       |      +-- colon, same rule as if statements
 |    |    |       +--------- how many times / what to repeat over
 |    |    +----------------- keyword meaning "go through each one"
 |    +---------------------- loop variable - holds the current count
 +--------------------------- keyword that starts a for loop
PieceWhat it means
for"Repeat the following, once per item."
iA brand-new variable that changes each time through the loop. Could be named anything, but i is the common convention.
inConnects the loop variable to what it's looping over.
range(4)Produces the sequence 0, 1, 2, 3 - four numbers, so the loop runs 4 times.
Can You Predict This?
for i in range(3):
    print(i)

Output (3 lines):

Common Mistake

Assuming range(4) counts 1,2,3,4. It actually counts 0,1,2,3 - four numbers starting at zero.

PAGE 33Loops

range() - The Full Reference

CallProduces
range(5)0, 1, 2, 3, 4  (stops before 5)
range(2, 6)2, 3, 4, 5  (start, stop before)
range(0, 10, 2)0, 2, 4, 6, 8  (start, stop, step)
range(5)
0----1----2----3----4----(5 - never reached)

range(2, 6)
     2----3----4----5----(6 - never reached)

range(0, 10, 2)
0---------2---------4---------6---------8----(10 - never reached)
Remember

range() always stops before its final number, never on it. This is the same rule as string indexing being 0-based - Python counts up to, but not including, the end.

Where You'd Use This

range(4) for drawing a 4-sided shape. range(0, 360, 36) for a turtle that spins in 10 evenly-spaced steps around a circle.

Try It

What does range(1, 5) produce?

PAGE 34Loops

while Loops

Definition

A while loop repeats as long as its condition stays True. Unlike for, it doesn't know in advance how many times it'll run.

lives = 3
while lives > 0:
    print("Still playing")
    lives -= 1
print("Game Over")
   lives > 0 ?
   +---+---+
  YES      NO -> "Game Over"
   |
"Still playing"
   |
lives -= 1
   |
   +---- back to the check
Common Mistake - Infinite Loop
lives = 3
while lives > 0:
    print("Still playing")   # lives never changes!

If nothing inside the loop ever makes the condition False, it runs forever. Every while loop needs something that eventually flips its condition.

Where You'd Use This

while is perfect for "keep playing until the player loses" or "keep asking until they type a valid answer" - situations where you don't know the exact number of repeats ahead of time.

Can You Predict This?
n = 3
while n > 0:
    print(n)
    n -= 1

Output (3 lines, in order):

PAGE 35Loops

Loop Mistakes & Practice

Common Mistake

Off-by-one: using range(5) when you actually wanted 5 to be included (it isn't - use range(1,6) instead).

Common Mistake

Forgetting to update the loop variable in a while loop -> infinite loop.

Common Mistake

Indenting code outside the loop by accident, so it runs every iteration instead of once at the end.


1

How many times does this loop run? for i in range(5): print("Hi")  

2

Fix this infinite loop:

count = 0
while count < 5:
    print(count)

My fix:

3

Write a for loop that prints "Enemy spawned" 3 times:

PAGE 36Functions

What Is a Function?

Definition

A function is a named, reusable chunk of code that performs a task. You write it once, then call it (use it) as many times as you want.

Think Of It Like...

A function is a machine: you feed something in, the machine does its work out of sight, and something comes out the other end.

   INPUT
     |
     v
+---------------+
|    FUNCTION    |
|   does work    |
+---------------+
     |
     v
   OUTPUT
Definition

You've already used functions! print(), input(), len(), range(), int() are all built-in functions. Now you'll learn to write your own.

Why Functions Exist

Without them, "check if the player collided with an enemy" would need to be retyped everywhere it's checked. With a function, you write check_collision() once and call it from anywhere.

PAGE 37Functions

Defining and Calling Functions

Defining - writing the machine (does not run it yet!)

def greet_player():
    print("Welcome to the game!")
def   greet_player  ( )  :
 |         |         |   |
 |         |         |   +-- colon - same rule, every time
 |         |         +------ empty parentheses = takes no info in
 |         +---------------- the function's name - you choose it
 +-------------------------- keyword meaning "define a new function"

Calling - actually running it

greet_player()     # NOW it prints "Welcome to the game!"
Remember

Defining a function with def does not run its code. Python just memorizes the recipe. Nothing happens until you call it by name with parentheses.

Common Mistake
def greet_player():
    print("Welcome!")
# ...forgot to actually call greet_player() anywhere

Result: the program runs with no output. The function was defined but never used.

PAGE 38Functions

Parameters vs. Arguments

Definition

A parameter is a placeholder name listed in the function's definition. An argument is the actual value you hand it when you call it.

def greet(name):        <- "name" is the PARAMETER (a placeholder)
    print(f"Hi, {name}!")

greet("Ava")             <- "Ava" is the ARGUMENT (the real value)
Think Of It Like...

Parameter = the blank slot on a form ("Name: ______"). Argument = what you actually write in that blank.

def take_damage(amount):
    print(f"Player takes {amount} damage!")

take_damage(10)
take_damage(25)

Multiple parameters

def move_player(x, y):
    print(f"Moving to ({x}, {y})")

move_player(100, 50)
Common Mistake
def take_damage(amount):
    print(f"Player takes {amount} damage!")

take_damage()   # ERROR - missing required argument
Try It

In def spawn_enemy(x, y):, name the two parameters: and

PAGE 39Functions

Return Values

Definition

return sends a value back out of a function so you can store it or use it elsewhere. Not every function needs one - but a function without return hands back None.

def add_points(score, points):
    return score + points

new_score = add_points(10, 5)
print(new_score)     # 15
   score=10, points=5
          |
          v
   +---------------+
   |  add_points()  |
   | score + points |
   +---------------+
          |
          v
      returns 15
          |
          v
   new_score = 15
Remember

print() only displays a value - it doesn't hand it back to your code. return actually gives the value back so you can use it in more math or store it in a variable.

Common Mistake
def add_points(score, points):
    print(score + points)   # prints it, but doesn't return it

new_score = add_points(10, 5)
print(new_score)             # None!
Can You Predict This?
def double(n):
    return n * 2

result = double(4)
print(result)

Output:

PAGE 40Functions

Functions Practice

1 - Write it

Write a function called square that takes a number n and returns n * n.

2 - Predict
def is_alive(lives):
    return lives > 0

print(is_alive(0))
print(is_alive(3))

Output: and

3 - Vocabulary Check

Match the word to its meaning: def, parameter, argument, return, call.

  • - actually running the function
  • - the placeholder name in the definition
  • - the real value passed in
  • - sends a value back out
  • - keyword that defines a function
PAGE 41Turtle & Visual Art

Meet Turtle

Turtle is a drawing library built into Python. Picture a little turtle holding a pen, standing on a blank canvas - you tell it where to move, and it draws a trail behind it.

Turtle is a drawing library built into Python. Picture a little turtle holding a pen, standing on a blank canvas - you tell it where to move, and it draws a trail behind it.

Code Turtle Online →
Definition

A library (or module) is a collection of pre-written code someone else built that you can use in your own programs. import is how you bring one in.

import turtle

t = turtle.Turtle()   # create a turtle object named t
t.forward(100)
turtle.done()          # keeps the drawing window open
import turtle : bring in the drawing toolbox
turtle.Turtle(): create ONE turtle - a real "object" you control
t.forward(100) : t is your turtle's name - commands go t.command()
Definition

An object is a thing your code creates and controls that has its own properties (position, color, speed) and its own actions (move, turn, draw). Your turtle t is an object.

Remember

You can name your turtle anything: t, artist, bob. Whatever you name it, every command afterward starts with that name and a dot.

PAGE 42Turtle & Visual Art

Turtle Command Reference

CommandWhat it does
t.forward(100)Move forward 100 pixels, drawing a line.
t.backward(100)Move backward 100 pixels.
t.left(90)Turn left 90 degrees, in place.
t.right(90)Turn right 90 degrees, in place.
t.penup()Lift the pen - move without drawing.
t.pendown()Lower the pen - start drawing again.
t.goto(x, y)Jump straight to a coordinate (see p43).
t.circle(50)Draw a circle with radius 50.
t.speed(1-10)How fast the turtle animates (10 = fast, 0 = instant).
t.color("blue")Set the pen (and fill) color.
t.width(3)Set the pen's line thickness.
t.begin_fill()Start remembering the shape to fill in.
t.end_fill()Fill the shape traced since begin_fill().
Common Mistake

Forgetting t.penup() before repositioning - you'll draw an unwanted line all the way to your new spot.

Try It

Write the two lines that move the turtle to a new spot without drawing a line, then start drawing again:

PAGE 43Turtle & Visual Art

The Turtle Coordinate System

Definition

The turtle canvas is a grid with (0, 0) at the exact center - not the top-left corner like some other tools. x is left/right, y is up/down.

                +Y
                 ^
                 |
       (-100,50) |   (100,50)
                 |
     -X ---------0-----------> +X
                 |        (0,0) is the CENTER
      (-100,-50) |   (100,-50)
                 |
                v
                -Y
t.goto(0, 0)        # dead center
t.goto(100, 0)      # 100 pixels right
t.goto(0, -100)     # 100 pixels down
t.goto(-50, 50)     # up and to the left
Remember

Positive y goes up in turtle world - the opposite of screen pixels in most other programs, where y often increases downward. This is the #1 thing that trips people up moving between tools.

Where You'd Use This

Placing shapes at exact spots, scattering random "stars" across the screen (paired with p49's random), building a simple grid-based game board.

Try It

What coordinate is directly below center by 75 pixels?

PAGE 44Turtle & Visual Art

Color, Fill & Style

t.color("red")            # pen (and fill) color
t.width(4)                 # thicker line
t.speed(6)                 # 1 (slow) to 10 (fast), 0 = instant

Filling in a shape

t.color("gold")
t.begin_fill()
for i in range(4):
    t.forward(80)
    t.right(90)
t.end_fill()
begin_fill()  -->  draw the outline  -->  end_fill()
    "start                                  "now paint
   remembering                               everything
   this shape"                              I traced"
Common Mistake

Calling end_fill() without a matching begin_fill() - nothing gets filled because Python never started tracking the shape.

Common Mistake

Not closing the shape (the turtle needs to return to roughly where it started) - the fill can look strange if the outline doesn't connect back up.

Color Name Ideas
"red""blue""green""purple""gold""cyan""magenta""black"
PAGE 45Turtle & Visual Art

Turtle Art - Square & Triangle

SketchPlanCodeResult
4 equal sides, 90deg cornersrepeat 4x: forward, turn 90degsee belowa square
for i in range(4):
    t.forward(100)
    t.right(90)
The Programming Idea

Any closed shape made of straight, equal sides is: walk forward, turn by the same angle, repeat - until you've turned all the way around (360deg). A square turns 90deg four times because 4 x 90 = 360.

Triangle - same idea, different angle

A triangle has 3 sides, so it needs to turn 360 / 3 = 120 degrees each time.

for i in range(3):
    t.forward(100)
    t.right(120)
Remember - The Shape Formula

For any regular shape with n sides: turn angle = 360 / n. This one formula unlocks every shape on the next page.

Try It

What turn angle would draw a 6-sided shape (hexagon)?

PAGE 46Turtle & Visual Art

Turtle Art - Polygons & Stars

Any polygon, using the 360/n formula

sides = 8
angle = 360 / sides

for i in range(sides):
    t.forward(60)
    t.right(angle)
Where the idea came from

This is p45's formula turned into variables instead of hard-coded numbers - change sides to 3, 5, 8, or 20 and the exact same loop draws a completely different shape.

Stars - turn by more than the polygon angle

A star is a polygon where the turtle turns further than needed to close the shape normally, so the lines cross over themselves.

for i in range(5):
    t.forward(100)
    t.right(144)    # a 5-point star
SKETCH        PLAN                 CODE               RESULT
  *     ->   5 points, turn    ->   for i in range(5): ->  a star
             sharply each          t.forward(100)         traced
             step (144deg)           t.right(144)          on screen
Try It

Change sides = 8 to sides = 3 in the polygon code above. What shape draws now?

PAGE 47Turtle & Visual Art

Turtle Art - Spirals & Flowers

Spiral - grow the side length every step

The programming idea: instead of a fixed forward() distance, let the distance increase a little each time through the loop.

length = 5
for i in range(100):
    t.forward(length)
    t.right(20)
    length += 2     # each step gets a little longer
Think Of It Like...

Same square-drawing loop as before, except the "side length" variable is no longer sitting still - it grows every lap.

Flower - repeat a whole shape, rotating each time

The idea: draw one circle (a petal), turn slightly, draw another, turn again - until you've gone all the way around.

for i in range(10):
    t.circle(50)
    t.left(36)     # 360 / 10 petals = 36deg
SKETCH -> PLAN -> CODE -> RESULT
 @      loop 10 times:   for i in range(10):   a flower ring
  spiral   draw a petal,    t.circle(50)         made of 10
  of        rotate a bit    t.left(36)           overlapping
  petals                                          circles
Try It

How would you change the flower code to draw 6 petals instead of 10? (Hint: two numbers need to change together.)

PAGE 48Turtle & Visual Art

Patterns, Loops of Loops & What's Next

Definition

A nested loop is a loop inside another loop - just like a nested if. The inner loop finishes completely before the outer loop moves to its next step.

for shape in range(6):          # draw 6 squares...
    for side in range(4):        # ...each made of 4 sides
        t.forward(50)
        t.right(90)
    t.right(60)                  # then rotate before the next square
OUTER LOOP (6 times)
   |
   +-- INNER LOOP (4 times) -> draws one square
   |
   +-- turn 60deg -> back to top of outer loop
Where You'd Use This

Any repeated pattern - a ring of shapes, a grid of shapes, snowflakes, mandalas. Once you can nest loops, "draw one thing" and "draw a pattern of that thing" become the same skill.

Coming Up Next

Right now every shape looks identical and predictable. In the next section (Randomness, p49) you'll learn random.randint() and random.choice() - so you can make each petal a different color, or scatter shapes randomly across the screen. That's called procedural art: art generated by rules plus a bit of chance.

sketch your own pattern idea here before you code it
PAGE 49Randomness

The random Module

import random
FunctionWhat it doesExample
random.randint(a, b)Random whole number, including both a and brandom.randint(1, 6) -> dice roll
random.choice(list)Picks one random item from a listrandom.choice(["red","blue"])
Remember

randint(1, 6) can actually land on 6 - both endpoints are included. This is different from range(), which stops before its last number (p33). Easy to mix up.

random.randint(1, 6)

  1    2    3    4    5    6
  +----+----+----+----+----+
        any one, equally likely
roll = random.randint(1, 6)
print(f"You rolled a {roll}")

color = random.choice(["red", "blue", "green"])
t.color(color)
Where You'd Use This

Dice and card games, enemy spawn positions, random colors or shapes in art, "critical hit" chance, shuffling which question comes next.

Can You Predict This?

random.randint(1, 3) - list every possible result:

PAGE 50Randomness

Randomness in Games & Art

A guessing game, using random

import random
secret = random.randint(1, 20)
guess = int(input("Guess 1-20: "))

if guess == secret:
    print("You got it!")
else:
    print(f"Nope, it was {secret}")

Random positions for turtle art

import random, turtle
t = turtle.Turtle()
t.penup()

for i in range(20):
    x = random.randint(-200, 200)
    y = random.randint(-200, 200)
    t.goto(x, y)
    t.dot(10, random.choice(["red","blue","gold"]))
Connects To
enemy spawn locationsdicerandom colorsrandom shapesprocedural artshuffled questions
Try It

Write one line that picks a random number of sides between 3 and 10, for a random polygon:

Common Mistake

Forgetting import random at the top - every use of random.anything() needs it, just once, at the start of the file.

PAGE 51Lists

What Is a List?

Definition

A list stores multiple values together, in order, inside square brackets [ ], separated by commas.

Think Of It Like...

A list is a row of numbered lockers. Each locker holds one item, and every locker has a number (its index) so you can find it again.

colors = ["red", "blue", "green"]
inventory = ["sword", "shield", "potion"]
scores = [88, 92, 75]
colors = ["red", "blue", "green"]

INDEX        VALUE
  0          "red"
  1          "blue"
  2          "green"
Remember

Lists use the exact same index rules as strings (p14): counting starts at 0, and list[-1] is the last item.

Where You'd Use This

Games: inventory, enemies on screen, level names, high scores. Visual coding: a palette of colors to pick from, a set of shapes to cycle through.

Try It

Make a list called weapons with 3 weapon names of your choice:

PAGE 52Lists

List Indexing & Changing Items

colors = ["red", "blue", "green"]
print(colors[0])      # red
print(colors[-1])     # green (last item)

Changing an item in place

colors[1] = "purple"
print(colors)     # ['red', 'purple', 'green']
BEFORE                          AFTER  colors[1] = "purple"
0: red                          0: red
1: blue    ---- overwritten --> 1: purple
2: green                        2: green
Remember

Unlike strings, lists are changeable (mutable) - you can overwrite one item without rebuilding the whole list.

Common Mistake
colors = ["red", "blue", "green"]
print(colors[3])     # ERROR - no index 3, only 0,1,2 exist
Can You Predict This?
items = ["sword", "shield"]
items[0] = "axe"
print(items)

Output:

PAGE 53Lists

List Methods - append, remove, len

MethodWhat it doesExample
.append(x)Adds x to the endinventory.append("key")
.remove(x)Removes the first x it findsinventory.remove("key")
len(list)How many items are in itlen(inventory)
inventory = ["sword", "shield"]
inventory.append("potion")
print(inventory)     # ['sword', 'shield', 'potion']

inventory.remove("shield")
print(inventory)     # ['sword', 'potion']

print(len(inventory))     # 2
["sword","shield"] --append("potion")--> ["sword","shield","potion"]
["sword","shield","potion"] --remove("shield")--> ["sword","potion"]
Common Mistake
inventory.remove("bow")   # ERROR if "bow" isn't in the list

.remove() needs an exact match that actually exists in the list.

Try It

Starting from enemies = ["goblin", "orc"], write the line to add "dragon":

PAGE 54Lists

Lists in Games

Common Uses
inventoryenemies on screenlevel nameshigh scoresweapon optionsdialogue lines

Looping over a list - combine with p32!

enemies = ["goblin", "orc", "dragon"]
for enemy in enemies:
    print(f"A wild {enemy} appears!")
Remember

for item in list: gives you each value directly, one at a time - no index math needed. This is the most common way lists and loops team up.

Can You Predict This?
scores = [70, 85, 90]
total = 0
for s in scores:
    total += s
print(total)

Output:

Try It

Write a loop that prints every item in high_scores = [120, 98, 150] on its own line:

PAGE 55Game Logic

Game State - The Scoreboard Idea

Definition

State is a snapshot of every important value in your game right now - score, lives, position, level. Nearly all game code exists to read or change the state.

Think Of It Like...

Game state is a scoreboard at a sports game. At any moment, you can glance at it and know exactly what's going on - you don't need to remember the whole match.

+----------------------+
|   GAME STATE          |
+----------------------+
|  SCORE     = 100      |
|  LIVES     = 3        |
|  LEVEL     = 2        |
|  PLAYER_X  = 50       |
|  PLAYER_Y  = 100      |
+----------------------+
score = 0
lives = 3
level = 1
player_x = 0
player_y = 0
Remember

Every one of these is just a plain variable you already know how to use. "Game state" isn't a new Python feature - it's a name for the group of variables that describe your game.

Where You'd Use This

Deciding whether the game is over (lives <= 0), deciding what to draw (player_x, player_y), deciding difficulty (level).

PAGE 56Game Logic

The Game Loop

Definition

The game loop is a while loop that runs over and over, many times a second, checking input and redrawing the screen - it's why a game feels alive instead of like a single line of output.

          +---------------------+
          |                     |
          v                     |
        INPUT                   |
          |                     |
          v                     |
        UPDATE                  |
          |                     |
          v                     |
     CHECK RULES                |
          |                     |
          v                     |
        OUTPUT                  |
          |                     |
          +---- REPEAT ---------+
StepMeans
InputRead what the player did (key press, typed guess).
UpdateChange the state based on that input (move player, subtract a life).
Check RulesHas anyone won or lost? Did something collide?
OutputShow the result - print text, redraw the screen.
RepeatGo back to Input, unless the game has ended.
lives = 3
while lives > 0:
    guess = input("Guess a number 1-10: ")   # INPUT
    guess = int(guess)
    if guess != 7:                            # CHECK RULES
        lives -= 1                              # UPDATE
        print(f"Wrong! Lives left: {lives}")   # OUTPUT
    else:
        print("You win!")
        break
Remember

break immediately exits the loop - useful for ending a game loop the instant someone wins, without waiting for the condition to naturally go False.

PAGE 57Game Logic

Game Vocabulary I

Definition

Player - the character or object the person using the game directly controls.

Definition

Enemy - a character controlled by the game (not the player) that opposes the player.

Definition

Obstacle - something in the environment that blocks or challenges the player, but doesn't act on its own like an enemy does.

Definition

Score - a number tracking how well the player is doing, usually meant to go up.

Definition

Lives - how many times the player can fail before the game ends.

Definition

Level - a distinct stage or section of the game, usually increasing in difficulty.

In Code
player_x, player_y = 0, 0
enemy_x, enemy_y = 100, 100
score = 0
lives = 3
level = 1
Try It

Name one obstacle and one enemy idea for a game you'd want to build: /

PAGE 58Game Logic

Game Vocabulary II

Definition

Win condition - the exact rule that ends the game in the player's favor. Example: score >= 100.

Definition

Lose condition - the exact rule that ends the game against the player. Example: lives <= 0.

Definition

Collision - when two objects occupy the same space, usually triggering an effect (damage, pickup, bounce).

Definition

Timer - a value that counts down (or up) over time, often ending the game or an event when it hits zero.

Definition

Power-up - a temporary or permanent boost the player can collect (extra life, speed boost).

Definition

Inventory - a list of items the player is currently holding (see p51's lists!).

Definition

Random event - something that happens with an element of chance rather than a guaranteed rule (p49's random).

if score >= 100:
    print("You win!")
elif lives <= 0:
    print("Game Over")
Remember

A collision, in beginner Python games, is usually just an if statement comparing positions - e.g. if player_x == enemy_x and player_y == enemy_y:.

PAGE 59Game Logic

Tracing a Mini Game

Walk through this dice game line by line, tracking every variable as it changes - a skill you'll use constantly (see p64).

import random

target = random.randint(1, 6)
attempts = 0
won = False

while attempts < 3 and not won:
    guess = int(input("Guess 1-6: "))
    attempts += 1
    if guess == target:
        won = True
        print("You won in", attempts, "tries!")
    else:
        print("Try again.")

if not won:
    print(f"Out of tries. It was {target}.")
LineWhat it does
target = random.randint(1,6)Pick the secret number once, before the loop.
while attempts < 3 and not won:Keep looping until either 3 tries are used or they've won.
attempts += 1Count this guess, every time through the loop.
won = TrueFlip the flag so the while condition goes False next check.
Try It

If target = 4 and the player guesses 2, then 4 - trace it: what prints, and after how many attempts?

PAGE 60Debugging

Types of Bugs

Definition

A bug is anything wrong with your code - it doesn't run, or it runs but does the wrong thing. Debugging is the process of finding and fixing bugs.

TypeMeaningExample
Syntax ErrorBroken grammar - Python can't even start running it.Missing colon, mismatched quotes.
Runtime ErrorThe code runs, then crashes partway through.Dividing by zero, index out of range.
Logic ErrorThe code runs fine with no crash, but gives the wrong answer.Using + when you meant -.
Think Of It Like...

Syntax error = a sentence with no verb - grammatically broken. Runtime error = a car that starts, then stalls on the highway. Logic error = a car that runs perfectly... straight into the wrong city.

Remember

Logic errors are the hardest to catch, because Python never complains - the program looks like it's working. This is exactly why "Can You Predict This?" practice matters.

PAGE 61Debugging

The Bug Detective Method

              BUG
               |
               v
         READ THE ERROR
               |
               v
          FIND THE LINE
               |
               v
   WHAT DID I EXPECT TO HAPPEN?
               |
               v
    WHAT ACTUALLY HAPPENED?
               |
               v
       MAKE A HYPOTHESIS
               |
               v
       CHANGE ONE THING
               |
               v
             TEST
               |
        +------+------+
      FIXED         STILL BROKEN
        |                |
      DONE      back to "make a hypothesis"
Remember

Change one thing at a time. If you change five things and it works, you'll never know which change actually fixed it - and you might have added a new bug.

Reading a Python error

Python errors usually tell you the exact line number and a short description at the bottom. Always read the last line of the error first - that's the actual problem.

Try It

Next time you hit a real error, write the line number and error message here, then work through the steps above:

PAGE 62Debugging

The Error Museum

Every beginner walks past these exhibits. Recognize the shape of the mistake, not just the exact code.

ExhibitBrokenFixed
Missing colonif score > 10if score > 10:
Missing parenthesisprint("hi"print("hi")
Bad indentationif x:
print(x)
if x:
    print(x)
Misspelled variableprint(scroe)print(score)
Wrong data type"5" + 5int("5") + 5
Forgetting quotesprint(hello)print("hello")
Infinite loopwhile True:
    print("hi")
add something that eventually breaks the loop
Wrong conditionif lives = 0:if lives == 0:
The single most common one

NameError: name 'scroe' is not defined - 90% of the time, this means a typo in a variable name. Check spelling and capitalization first.

Try It

Add one bug you personally made this week to this museum, and its fix:

PAGE 63Debugging

Debugging Checklist

Work through these, in order, before asking for help.

Checklist
  • [ ] Did I read the last line of the error message?
  • [ ] Did I find the exact line number it points to?
  • [ ] Are all my colons, quotes, and parentheses matched up?
  • [ ] Is my indentation consistent (same number of spaces)?
  • [ ] Did I spell every variable name exactly the same everywhere?
  • [ ] Am I mixing up = and ==?
  • [ ] Is a string sneaking in where I need a number (or vice versa)?
  • [ ] If it's a loop - does something inside it actually change the condition?
  • [ ] Did I add a print() statement to check a variable's value mid-program?
Remember

Sprinkling print(variable_name) throughout your code to see what's actually stored is not "cheating" - it's one of the most-used real debugging techniques there is.

space for your own recurring mistakes - build your personal list here over the next 5 weeks
PAGE 64Code Reading

How To Read Code - Tracing Variables

Definition

Tracing means running code in your head (or on paper), line by line, writing down what every variable equals after each line. It's the single best skill for both debugging and predicting output.

Trace this by hand - fill in the table as you go:

x = 5
y = 2
x = x + y
y = x - y
print(x, y)
Linexy
x = 55 -
y = 252
x = x + y2
y = x - y
Remember

Read the right side of an = first - Python always fully calculates it before storing anything.

When To Trace

Whenever output doesn't match what you expected. Draw a mini table like the one above, one column per variable, one row per line - the wrong value usually reveals itself immediately.

PAGE 65Code Reading

What Does This Code Do?

1
total = 0
for i in range(1, 6):
    total += i
print(total)

Identify: the loop, the condition (if any), the final value of total.

2
def mystery(n):
    if n % 2 == 0:
        return "even"
    else:
        return "odd"

print(mystery(7))

Identify: the function name, its parameter, what it returns for 7.

3
items = ["a", "b", "c"]
for i in range(len(items)):
    print(i, items[i])

Identify: how many times it loops, and what prints on the first line.

Remember

Before predicting output, first identify the shape of the code: is there a loop? A condition? A function? Naming the parts out loud makes tracing the values much easier.

PAGE 66Project Design

The Game Design Blueprint

Before writing a single line of a new project, fill this page out. It will save you from the "I don't know what to build next" wall.

Game Idea

In one sentence, what is this game?

Game Rules

What can the player do? What isn't allowed?

Controls

What input does the player give? (typed text, key presses)

Win Condition

Lose Condition

PAGE 67Project Design

Project Planning Worksheet

Variables I'll need (game state)
Functions I'll need

List actions that will repeat:

Visuals

Turtle shapes, colors, layout:

Levels

Does difficulty change over time? How?

Sounds (conceptually)

If this had sound, what would play and when?

Testing

What's the very first small piece you'll build and test, before anything else?

Remember

Build the smallest working version first - one shape on screen, one working input - then add features. A game that does one thing is more valuable than five broken half-built ideas.

PAGE 68Toolbox

Python Symbols Cheat Sheet

SymbolNameMeaning
+PlusAddition, or joining strings
-MinusSubtraction
*StarMultiplication, or repeating strings
/SlashDivision (always returns a float)
//Double slashFloor division (rounds down)
%Percent / ModuloRemainder after division
**Double starExponent (power)
=EqualsAssignment - store a value
==Double equalsComparison - are these equal?
!=Not-equalsComparison - are these different?
> <Greater / Less thanComparison
>= <=Greater / Less or equalComparison
+= -= *= /=Compound assignmentUpdate a variable using itself
[ ]Square bracketsIndexing, or defining a list
( )ParenthesesCalling a function, grouping math
:ColonStarts a new indented block (if/for/while/def)
#HashStarts a comment - Python ignores the rest of the line
PAGE 69Toolbox

Python Vocabulary Dictionary - A to L

TermDefinition
AlgorithmA step-by-step set of instructions for solving a problem.
ArgumentThe real value handed to a function when you call it.
AssignmentStoring a value into a variable, using =.
BooleanA True/False value.
BugAnything wrong with your code.
CodeWritten instructions for a computer.
ConditionA statement that evaluates to True or False.
DataInformation a program stores and works with.
Data typeThe category a value belongs to (str, int, float, bool...).
DebuggingFinding and fixing bugs.
EventSomething that happens that a program can react to (a key press, a click).
ExpressionAny bit of code that produces a value, like 5 + 2.
FloatA decimal number.
FunctionA named, reusable block of code.
Game loopThe repeating cycle of input -> update -> check -> output.
IndexThe position number of an item in a string or list, starting at 0.
InputInformation going into a program, often from the user.
IntegerA whole number.
IterationOne single repetition of a loop.
ListAn ordered collection of values in square brackets.
PAGE 70Toolbox

Python Vocabulary Dictionary - M to Z

TermDefinition
MethodAn action attached to a value, called with a dot: value.method().
ModuleA file of pre-written code you can import and use (same idea as a library).
ObjectA thing your code creates that has its own properties and actions.
OperatorA symbol that performs an operation, like + or ==.
OutputInformation a program produces, often shown on screen.
ParameterThe placeholder name in a function's definition.
ProgramA complete set of code that does something useful.
ProgrammingThe act of writing code to build a program.
ReturnSending a value back out of a function.
StateThe current values of all the important variables in a program.
StringText, wrapped in quotation marks.
SyntaxThe exact spelling and grammar rules of a language.
ValueA single piece of data - a number, some text, a Boolean.
VariableA named box that stores a value.
Try It

Pick 3 words above you still find confusing. Flip back to the page that explains each one and re-read it right now:

PAGE 71Toolbox

"When Do I Use This?"

Stuck on what tool to reach for? Start here.

I need to...Reach for...Page
Display somethingprint()p5
Ask the user somethinginput()p7
Store informationa variablep9
Turn typed text into a numberint() / float()p22
Repeat something a set number of timesfor loopp32
Repeat until a condition changeswhile loopp34
Make a decisionif / elif / elsep27
Reuse the same code in many placesa functionp36
Store many values togethera listp51
Generate unpredictabilityrandomp49
Draw something on screenturtlep41
Track score, lives, or positiongame state variablesp55
Something isn't workingthe Bug Detectivep61
PAGE 72Toolbox

Visual Analogies - The Complete Set

ConceptAnalogy
VariableA labeled storage box
FunctionA machine - input goes in, output comes out
LoopA conveyor belt, repeating the same action
if statementA decision gate - one path or the other
ListA row of numbered lockers
StringBeads threaded on a string, each one a character
IntegerA whole-number counter - score, lives
FloatA measuring cup - captures the in-between amounts
BooleanA light switch - only ON or OFF
DebuggingDetective work - evidence, hypothesis, test
Game stateA scoreboard - a snapshot of everything happening now
f-stringA fill-in-the-blank sentence
Remember

When a concept feels abstract, come back to its analogy first. The code will make more sense once the picture in your head is solid.

PAGE 73Toolbox

Capstone Project Checklist

You've made it through the whole guide. Time to build something real and put every page to work.

Before You Start
  • [ ] Filled out the Game Design Blueprint (p66) and Planning Worksheet (p67)
  • [ ] Know your win condition and lose condition, in plain English
  • [ ] Listed the game-state variables you'll need
While Building
  • [ ] Built the smallest working version first, then added features one at a time
  • [ ] Used functions for anything that repeats
  • [ ] Used a loop for the main game loop, and if for the rules
  • [ ] Tested after every small change, not just at the end
When Stuck
  • [ ] Ran the Debugging Checklist (p63)
  • [ ] Traced the variables by hand (p64)
  • [ ] Flipped back to the relevant page instead of guessing
Congratulations! You've finished the workbook!