← Back to Education
Education digital-technologies year-9

Python Reference

A practical Python lookup page for syntax, structures, common errors, and worked examples.

Published Updated Type reference

Use this page as a lookup tool while coding. It complements the chapter sequence by giving quick reminders and examples across the whole Python toolkit.

Reference Areas

  • variables and data types
  • input and output
  • conditional logic
  • loops and iteration
  • lists, dictionaries, sets, and tuples
  • functions and modular thinking
  • debugging patterns and error interpretation

How To Use It In Class

  • use this page for targeted help when a concept blocks progress
  • return to the chapter pages for full learning flow and context
  • pair examples here with your own test inputs before reusing them

See Also

🐍 Python Reference Wiki
A single place to learn and look things up,from absolute beginner to solid intermediate. Every section includes examples, common mistakes, and two practice tasks with hints and solutions (all collapsed).
✅ How to use this page (read this once)
  • Use the Jump Menu below to find what you need fast.
  • Open the Examples dropdowns and run the code in your editor.
  • Then do the Try it tasks. They’re part of learning - not “extra work”.
  • The Try it tasks will teach you more functions - think of them as extra tips and tricks!
  • If you get an error: read the last line first. It usually tells you what went wrong.
  • Use the ↑ Back to top link at the end of every section to return here.
⚠️ Important
Python is picky about indentation. If the spacing is wrong, your program is wrong - even if the words are correct.
🎯 Your job while learning Python
  • Run code. Change one thing. Run it again.
  • Predict what will happen before you run it.
  • When stuck: isolate the problem (smallest failing piece).
Tip: If your code “doesn’t work”, copy the error message into your notes. Errors are clues.
1) Getting started: running code, printing, and comments
This section is about the first moves in Python: writing lines that actually run, seeing output, and leaving yourself clear notes. You’ll also learn the two rules that cause most beginner problems: indentation matters and errors are clues.
✅ Success looks like
  • You can run a Python file and see output.
  • You can explain what print() does.
  • You can add comments that explain your thinking.
📌 Core idea: Output is how you “talk” to the computer

When you write Python, you need a way to see what the program is doing. That’s what print() is for.

Think of it like this:
  • Your code = instructions
  • Output = evidence the instructions happened
  • Print statements = your “window” into what’s happening
👀 Examples: print(), comments, and running code
Example A: The smallest working program
# This is a comment. Python ignores it.
# Comments are for humans (including future you).

print("Hello, world!")
print("If you can see this, your code is running.")
What you should notice: Each print() produces a new line of output.
Example B: Printing values and mixing text + numbers
score = 7
total = 10

# f-strings let you embed variables inside text
print(f"Score: {score} out of {total}")
print(f"Percentage: {score/total * 100}%")
Why this matters: Beginners often try to “glue” text and numbers using + and hit type errors. f-strings are the easiest clean option.
Example C: A “run-check” pattern (for bigger programs)
print("=== Program starting ===")

# Your code goes here...
name = "Ava"
print(f"Loaded name: {name}")

print("=== Program finished ===")
Why this helps: If you don’t see “Program finished”, your code crashed before the end.
⚠️ Common mistakes (and fixes)
Mistake 1: Missing quotes around text
If you want Python to print text, you must put it in quotes.
# ❌ Wrong
print(Hello)

# ✅ Right
print("Hello")
Mistake 2: Using smart quotes (from Google Docs / Word)
Some apps turn quotes into curly quotes like “ ”. Python usually rejects them. Use straight quotes: " "
# ❌ Might break (curly quotes)
print(“Hello”)

# ✅ Works (straight quotes)
print("Hello")
Mistake 3: Expecting print() to “store” a value
print() shows something. It doesn’t save it. To save a value, you need a variable (next section).
# This prints 5, but doesn't store it anywhere
print(2 + 3)

# This stores the value in a variable AND prints it
result = 2 + 3
print(result)
🎮 Try it: mini practice tasks
Task 1 (starter): Make a “3-line intro” program
Write a program that prints:
  • A title line (your choice)
  • Your name (or a nickname)
  • One fun fact (school-appropriate)
Checkpoint: When you run it, you see exactly 3 lines.
Hint
Use three separate print() lines. Text must be inside quotes.
Solution
print("=== My Python Intro ===")
print("Name: Sam")
print("Fun fact: I can juggle three objects.")
Task 2 (stretch): Print a “status report” using variables + f-strings
Create two variables:
  • level (a number)
  • nickname (text)
Then print one line like:
Nickname = CodeNinja, Level = 3
Checkpoint: If you change the variable values, the printed line updates without changing the print text.
Hint
Use an f-string: print(f"... {variable} ...")
Text needs quotes. Numbers do not.
Solution
level = 3
nickname = "CodeNinja"

