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 ↗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
This workbook belongs to:
Started on: Class:
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 color | What it means |
|---|---|
| Definition | A term is being explained for the first time. |
| Common Mistake | Something beginners get wrong - including you, and that's fine. |
| Remember | A rule worth memorizing. If you forget everything else, don't forget this. |
| Try It | A 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 This | Connects the concept to a real game or art project. |
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.
Table of Contents
First Steps
- Code, Program & Syntax p4
- print() p5
- print() practice p6
- input() p7
- Converting input p8
Data & Variables
- Variables - the box p9
- Naming rules p10
- The Data Type Map p11
- String basics p12
- Strings: quotes & joining p13
- String indexing p14
- Negative index & len() p15
- String methods p16
- String mistakes+practice p17
- Integer p18
- Float p19
- Arithmetic operators p20
- Compound assignment p21
- Type conversion p22
- Boolean & comparisons p23
- and / or / not p24
- None p25
- Data types review p26
Control Flow
- if statements p27
- if / elif / else p28
- Nested conditions p29
- Control flow practice p30
Loops
- What is a loop? p31
- for loops, piece by piece p32
- range() reference p33
- while loops p34
- Loop mistakes+practice p35
Functions
- What is a function? p36
- Defining & calling p37
- Parameters vs arguments p38
- Return values p39
- Functions practice p40
Turtle & Visual Art
- Meet turtle p41
- Movement commands p42
- Coordinate system p43
- Color & style p44
- Square & triangle p45
- Polygons & stars p46
- Spirals & flowers p47
- Patterns & randomness p48
Randomness
- The random module p49
- Randomness practice p50
Lists
- What is a list? p51
- Indexing & changing p52
- List methods p53
- Lists in games p54
Game Logic
- Game state p55
- The game loop p56
- Game vocabulary I p57
- Game vocabulary II p58
- Tracing a mini game p59
Debugging
- Types of bugs p60
- The Bug Detective p61
- The Error Museum p62
- Debugging checklist p63
Code Reading
- Tracing variables p64
- What does this do? p65
Project Design
- Game Design Blueprint p66
- Planning worksheet p67
Toolbox
- Symbols cheat sheet p68
- Vocabulary A-L p69
- Vocabulary M-Z p70
- "When do I use this?" p71
- Visual analogies p72
- Capstone checklist p73
Code, Program & Syntax
Here's a list of some of the programming terms you'll see throughout this course!
Code - written instructions that tell a computer what to do, written in a language it understands (like Python).
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.
Programming - the act of writing code to build a program. That's what you're learning.
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.
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) ^
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.
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.
print() - Talking to the Screen
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!
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)
Forgetting quotation marks around text:
print(Hello) # ERROR - Python thinks Hello is a variable name
Fix: print("Hello")
Forgetting a closing parenthesis:
print("Hello!"
Python will wait forever for the ) that never comes.
Write a line of code that prints your name:
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!
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.
lives = 3
print(f"Lives left: {lives}")
Output:
Fix this line so it actually prints the value of score instead of the word "score":
score = 5
print("score")
My fix:
input() - Listening to the User
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)
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)
age = input("How old are you? ")
print(age + 1) # ERROR - can't add a number to a string
See p8 for the fix.
Asking a player's name before a game starts, asking for a guess in a guessing game, asking "play again? (y/n)".
Write a line that asks the user "What's your favorite color?" and stores it in a variable called color:
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
age = input("Age? ")
print(age + 1)
# ERROR: can only
# concatenate str
# (not "int") to str
age = int(input("Age? "))
print(age + 1)
# works! prints
# age + 1
The three converters you'll use most
| Function | Turns text into... | Example |
|---|---|---|
int() | a whole number | int("7") -> 7 |
float() | a decimal number | float("3.5") -> 3.5 |
str() | text (goes the other way) | str(7) -> "7" |
You can convert while asking, in one line: int(input("...")). Read it inside-out: get input -> then convert it.
Variables - The Labeled Box
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.
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 +-------------+ +-------------+
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).
score = 5 score = score + 1 print(score)
Output: (hint: Python reads the right side first, then stores the result)
Variable Naming Rules
| Rule | Example |
|---|---|
| Can use letters, numbers, underscores | player_1 |
| Can't start with a number | 1player (invalid) |
| No spaces - use underscores instead | high_score not high score |
| Case-sensitive | Score and score are different variables |
| Can't use Python's reserved words | for, if, print (invalid) |
Good names vs. bad names
livesplayer_scoreenemy_xis_game_over
x(what is x?)thing2datal(looks like the number 1)
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.
Circle the valid variable names: 2lives player_name high-score isAlive for
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)
| Type | Python name | Example | Ask yourself |
|---|---|---|---|
| String | str | "Ava" | Is it in quotes? |
| Integer | int | 7 | Whole number, no decimal? |
| Float | float | 7.0 | Has a decimal point? |
| Boolean | bool | True | Is it a yes/no answer? |
| List | list | [1,2,3] | In square brackets? |
| None | NoneType | None | Is it "nothing on purpose"? |
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.
Find out any value's type by wrapping it in type():
print(type(5)) # <class 'int'> print(type("5")) # <class 'str'>
String - What Is Text Data?
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.
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"
Games: player names, messages ("Game Over"), item names. Visual coding: labels, color names passed to turtle like "red".
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.
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
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
Forgetting the space string in between -> "AvaChen". The + doesn't add spaces for you.
Repeating strings with *
line = "-" * 10
print(line) # ----------
Building a divider line, repeating a character for a loading bar, stacking a player's name onto their score in one printed line.
word = "ha" laugh = word * 3 print(laugh)
Output:
String Indexing
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
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.
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.
For word = "GAME", what is word[1]?
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)
len() returns how many characters are in a string (its length).
word = "PYTHON"
print(len(word)) # 6
len(word) - 1 always equals the index of the last character. That's why word[-1] is such a handy shortcut - no counting required.
name = "ROBOT" print(len(name)) print(name[-1])
Output: and
String Methods
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.
| Method | What it does | Example |
|---|---|---|
.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
.upper() for a "GAME OVER" banner. .strip() to clean up messy typed input. .lower() so "YES" and "yes" both count as a valid answer.
"play again".replace("play", "quit") ->
String Roundup: Mistakes & Practice
Mismatched quotes: "hello' - Python needs the same quote type on both ends.
Treating a number-looking string as a number: "3" + "4" gives "34" (joined text), not 7.
Off-by-one indexing: expecting word[1] to be the first letter. It's actually the second.
Mini Practice
What is the data type of "42"?
word = "SPACE" - what is word[0]? What is word[-1]?
What does "go" * 3 print?
Find the bug: print('It's a bug') - what's wrong and how would you fix it?
Integer - Whole Numbers
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
| Integers | Not integers |
|---|---|
5, 0, -12, 100 | 3.14 (has a decimal) - "5" (it's text) |
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
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).
lives = 3 lives = lives - 1 print(lives)
Output:
Float - Decimal Numbers
A float (float, short for "floating-point number") is any number with a decimal point.
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.
| Floats | Not floats |
|---|---|
3.14, 0.5, -2.0, 100.0 | 3 (no decimal - that's an int) - "3.14" (text) |
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
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.
x = 5 y = 2.0 print(x + y)
Output: (mixing int + float always produces a float)
Arithmetic Operators Chart
| Symbol | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division (always gives a float) | 5 / 2 | 2.5 |
// | Floor division (rounds down, drops remainder) | 5 // 2 | 2 |
% | Modulo (the leftover remainder) | 5 % 2 | 1 |
** | Exponent (power) | 5 ** 2 | 25 |
score = score + 10 # add points lives = lives - 1 # lose a life is_even_turn = turn % 2 # 0 if even, 1 if odd
% (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.
print(10 // 3) print(10 % 3)
Output: and
Compound Assignment Operators
A shortcut for "take a variable, change it, and store it back in itself."
| Shortcut | Means the same as |
|---|---|
score += 10 | score = score + 10 |
lives -= 1 | lives = lives - 1 |
size *= 2 | size = size * 2 |
health /= 2 | health = health / 2 |
score = 0
score += 10
score += 10
print(score) # 20
Read += as "plus-equals." It always means: do the math, then save the result back into the same box.
Nearly every game uses these constantly: adding points on a hit, subtracting a life on damage, doubling a power-up's strength.
Rewrite lives = lives - 1 using a compound operator:
Type Conversion - Full Reference
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
| Function | Converts to | Fails if... |
|---|---|---|
int(x) | integer | x isn't a whole number, e.g. int("hi") |
float(x) | float | x isn't a valid number at all |
str(x) | string | almost never fails - everything can become text |
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 +
print("Score: " + 10) # ERROR - can't + a string and an int
Fix: print("Score: " + str(10)) or just use an f-string (p6).
Boolean & Comparison Operators
A Boolean (bool) is a value that is either True or False. Nothing in between.
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.
| Symbol | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
> | greater than | 5 > 3 | True |
< | less than | 5 < 3 | False |
>= | greater or equal | 5 >= 5 | True |
<= | less or equal | 5 <= 3 | False |
5 > 3 5 == 3
v v
True False
Using = (assignment) when you mean == (comparison). if score = 10: is a syntax error - use if score == 10:.
lives = 0 print(lives == 0) print(lives > 0)
Output: and
and / or / not
These combine multiple Boolean values into one Boolean answer.
| A | B | A and B | A or B |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
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
if lives > 0 and time_left > 0: - game only continues if both are true. if answer == "y" or answer == "yes": - accept either spelling.
print(not False) ->
None - The Empty Value
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.
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")
Compare to None using is None, not == None. Not required to know why yet - just the habit to build now.
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.
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.
Data Types Review Roundup
"7" | |
7 | |
7.0 | |
True | |
None |
a = 4 b = "4" print(a == b)
Output: (different types are never equal, even if they look alike)
age = input("Age: ")
next_year = age + 1
print(next_year)
What's wrong, and how would you fix line 2?
if Statements - Making Decisions
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.
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
if lives > 0
print("Keep playing!") # missing colon after condition
if lives > 0:
print("Keep playing!") # not indented - Python doesn't know it's inside the if
Write an if statement that prints "Level up!" when score >= 100:
if / elif / else
| Keyword | Means |
|---|---|
if | Check this condition first. |
elif | "Else if" - if the first one was False, check this one instead. |
else | If 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")
PLAYER HAS KEY?
|
+------+------+
YES NO
| |
OPEN DOOR "LOCKED"
| |
(done) (done)
if has_key:
print("The door opens.")
else:
print("Locked. Find a key.")
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.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 80:
print("also B?")
Output:
Nested Conditions & Game Examples
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!"
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.
Checking win conditions (if lives > 0 and flag_captured:), checking multiple requirements to unlock a level, checking difficulty tiers.
Rewrite the nested example above using and instead of nesting, for the "treasure room" case only:
Control Flow Practice
health = 0
if health > 0:
print("Alive")
else:
print("Game Over")
Output:
if score > 10
print("You win!")
What's wrong?
Write code: if coins >= 5, print "Buy a power-up!", otherwise print "Keep collecting."
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.
What Is a Loop?
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.
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
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.
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.
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
| Piece | What it means |
|---|---|
for | "Repeat the following, once per item." |
i | A brand-new variable that changes each time through the loop. Could be named anything, but i is the common convention. |
in | Connects 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. |
for i in range(3):
print(i)
Output (3 lines):
Assuming range(4) counts 1,2,3,4. It actually counts 0,1,2,3 - four numbers starting at zero.
range() - The Full Reference
| Call | Produces |
|---|---|
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)
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.
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.
What does range(1, 5) produce?
while Loops
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
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.
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.
n = 3
while n > 0:
print(n)
n -= 1
Output (3 lines, in order):
Loop Mistakes & Practice
Off-by-one: using range(5) when you actually wanted 5 to be included (it isn't - use range(1,6) instead).
Forgetting to update the loop variable in a while loop -> infinite loop.
Indenting code outside the loop by accident, so it runs every iteration instead of once at the end.
How many times does this loop run? for i in range(5): print("Hi")
Fix this infinite loop:
count = 0
while count < 5:
print(count)
My fix:
Write a for loop that prints "Enemy spawned" 3 times:
What Is a Function?
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.
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
You've already used functions! print(), input(), len(), range(), int() are all built-in functions. Now you'll learn to write your own.
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.
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!"
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.
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.
Parameters vs. Arguments
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)
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)
def take_damage(amount):
print(f"Player takes {amount} damage!")
take_damage() # ERROR - missing required argument
In def spawn_enemy(x, y):, name the two parameters: and
Return Values
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
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.
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!
def double(n):
return n * 2
result = double(4)
print(result)
Output:
Functions Practice
Write a function called square that takes a number n and returns n * n.
def is_alive(lives):
return lives > 0
print(is_alive(0))
print(is_alive(3))
Output: and
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
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 →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()
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.
You can name your turtle anything: t, artist, bob. Whatever you name it, every command afterward starts with that name and a dot.
Turtle Command Reference
| Command | What 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(). |
Forgetting t.penup() before repositioning - you'll draw an unwanted line all the way to your new spot.
Write the two lines that move the turtle to a new spot without drawing a line, then start drawing again:
The Turtle Coordinate System
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
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.
Placing shapes at exact spots, scattering random "stars" across the screen (paired with p49's random), building a simple grid-based game board.
What coordinate is directly below center by 75 pixels?
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"
Calling end_fill() without a matching begin_fill() - nothing gets filled because Python never started tracking the shape.
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.
Turtle Art - Square & Triangle
| Sketch | Plan | Code | Result |
|---|---|---|---|
| 4 equal sides, 90deg corners | repeat 4x: forward, turn 90deg | see below | a square |
for i in range(4):
t.forward(100)
t.right(90)
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)
For any regular shape with n sides: turn angle = 360 / n. This one formula unlocks every shape on the next page.
What turn angle would draw a 6-sided shape (hexagon)?
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)
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
Change sides = 8 to sides = 3 in the polygon code above. What shape draws now?
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
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
How would you change the flower code to draw 6 petals instead of 10? (Hint: two numbers need to change together.)
Patterns, Loops of Loops & What's Next
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
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.
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.
The random Module
import random
| Function | What it does | Example |
|---|---|---|
random.randint(a, b) | Random whole number, including both a and b | random.randint(1, 6) -> dice roll |
random.choice(list) | Picks one random item from a list | random.choice(["red","blue"]) |
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)
Dice and card games, enemy spawn positions, random colors or shapes in art, "critical hit" chance, shuffling which question comes next.
random.randint(1, 3) - list every possible result:
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"]))
Write one line that picks a random number of sides between 3 and 10, for a random polygon:
Forgetting import random at the top - every use of random.anything() needs it, just once, at the start of the file.
What Is a List?
A list stores multiple values together, in order, inside square brackets [ ], separated by commas.
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"
Lists use the exact same index rules as strings (p14): counting starts at 0, and list[-1] is the last item.
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.
Make a list called weapons with 3 weapon names of your choice:
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
Unlike strings, lists are changeable (mutable) - you can overwrite one item without rebuilding the whole list.
colors = ["red", "blue", "green"]
print(colors[3]) # ERROR - no index 3, only 0,1,2 exist
items = ["sword", "shield"] items[0] = "axe" print(items)
Output:
List Methods - append, remove, len
| Method | What it does | Example |
|---|---|---|
.append(x) | Adds x to the end | inventory.append("key") |
.remove(x) | Removes the first x it finds | inventory.remove("key") |
len(list) | How many items are in it | len(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"]
inventory.remove("bow") # ERROR if "bow" isn't in the list
.remove() needs an exact match that actually exists in the list.
Starting from enemies = ["goblin", "orc"], write the line to add "dragon":
Lists in Games
Looping over a list - combine with p32!
enemies = ["goblin", "orc", "dragon"]
for enemy in enemies:
print(f"A wild {enemy} appears!")
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.
scores = [70, 85, 90]
total = 0
for s in scores:
total += s
print(total)
Output:
Write a loop that prints every item in high_scores = [120, 98, 150] on its own line:
Game State - The Scoreboard Idea
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.
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
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.
Deciding whether the game is over (lives <= 0), deciding what to draw (player_x, player_y), deciding difficulty (level).
The Game Loop
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 ---------+
| Step | Means |
|---|---|
| Input | Read what the player did (key press, typed guess). |
| Update | Change the state based on that input (move player, subtract a life). |
| Check Rules | Has anyone won or lost? Did something collide? |
| Output | Show the result - print text, redraw the screen. |
| Repeat | Go 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
break immediately exits the loop - useful for ending a game loop the instant someone wins, without waiting for the condition to naturally go False.
Game Vocabulary I
Player - the character or object the person using the game directly controls.
Enemy - a character controlled by the game (not the player) that opposes the player.
Obstacle - something in the environment that blocks or challenges the player, but doesn't act on its own like an enemy does.
Score - a number tracking how well the player is doing, usually meant to go up.
Lives - how many times the player can fail before the game ends.
Level - a distinct stage or section of the game, usually increasing in difficulty.
player_x, player_y = 0, 0 enemy_x, enemy_y = 100, 100 score = 0 lives = 3 level = 1
Name one obstacle and one enemy idea for a game you'd want to build: /
Game Vocabulary II
Win condition - the exact rule that ends the game in the player's favor. Example: score >= 100.
Lose condition - the exact rule that ends the game against the player. Example: lives <= 0.
Collision - when two objects occupy the same space, usually triggering an effect (damage, pickup, bounce).
Timer - a value that counts down (or up) over time, often ending the game or an event when it hits zero.
Power-up - a temporary or permanent boost the player can collect (extra life, speed boost).
Inventory - a list of items the player is currently holding (see p51's lists!).
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")
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:.
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}.")
| Line | What 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 += 1 | Count this guess, every time through the loop. |
won = True | Flip the flag so the while condition goes False next check. |
If target = 4 and the player guesses 2, then 4 - trace it: what prints, and after how many attempts?
Types of Bugs
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.
| Type | Meaning | Example |
|---|---|---|
| Syntax Error | Broken grammar - Python can't even start running it. | Missing colon, mismatched quotes. |
| Runtime Error | The code runs, then crashes partway through. | Dividing by zero, index out of range. |
| Logic Error | The code runs fine with no crash, but gives the wrong answer. | Using + when you meant -. |
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.
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.
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"
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.
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.
Next time you hit a real error, write the line number and error message here, then work through the steps above:
The Error Museum
Every beginner walks past these exhibits. Recognize the shape of the mistake, not just the exact code.
| Exhibit | Broken | Fixed |
|---|---|---|
| Missing colon | if score > 10 | if score > 10: |
| Missing parenthesis | print("hi" | print("hi") |
| Bad indentation | if x: | if x: |
| Misspelled variable | print(scroe) | print(score) |
| Wrong data type | "5" + 5 | int("5") + 5 |
| Forgetting quotes | print(hello) | print("hello") |
| Infinite loop | while True: | add something that eventually breaks the loop |
| Wrong condition | if lives = 0: | if lives == 0: |
NameError: name 'scroe' is not defined - 90% of the time, this means a typo in a variable name. Check spelling and capitalization first.
Add one bug you personally made this week to this museum, and its fix:
Debugging Checklist
Work through these, in order, before asking for help.
- [ ] 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?
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.
How To Read Code - Tracing Variables
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)
| Line | x | y |
|---|---|---|
x = 5 | 5 | - |
y = 2 | 5 | 2 |
x = x + y | 2 | |
y = x - y |
Read the right side of an = first - Python always fully calculates it before storing anything.
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.
What Does This Code Do?
total = 0
for i in range(1, 6):
total += i
print(total)
Identify: the loop, the condition (if any), the final value of total.
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.
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.
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.
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.
In one sentence, what is this game?
What can the player do? What isn't allowed?
What input does the player give? (typed text, key presses)
Project Planning Worksheet
List actions that will repeat:
Turtle shapes, colors, layout:
Does difficulty change over time? How?
If this had sound, what would play and when?
What's the very first small piece you'll build and test, before anything else?
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.
Python Symbols Cheat Sheet
| Symbol | Name | Meaning |
|---|---|---|
+ | Plus | Addition, or joining strings |
- | Minus | Subtraction |
* | Star | Multiplication, or repeating strings |
/ | Slash | Division (always returns a float) |
// | Double slash | Floor division (rounds down) |
% | Percent / Modulo | Remainder after division |
** | Double star | Exponent (power) |
= | Equals | Assignment - store a value |
== | Double equals | Comparison - are these equal? |
!= | Not-equals | Comparison - are these different? |
> < | Greater / Less than | Comparison |
>= <= | Greater / Less or equal | Comparison |
+= -= *= /= | Compound assignment | Update a variable using itself |
[ ] | Square brackets | Indexing, or defining a list |
( ) | Parentheses | Calling a function, grouping math |
: | Colon | Starts a new indented block (if/for/while/def) |
# | Hash | Starts a comment - Python ignores the rest of the line |
Python Vocabulary Dictionary - A to L
| Term | Definition |
|---|---|
| Algorithm | A step-by-step set of instructions for solving a problem. |
| Argument | The real value handed to a function when you call it. |
| Assignment | Storing a value into a variable, using =. |
| Boolean | A True/False value. |
| Bug | Anything wrong with your code. |
| Code | Written instructions for a computer. |
| Condition | A statement that evaluates to True or False. |
| Data | Information a program stores and works with. |
| Data type | The category a value belongs to (str, int, float, bool...). |
| Debugging | Finding and fixing bugs. |
| Event | Something that happens that a program can react to (a key press, a click). |
| Expression | Any bit of code that produces a value, like 5 + 2. |
| Float | A decimal number. |
| Function | A named, reusable block of code. |
| Game loop | The repeating cycle of input -> update -> check -> output. |
| Index | The position number of an item in a string or list, starting at 0. |
| Input | Information going into a program, often from the user. |
| Integer | A whole number. |
| Iteration | One single repetition of a loop. |
| List | An ordered collection of values in square brackets. |
Python Vocabulary Dictionary - M to Z
| Term | Definition |
|---|---|
| Method | An action attached to a value, called with a dot: value.method(). |
| Module | A file of pre-written code you can import and use (same idea as a library). |
| Object | A thing your code creates that has its own properties and actions. |
| Operator | A symbol that performs an operation, like + or ==. |
| Output | Information a program produces, often shown on screen. |
| Parameter | The placeholder name in a function's definition. |
| Program | A complete set of code that does something useful. |
| Programming | The act of writing code to build a program. |
| Return | Sending a value back out of a function. |
| State | The current values of all the important variables in a program. |
| String | Text, wrapped in quotation marks. |
| Syntax | The exact spelling and grammar rules of a language. |
| Value | A single piece of data - a number, some text, a Boolean. |
| Variable | A named box that stores a value. |
Pick 3 words above you still find confusing. Flip back to the page that explains each one and re-read it right now:
"When Do I Use This?"
Stuck on what tool to reach for? Start here.
| I need to... | Reach for... | Page |
|---|---|---|
| Display something | print() | p5 |
| Ask the user something | input() | p7 |
| Store information | a variable | p9 |
| Turn typed text into a number | int() / float() | p22 |
| Repeat something a set number of times | for loop | p32 |
| Repeat until a condition changes | while loop | p34 |
| Make a decision | if / elif / else | p27 |
| Reuse the same code in many places | a function | p36 |
| Store many values together | a list | p51 |
| Generate unpredictability | random | p49 |
| Draw something on screen | turtle | p41 |
| Track score, lives, or position | game state variables | p55 |
| Something isn't working | the Bug Detective | p61 |
Visual Analogies - The Complete Set
| Concept | Analogy |
|---|---|
| Variable | A labeled storage box |
| Function | A machine - input goes in, output comes out |
| Loop | A conveyor belt, repeating the same action |
| if statement | A decision gate - one path or the other |
| List | A row of numbered lockers |
| String | Beads threaded on a string, each one a character |
| Integer | A whole-number counter - score, lives |
| Float | A measuring cup - captures the in-between amounts |
| Boolean | A light switch - only ON or OFF |
| Debugging | Detective work - evidence, hypothesis, test |
| Game state | A scoreboard - a snapshot of everything happening now |
| f-string | A fill-in-the-blank sentence |
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.
Capstone Project Checklist
You've made it through the whole guide. Time to build something real and put every page to work.
- [ ] 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
- [ ] 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
iffor the rules - [ ] Tested after every small change, not just at the end
- [ ] Ran the Debugging Checklist (p63)
- [ ] Traced the variables by hand (p64)
- [ ] Flipped back to the relevant page instead of guessing