print(f"Nickname = {nickname}, Level = {level}")
2) Variables & data types: storing information on purpose
A variable is a name that points to a value, so you can reuse it, update it, and make your code readable. A data type is the kind of value you’re storing (number, text, true/false, etc.). Getting these right early makes everything else easier: input, maths, decisions, loops - all of it.
✅ Success looks like
  • You can create variables and update them.
  • You can tell the difference between int, float, str, bool.
  • You can use type() to check what Python thinks a value is.
  • You can convert types when you need to (especially after input()).
📌 Core idea: Variables help you avoid repeating yourself

Without variables, you end up copying the same values everywhere. That makes code harder to change and easier to break. Variables let you store information once, then reuse it reliably.

A quick example of why variables matter:
If you write the number 25 all over your code and later it needs to become 30, you have to find every single 25. With a variable, you change it once.
Important: In Python, you do not have to “declare” variable types. Python figures it out from the value. But you still need to understand types, because types affect what operations are allowed.
🧱 Data types you’ll use constantly
int
Whole numbers (no decimal point)
Examples: 0, 7, -12, 2048
float
Numbers with decimals
Examples: 3.14, 0.5, -2.0
str
Text (characters) inside quotes
Examples: "hi", "25", "Year 9"
bool
True/False values (used in decisions)
Examples: True, False
Two very common “gotchas”
  • "25" is a string (text). 25 is an integer (number).
  • Python cares about this difference. It changes what + means (add vs join).
👀 Examples: variables, type(), and updating values
Example A: Variables store values and can change
score = 0
print(f"Starting score: {score}")

score = score + 1
print(f"After +1: {score}")

score = score + 5
print(f"After +5: {score}")

score = 100
print(f"Reset score: {score}")
Notice: The variable name stays the same, but the value can be updated whenever you assign a new value.
Example B: Checking types with type()
age = 15
height = 1.72
name = "Ravi"
is_student = True

print(type(age))
print(type(height))
print(type(name))
print(type(is_student))
What you should see: <class 'int'>, <class 'float'>, etc.
Example C: When + means different things
print(10 + 5)          # numbers: addition
print("10" + "5")      # strings: joining (concatenation)

# Mixing types causes errors:
# print("Score: " + 10)  # TypeError

# Use an f-string instead:
print(f"Score: {10}")
Key idea: The operator is the same symbol, but the behavior depends on the data types.
Example D: Converting types (this will save you later)
text_number = "42"
print(text_number)
print(type(text_number))

real_number = int(text_number)
print(real_number)
print(type(real_number))

decimal_text = "3.5"
real_decimal = float(decimal_text)
print(real_decimal)
print(type(real_decimal))

print(str(999))        # convert number to text
Important: int() only works if the string is a whole number like "42". For decimals like "3.5", use float().
⚠️ Common mistakes (and fixes)
Mistake 1: Thinking Python “knows” what you meant
Python does exactly what you write, not what you meant. If a number is inside quotes, Python treats it as text.
apples = "5"
more_apples = "2"
print(apples + more_apples)  # prints "52" not 7
Fix: convert to a number first.
apples = int("5")
more_apples = int("2")
print(apples + more_apples)  # prints 7
Mistake 2: Variable names that cause confusion
Use names that explain the meaning. Avoid single letters (except simple loops later). Don’t use Python keywords like print, input, type as variable names.
# ❌ Confusing or dangerous
print = 10
type = "hello"

# ✅ Clear
player_score = 10
player_name = "hello"
Mistake 3: Using commas but expecting f-string formatting
This works, but it prints spaces in a specific way. f-strings give you more control.
name = "Mina"
age = 15

print("Name:", name, "Age:", age)       # works
print(f"Name: {name} | Age: {age}")     # clearer formatting
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Score tracker
Make a program that:
  1. Creates a variable called score starting at 0
  2. Prints the score
  3. Adds 10 to the score
  4. Prints the score again
  5. Adds 3 more
  6. Prints the final score
Checkpoint: You should see three printed values, and they should increase each time.
Hint
You can update a variable using: score = score + 10
Use f-strings to print nicely: print(f"Score: {score}")
Solution
score = 0
print(f"Score: {score}")

score = score + 10
print(f"Score: {score}")

score = score + 3
print(f"Score: {score}")
Task 2 (stretch): Type detective
Create four variables:
  • One int
  • One float
  • One string that looks like a number (example: "12")
  • One bool
Then print each variable and its type on a separate line.
Checkpoint: Your output shows four lines, and each line includes something like <class 'int'>.
Hint
Use type(variable_name).
You can print a value and its type on one line using an f-string: print(f"{x} -> {type(x)}")
Solution
whole = 15
decimal = 2.5
looks_like_number = "12"
flag = True

print(f"{whole} -> {type(whole)}")
print(f"{decimal} -> {type(decimal)}")
print(f"{looks_like_number} -> {type(looks_like_number)}")
print(f"{flag} -> {type(flag)}")
3) Input & output: talking with your program
So far, your programs have only talked at the user. Input lets your program listen. Almost every real program follows this loop: ask → process → respond.
✅ Success looks like
  • You can use input() to ask questions.
  • You understand that input is always text.
  • You can convert input into numbers when needed.
  • You can format output clearly using f-strings.
📌 Core idea: input() always returns a string

This is one of the most important rules in beginner Python:
Everything that comes from input() is text.

Even if the user types 42, Python sees it as "42". If you want to do maths, you must convert it first.
Rule of thumb: Use int() or float() immediately after input() if you plan to do maths.
👀 Examples: input(), storing responses, and conversion
Example A: Asking a question and responding
name = input("What is your name? ")
print(f"Hello, {name}!")
What’s happening: The program pauses, waits for input, stores it in name, then prints a response.
Example B: Why conversion matters
age_text = input("How old are you? ")

print(age_text + 1)      # ❌ error (string + number)
This fails because age_text is a string.
age = int(input("How old are you? "))
print(age + 1)           # ✅ works
Example C: Using input inside calculations
width = float(input("Enter the width (m): "))
height = float(input("Enter the height (m): "))

area = width * height
print(f"Area = {area} square metres")
Key idea: Convert once, then treat the variable like a normal number.
⚠️ Common mistakes (and fixes)
Mistake 1: Forgetting to convert input
number = input("Enter a number: ")
print(number * 2)   # prints text twice, not doubled
Fix: convert the input.
number = int(input("Enter a number: "))
print(number * 2)
Mistake 2: Messy prompts
If your prompt doesn’t include a space or punctuation, the input looks squashed.
# ❌ Hard to read
name = input("Enter your name")

# ✅ Clear
name = input("Enter your name: ")
Mistake 3: Expecting input() to remember answers
input() only returns a value once. If you want to reuse it, store it in a variable.
# ❌ Asked twice
print(input("Name: "))
print(input("Name: "))

# ✅ Asked once, reused
name = input("Name: ")
print(name)
print(name)
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Age next year
Write a program that:
  1. Asks the user for their age
  2. Converts it to a number
  3. Prints how old they will be next year
Checkpoint: If the user enters 14, the program prints 15.
Hint
Convert input using int() before adding 1.
Solution
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}")
Task 2 (stretch): Rectangle calculator
Ask the user for the width and height of a rectangle, then calculate and print the area.
Checkpoint: Decimal values should work correctly.
Hint
Use float() instead of int().
Solution
width = float(input("Enter width: "))
height = float(input("Enter height: "))

area = width * height
print(f"Area = {area}")
4) Operators: doing things with values
Operators are the symbols that do work in Python. They compare values, perform calculations, and combine conditions. Most bugs at this stage come from using the right symbol in the wrong way.
✅ Success looks like
  • You can use arithmetic operators correctly.
  • You can compare values using ==, <, >.
  • You understand the difference between = and ==.
  • You can combine conditions using and / or.
📌 Core idea: Operators behave differently depending on data type

The same symbol can mean different things depending on the data types involved. Code doesn’t guess - it follows strict rules.

Example:
  • + adds numbers
  • + joins strings
  • == compares values
  • = assigns values
Golden rule: If Python throws an error, it’s usually because the operator and data types don’t match.
➕ Arithmetic operators
+ addition
- subtraction
* multiplication
/ division
// integer division
% remainder (modulo)
** powers
print(10 + 3)     # 13
print(10 / 3)     # 3.333...
print(10 // 3)    # 3
print(10 % 3)     # 1
print(2 ** 4)     # 16
Why this matters: // and % are extremely useful for checking even/odd numbers and splitting things into groups.
🔍 Comparison operators
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
age = 15

print(age == 15)   # True
print(age > 18)    # False
print(age != 10)   # True
Critical distinction: = assigns a value. == compares.
🧠 Logical operators
age = 15
has_permission = True

print(age >= 13 and has_permission)   # True
print(age >= 18 or has_permission)    # True
print(not has_permission)             # False
Think of it like English:
  • and → both must be true
  • or → at least one must be true
  • not → flips true/false
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Even or odd?
Ask the user for a number and print whether it is even or odd.
Checkpoint: Even numbers return “even”, odd numbers return “odd”.
Hint Use the modulo operator %.
Solution
number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even")
else:
    print("Odd")
Task 2 (stretch): Pass check
Ask for a score (0–100). Print Pass if the score is 50 or more, otherwise print Fail.
Hint Use a comparison operator inside an if statement.
Solution
score = int(input("Enter score: "))

if score >= 50:
    print("Pass")
else:
    print("Fail")
5) Conditionals: making decisions with if / elif / else
Conditionals let your program make choices. They’re how you turn a program from “always does the same thing” into “responds differently depending on the situation”. This is the logic behind games, menus, validation, and almost everything interactive.
✅ Success looks like
  • You can write a correct if block with indentation.
  • You can add extra conditions using elif.
  • You can handle “everything else” using else.
  • You can explain what a condition is (a True/False question).
📌 Core idea: an if statement is a True/False gate

An if statement checks a condition (a question with a True/False answer). If the condition is True, the indented code runs. If it’s False, Python skips it.

The structure matters:
if condition:
    # indented block runs only when condition is True
    do_something()
Two non-negotiables:
  • The colon : at the end of the line
  • Indentation under the if/elif/else
🧠 How if / elif / else works together
The decision flow
  1. Python checks the if condition.
  2. If it’s True, Python runs that block and skips the rest.
  3. If it’s False, Python checks the first elif.
  4. It keeps checking elif blocks in order until one is True.
  5. If none are True, Python runs the else block (if there is one).
Important: Order matters. Put the most specific conditions first, and the broad “catch-all” conditions later.
👀 Examples: simple decisions to multi-branch decisions
Example A: One decision (if)
temperature = int(input("Temperature (°C): "))

if temperature >= 30:
    print("It is hot today.")
If the condition is False, nothing prints. That’s normal: there’s no else.
Example B: Two outcomes (if/else)
number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even")
else:
    print("Odd")
This guarantees one result prints: even or odd.
Example C: Multiple outcomes (if/elif/else)
score = int(input("Score (0-100): "))

if score >= 85:
    print("A")
elif score >= 70:
    print("B")
elif score >= 50:
    print("C")
else:
    print("D")
Why the order matters: If you put score >= 50 first, it would catch 85 too, and you’d never get an A.
Example D: Combining conditions (and/or)
age = int(input("Age: "))
has_ticket = input("Do you have a ticket? (yes/no): ").lower()

if age >= 13 and has_ticket == "yes":
    print("You can enter.")
else:
    print("You cannot enter.")
Notice: We used .lower() so "YES", "Yes", "yes" all behave the same.
⚠️ Common mistakes (and fixes)
Mistake 1: Using = instead of ==
= assigns. == compares. In an if condition, you almost always want ==.
# ❌ Wrong
# if score = 50:

# ✅ Right
# if score == 50:
Mistake 2: Forgetting the colon
# ❌ Wrong
# if age >= 13
#     print("OK")

# ✅ Right
# if age >= 13:
#     print("OK")
Mistake 3: Indentation errors
Everything under an if/elif/else must line up with the same indentation level.
# ❌ Wrong (mixed indentation)
if True:
  print("A")
    print("B")

# ✅ Right (same indentation level)
if True:
    print("A")
    print("B")
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Number sign
Ask for a number and print:
  • Positive if it’s greater than 0
  • Zero if it’s exactly 0
  • Negative if it’s less than 0
Checkpoint: The program prints exactly one of the three words.
Hint
Use if, elif, and else. One of the conditions can be “everything else”.
Solution
number = int(input("Enter a number: "))

if number > 0:
    print("Positive")
elif number == 0:
    print("Zero")
else:
    print("Negative")
Task 2 (stretch): Simple login check
Set a secret password in your code (example: "platypus"). Ask the user to enter a password.
  • If it matches, print Access granted
  • Otherwise, print Access denied
Checkpoint: "Platypus" and "platypus" should be treated as the same password.
Hint
Use .lower() on the user’s input before comparing it.
Solution
secret = "platypus"
guess = input("Enter password: ").lower()

if guess == secret:
    print("Access granted")
else:
    print("Access denied")
6) Loops: repeating actions on purpose
Loops let your program repeat instructions without copying and pasting code. Any time you see yourself doing the same thing again and again, a loop is probably the right tool.
✅ Success looks like
  • You can use a for loop to repeat a fixed number of times.
  • You can use a while loop to repeat until a condition changes.
  • You understand what an infinite loop is — and how to avoid it.
  • You can explain what the loop variable represents.
📌 Core idea: loops save time and reduce mistakes

Without loops, repeating actions means copying code. That’s slow to write, hard to change, and easy to mess up.

Loops help you:
  • repeat actions cleanly
  • scale your program easily
  • change behaviour by updating one line
🔁 for loops: repeating a known number of times
Basic structure
for i in range(5):
    print(i)
This prints the numbers 0 to 4.
i is the loop variable : it changes automatically each time.
Using range()
for i in range(1, 6):
    print(i)

for i in range(0, 10, 2):
    print(i)
range(start, stop, step) lets you control where counting starts, stops, and how it steps.
⏳ while loops: repeating until something changes
Basic structure
count = 0

while count < 5:
    print(count)
    count = count + 1
The condition is checked before each loop. If it never becomes False, the loop never ends.
Important: Every while loop must change something that affects its condition.
⚠️ Common mistakes (and fixes)
Mistake 1: Infinite loops
# ❌ Infinite loop
count = 0
while count < 5:
    print(count)
Fix: Update the variable inside the loop.
Mistake 2: Loop variable misuse
Don’t manually change the loop variable in a for loop: Python already does that.
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Count down
Use a for loop to count down from 10 to 1.
Hint Use range() with a negative step.
Solution
for i in range(10, 0, -1):
    print(i)
Task 2 (stretch): Guessing game
Keep asking the user to guess a number until they type the correct one.
Hint Use a while loop that runs until the guess is correct.
Solution
secret = 7
guess = -1

while guess != secret:
    guess = int(input("Guess the number: "))

print("Correct!")
7) Strings: working with text
Strings are how Python stores and works with text. They’re everywhere: user input, messages, file data, names, passwords. Learning to control strings properly is a huge step toward writing real programs.
✅ Success looks like
  • You can index and slice strings.
  • You can use common string methods.
  • You understand that strings are sequences.
  • You can clean and normalise user input.
📌 Core idea: a string is a sequence of characters

In Python, a string is a sequence of text. That means:

  • You can access individual characters
  • You can loop over it
  • You can take slices (parts of it)
Important: Strings are immutable. You can’t change a character inside a string — you make a new string instead.
🔎 Indexing and slicing strings
Indexing
word = "python"

print(word[0])   # p
print(word[1])   # y
print(word[-1])  # n (last character)
Indexing starts at 0. Negative indexes count from the end.
Slicing
text = "computer science"

print(text[0:8])     # computer
print(text[9:])      # science
print(text[:8])      # computer
Slicing uses [start:stop]. The stop index is not included.
🧰 Common string methods you will use a lot
text = "  Hello World  "

print(text.lower())      # hello world
print(text.upper())      # HELLO WORLD
print(text.strip())      # Hello World
print(text.replace("World", "Python"))
print(text.split())      # ['Hello', 'World']
Why this matters: Cleaning and normalising input avoids bugs caused by spaces and capital letters.
⚠️ Common mistakes (and fixes)
Mistake 1: Trying to change a character directly
# ❌ Not allowed
word = "cat"
# word[0] = "b"
Fix: build a new string.
word = "cat"
word = "b" + word[1:]
print(word)
Mistake 2: Forgetting to clean input
answer = input("Yes or no? ")

if answer == "yes":
    print("OK")
Fix: normalise input first.
answer = input("Yes or no? ").strip().lower()

if answer == "yes":
    print("OK")
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Username cleaner
Ask the user for a username. Remove spaces and convert it to lowercase before printing it.
Hint Use strip() and lower().
Solution
username = input("Enter username: ").strip().lower()
print(username)
Task 2 (stretch): First and last letters
Ask the user for a word and print the first and last letters.
Hint Use indexing with [0] and [-1].
Solution
word = input("Enter a word: ")
print(word[0])
print(word[-1])
8) Lists & tuples: storing many values in one place
A single variable can store one value… but most real problems involve collections. Lists and tuples let you group values together so you can loop over them, update them, and keep your data organised.
✅ Success looks like
  • You can create a list and access items by index.
  • You can change a list (lists are mutable).
  • You can loop through a list with for.
  • You know that tuples are like lists, but fixed (immutable).
📌 Core idea: a list is a sequence of values

A list stores multiple values in a single variable, in a specific order. Each item has an index (starting at 0), just like strings.

Think of a list as: a backpack with labelled pockets (indexes). You can add, remove, and swap items.
Important: Lists can change (mutable). Tuples can’t (immutable).
🧱 Creating lists and accessing items
Create a list
fruits = ["apple", "banana", "mango"]
numbers = [3, 7, 10, 12]
mixed = ["Ava", 14, True]
Access items by index
fruits = ["apple", "banana", "mango"]

print(fruits[0])   # apple
print(fruits[1])   # banana
print(fruits[-1])  # mango (last item)
Checkpoint: Indexes start at 0, and negative indexes count from the end.
🛠️ Changing a list: append, remove, and update
Example A: Updating items
teams = ["red", "blue", "green"]
teams[1] = "yellow"
print(teams)   # ['red', 'yellow', 'green']
Lists are mutable, so you can replace an item by assigning a new value at that index.
append()
Adds an item to the end of the list
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
remove()
Removes the first matching value
fruits = ["apple", "banana", "mango"]
fruits.remove("banana")
print(fruits)
Watch out: remove() removes by value. If the value is not in the list, Python gives an error.
🔁 Looping through a list
The most common pattern
pets = ["dog", "cat", "fish"]

for pet in pets:
    print(pet)
Python sets pet to each item in the list, one by one.
When you need the index too
pets = ["dog", "cat", "fish"]

for i in range(len(pets)):
    print(i, pets[i])
This pattern is useful when you need both the position and the value.
📦 Tuples: like lists, but fixed
Creating a tuple
coords = (10, 20)
days = ("Mon", "Tue", "Wed")
Important: You can read items from a tuple, but you can’t change them. That’s why tuples are used for “this should not change” data (like coordinates).
⚠️ Common mistakes (and fixes)
Mistake 1: Index out of range
If a list has 3 items, valid indexes are 0, 1, and 2.
names = ["Ava", "Noah", "Zoe"]
# print(names[3])  # ❌ error
Mistake 2: Expecting remove() to use an index
remove() removes by value, not index.
names = ["Ava", "Noah", "Zoe"]

# ❌ Wrong idea:
# names.remove(1)

# ✅ Correct:
names.remove("Noah")
print(names)
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Class roll list
Create a list of 5 names (they can be made up). Then:
  1. Print the first name
  2. Print the last name
  3. Replace the third name with a different name
  4. Print the whole list
Checkpoint: Your printed list should show the updated third name.
Hint
The third item in a list is index 2. Use names[2] = "NewName".
Solution
names = ["Ava", "Noah", "Zoe", "Liam", "Mia"]

print(names[0])
print(names[-1])

names[2] = "Kai"
print(names)
Task 2 (stretch): Total the numbers
Create a list of numbers. Use a for loop to add them up and print the total.
Checkpoint: Your total should match what you get if you add them on a calculator.
Hint
Start with total = 0. Then loop through the list and add each number to total.
Solution
numbers = [3, 7, 10, 12]
total = 0

for n in numbers:
    total = total + n

print(total)
9) Dictionaries & sets: labelled data and unique collections
Lists are great when order matters. But sometimes you want:
labelled data (like a student profile) or unique values (no duplicates).
That’s where dictionaries and sets shine.
✅ Success looks like
  • You can create a dictionary and use keys to access values.
  • You can add/update dictionary entries.
  • You can loop through a dictionary.
  • You can use a set to remove duplicates and check “is it already there?”
📌 Core idea: dictionary = labelled values, set = unique values
Dictionary
A dictionary stores key → value pairs. Keys are like labels.
student = {
    "name": "Ava",
    "year": 9,
    "age": 14
}
Set
A set stores unique values only. Duplicates are automatically removed.
names = {"Ava", "Noah", "Zoe"}
Quick test:
If you need a label (like "score" or "age") → dictionary.
If you need no duplicates (unique values) → set.
🧠 Dictionaries: key → value pairs
Create and access dictionary values
profile = {
    "name": "Ava",
    "year": 9,
    "favourite_subject": "Science"
}

print(profile["name"])
print(profile["year"])
print(profile["favourite_subject"])
Key idea: You use the key (label) inside square brackets to get the value.
Add a new key
profile["school"] = "Example High"
print(profile)
Update an existing value
profile["year"] = 10
print(profile)
Looping through a dictionary
scores = {
    "Ava": 85,
    "Noah": 72,
    "Zoe": 90
}

for name, score in scores.items():
    print(name, score)
items() gives you both the key and the value each time through the loop.
🧩 Sets: unique values + fast “already used?” checks
Removing duplicates using a set
names = ["Ava", "Noah", "Ava", "Zoe", "Noah"]
unique_names = set(names)

print(unique_names)
A set automatically keeps only one copy of each value.
Important: Sets do not keep order. If you need order, use a list.
Creating a set
colours = {"red", "blue", "green"}
print(colours)
Adding to a set
colours.add("yellow")
print(colours)
Membership checking with in
used_names = {"Ava", "Noah", "Zoe"}
name = input("Enter a name: ")

if name in used_names:
    print("Already used")
else:
    print("Available")
Sets are excellent for “have we seen this before?” programs.
⚠️ Common mistakes (and fixes)
Mistake 1: Treating a dictionary like a list
Dictionaries use keys, not numbered positions.
profile = {"name": "Ava", "year": 9}

# ❌ Wrong idea:
# print(profile[0])

# ✅ Correct:
print(profile["name"])
Mistake 2: Key not found
If the key doesn’t exist, Python throws an error. For beginners, the fix is usually: make sure the spelling matches.
scores = {"Ava": 85}

name = input("Enter name exactly: ")
print(scores[name])
Mistake 3: Expecting sets to keep order
A set is for uniqueness, not order. Printing a set may look “scrambled”.
numbers = [3, 1, 3, 2]
print(set(numbers))
Mistake 4: Creating an empty set the wrong way
{} creates an empty dictionary, not an empty set.
empty_dict = {}
empty_set = set()

print(type(empty_dict))
print(type(empty_set))
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Build a student dictionary
Create a dictionary called student with keys:
  • "name"
  • "year"
  • "favourite_subject"
Print each value on a new line.
Hint
Access values using student["name"], student["year"], etc.
Solution
student = {
    "name": "Ava",
    "year": 9,
    "favourite_subject": "Science"
}

print(student["name"])
print(student["year"])
print(student["favourite_subject"])
Task 2 (stretch): Duplicate remover
Create a list that contains repeated values (e.g. names or items). Convert it to a set and print the set.
Checkpoint: Your printed set should show each item only once.
Hint
Use set(your_list).
Solution
items = ["pen", "pen", "book", "pen", "ruler"]
unique_items = set(items)

print(unique_items)
10) Functions: reusable blocks of code
As programs get bigger, repeating the same code becomes messy.
Functions let you package instructions into a reusable block with a clear name.
✅ Success looks like
  • You can define a function using def.
  • You can call a function to run it.
  • You understand parameters vs arguments.
  • You know the difference between print and return.
📌 Core idea: name a job once, use it many times

A function is a named set of instructions. Instead of rewriting the same code again and again, you:

  • Write it once
  • Give it a clear name
  • Run it whenever you need it
Think of a function as: a recipe. You don’t rewrite the recipe — you just follow it when needed.
🧱 Defining and calling a function
Define a function
def greet():
    print("Hello!")
Call (run) the function
greet()
greet()
The code inside the function only runs when you call it.
📥 Parameters and arguments
Function with a parameter
def greet(name):
    print("Hello", name)
Calling with an argument
greet("Ava")
greet("Noah")
Parameter = the variable in the function definition.
Argument = the actual value you pass in.
📤 Return vs print
Using print
def add_print(a, b):
    print(a + b)

add_print(3, 4)
This shows the result, but you can’t reuse it later.
Using return
def add_return(a, b):
    return a + b

result = add_return(3, 4)
print(result)
return sends a value back so it can be stored or reused.
⚠️ Common mistakes (and fixes)
Mistake 1: Forgetting to call the function
def greet():
    print("Hello")

# ❌ Nothing happens
Fix: Call it using greet().
Mistake 2: Missing arguments
def greet(name):
    print(name)

# greet()  ❌ error
Fix: Pass a value: greet("Ava").
Mistake 3: Expecting print to return a value
def add(a, b):
    print(a + b)

total = add(2, 3)
print(total)  # prints None
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Greeting function
Write a function called say_hello that takes a name and prints a greeting.
Hint
Use one parameter and print() inside the function.
Solution
def say_hello(name):
    print("Hello", name)

say_hello("Ava")
Task 2 (stretch): Add numbers
Write a function that takes two numbers and returns their total. Print the result.
Hint
Use return, not print, inside the function.
Solution
def add(a, b):
    return a + b

result = add(5, 7)
print(result)
11) Working with files: saving and loading data
So far, your programs forget everything when they stop running. Files let you save data and load it later.
✅ Success looks like
  • You can open a file using with open().
  • You understand read ("r"), write ("w") and append ("a").
  • You can write text to a file.
  • You can read text from a file.
📌 Core idea: programs can store information
A file is just saved text on your computer. Python can open it, read it, change it, and save it again.
✍️ Writing to a file
with open("notes.txt", "w") as file:
    file.write("Hello world\n")
    file.write("This is saved text.")
"w" means write. If the file already exists, it will be replaced.
📖 Reading from a file
with open("notes.txt", "r") as file:
    content = file.read()

print(content)
"r" means read.
⚠️ Common mistakes (and fixes)
Overwriting files accidentally
Using "w" deletes old content. Use "a" to append instead.
File not found error
Make sure the file name matches exactly.
🎮 Try it: mini practice tasks
Task 1: Write a program that saves your name to a file called name.txt.
Task 2: Write a program that reads from name.txt and prints the name.
12) Modules & imports: using built-in tools
Python comes with loads of useful code already written.
Imports let you use those tools instead of reinventing them.
✅ Success looks like
  • You can use import to access a module.
  • You can call functions inside modules (e.g. random.randint).
  • You can use from ... import ... when needed.
  • You can recognise common import mistakes.
📌 Core idea: a module is a toolbox
A module is a collection of useful functions. Importing a module is like opening a toolbox.
🧱 Basic import pattern
Import the module
import random
Use something inside it
number = random.randint(1, 10)
print(number)
You call functions using module_name.function_name().
🎲 Useful modules (starter pack)
random
Random numbers and random choices
import random

coin = random.choice(["Heads", "Tails"])
print(coin)
time
Pauses and time delays
import time

print("Get ready...")
time.sleep(2)
print("Go!")
🧠 Another pattern: from ... import ...
Import a specific function
from random import randint

number = randint(1, 10)
print(number)
Note: This can be convenient, but it can also make code harder to read. For beginners, import random is often clearer.
⚠️ Common mistakes (and fixes)
Mistake 1: Naming your file the same as a module
If your file is called random.py, Python might import your file instead of the real module.
Fix: Rename your file to something else (e.g. dice_game.py).
Mistake 2: Forgetting parentheses
randint is a function — it needs brackets to run.
# ❌ Wrong:
# number = random.randint

# ✅ Correct:
number = random.randint(1, 10)
Mistake 3: Importing but not using it
Imports should be at the top and used in your program. If you never use it, delete it.
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Dice roll
Import random and simulate a dice roll (number 1 to 6). Print the result.
Hint
Use random.randint(1, 6).
Solution
import random

roll = random.randint(1, 6)
print("You rolled:", roll)
Task 2 (stretch): Countdown timer
Import time. Create a countdown from 3 to 1, pausing 1 second between each number. Print Go! at the end.
Hint
Use a loop and time.sleep(1).
Solution
import time

for i in range(3, 0, -1):
    print(i)
    time.sleep(1)

print("Go!")
13) Debugging: finding and fixing problems in your code
Debugging is not “being bad at coding”. It’s a normal part of coding.
Your job is to read what Python is telling you, work out what went wrong, and fix it.
✅ Success looks like
  • You can find the line number where the problem happened.
  • You can name the error type (e.g. NameError, TypeError).
  • You can explain what the error means in plain English.
  • You can fix it and test again.
  • You can use print() to inspect variables while debugging.
📌 The 4-step debugging routine
Step 1: Read the LAST line of the error
The last line usually tells you the error type and a message explaining what Python thinks is wrong.
Step 2: Find the line number
Python shows you the line where it noticed the error. That line is where you start looking first.
Step 3: Translate the message into plain English
Example: NameError: name 'scroe' is not defined means you used a variable name that doesn't exist. Often it’s a spelling mistake.
Step 4: Fix ONE thing, test again
Don’t change five things at once. Fix one thing, run it again, and see what happens.
🧾 How to read an error message (traceback)
What a traceback looks like
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(score)
NameError: name 'score' is not defined
Where to look first
  1. The last line (error type + message)
  2. The line number shown above it
  3. Your code on that line
Important detail
Sometimes the error shows up on one line, but the real cause is on a line above it. Example: you forgot a bracket earlier, and Python only “realises” later.
🧪 The #1 debugging tool: print what you THINK is happening
Why print-debugging works
Beginners often have the right idea but the code is doing something different. Printing values helps you see what’s actually happening inside your program.
Example: checking variable values
age_text = input("Enter your age: ")

print("DEBUG: age_text is", age_text)
print("DEBUG: type is", type(age_text))

age = int(age_text)
print("DEBUG: age is", age)
Tip: label your debug prints
If you only print values, you might forget what they mean. Labels make it obvious.
print("DEBUG: total =", total)
🧩 The most common error types (what they mean + how to fix)
SyntaxError: Python can't understand your code
Meaning: You wrote something that is not valid Python grammar. This often happens with missing brackets, missing colons, or mismatched quotes.
What to do first: Look at the line Python highlights, then also look at the line ABOVE it. Syntax mistakes often “break” the next line too.
# Common SyntaxError example:
age = 14
if age > 13
    print("Teen")
Fix: Add the missing colon : after the if.
IndentationError: your blocks don't line up
Meaning: Code inside an if, for, while, or function must be indented consistently. Python uses indentation to know what belongs inside the block.
if True:
print("Hi")
Fix: Indent the line inside the block (usually 4 spaces).
Common cause: Mixing tabs and spaces. Use spaces only.
NameError: you used a name Python doesn't know
Meaning: You used a variable or function name that doesn't exist (usually a spelling mistake, or you forgot to create it first).
score = 10
print(scroe)
Fix: Make the name match exactly (score not scroe).
Debug tip: Copy-paste the variable name from where you created it to where you used it.
TypeError: you used the wrong type of data
Meaning: You tried to do something with a value that isn't the right type. Example: adding a number to a string.
age = input("Age: ")
print(age + 1)
Fix: Convert text to a number first: int(age).
A safe debugging habit
print("DEBUG:", age, type(age))
Always check the value and the type when you're confused.
ValueError: the type is right, but the value is wrong
Meaning: Python tried to convert or use a value, but the value doesn't make sense. Example: trying to turn "hello" into an integer.
text = input("Enter a number: ")
number = int(text)
Fix: Make sure the input really is a number. A simple beginner strategy is to tell the user what to enter and test carefully.
Later on, you can learn error-handling with try and except. For now: focus on reading the error and checking the input.
IndexError: list index out of range
Meaning: You tried to access a position in a list that doesn't exist. If a list has 3 items, valid indexes are 0, 1, 2.
names = ["Ava", "Noah", "Zoe"]
print(names[3])
Fix: Check the list length using len(names) and check your indexes.
Debug tip
print("DEBUG: len(names) =", len(names))
print("DEBUG: names =", names)
KeyError: dictionary key not found
Meaning: You tried to access a dictionary key that isn't in the dictionary. Often it's spelling or capital letters.
scores = {"Ava": 85, "Noah": 72}
print(scores["ava"])
Fix: Keys must match exactly. "Ava" is not the same as "ava".
Debug tip: Print the keys to see what’s actually available:
print(scores.keys())
🧠 Logic bugs: when your code runs but gives the wrong answer
What a logic bug is
Sometimes your code has no errors, but the output is wrong. That means the logic is wrong, not the syntax.
Example: incorrect comparison
age = 14

if age > 14:
    print("You can go")
else:
    print("You cannot go")
If the rule is “14 and above”, the check should be >=.
How to debug a logic bug
  1. Choose one test input (like age = 14).
  2. Predict what should happen before you run it.
  3. Run it and compare the result.
  4. Add debug prints to show the values used in decisions.
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Task 1 (starter): Fix the NameError
The program below crashes. Run it, read the error carefully, and fix it so it works.
score = 10
print(scroe)
Hint
Compare the spelling of the variable on both lines.
Solution
score = 10
print(score)
Task 2 (stretch): Debug a logic bug with prints
The program runs, but the answer is wrong. It is meant to add up 3 numbers and print the total. Use debug prints to work out what is happening and fix it.
a = 5
b = 7
c = 2

total = a + b
total = c

print(total)
Hint
Notice that total is being overwritten. Print total after each line to see when it changes.
Solution
a = 5
b = 7
c = 2

total = a + b + c
print(total)