Python Reference
A practical Python lookup page for syntax, structures, common errors, and worked examples.
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
✅ 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.
- Run code. Change one thing. Run it again.
- Predict what will happen before you run it.
- When stuck: isolate the problem (smallest failing piece).
- 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.
- Your code = instructions
- Output = evidence the instructions happened
- Print statements = your “window” into what’s happening
👀 Examples: print(), comments, and running code
# 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.")
print() produces a new line of output.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}%")
+ and hit type errors. f-strings are the easiest clean option.print("=== Program starting ===")
# Your code goes here...
name = "Ava"
print(f"Loaded name: {name}")
print("=== Program finished ===")
⚠️ Common mistakes (and fixes)
# ❌ Wrong
print(Hello)
# ✅ Right
print("Hello")
# ❌ Might break (curly quotes)
print(“Hello”)
# ✅ Works (straight quotes)
print("Hello")
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
- A title line (your choice)
- Your name (or a nickname)
- One fun fact (school-appropriate)
Hint
print() lines. Text must be inside quotes.Solution
print("=== My Python Intro ===")
print("Name: Sam")
print("Fun fact: I can juggle three objects.")
level(a number)nickname(text)
Hint
print(f"... {variable} ...") Text needs quotes. Numbers do not.
Solution
level = 3
nickname = "CodeNinja"
print(f"Nickname = {nickname}, Level = {level}")
- 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.
🧱 Data types you’ll use constantly
- "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
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}")
age = 15
height = 1.72
name = "Ravi"
is_student = True
print(type(age))
print(type(height))
print(type(name))
print(type(is_student))
<class 'int'>, <class 'float'>, etc.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}")
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
int() only works if the string is a whole number like "42". For decimals like "3.5", use float().⚠️ Common mistakes (and fixes)
apples = "5"
more_apples = "2"
print(apples + more_apples) # prints "52" not 7
apples = int("5")
more_apples = int("2")
print(apples + more_apples) # prints 7
# ❌ Confusing or dangerous
print = 10
type = "hello"
# ✅ Clear
player_score = 10
player_name = "hello"
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)
- Creates a variable called
scorestarting at 0 - Prints the score
- Adds 10 to the score
- Prints the score again
- Adds 3 more
- Prints the final score
Hint
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}")
- One int
- One float
- One string that looks like a number (example: "12")
- One bool
<class 'int'>.Hint
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)}")
- 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.
int() or float() immediately after input() if you plan to do maths.👀 Examples: input(), storing responses, and conversion
name = input("What is your name? ")
print(f"Hello, {name}!")
name, then prints a response.age_text = input("How old are you? ")
print(age_text + 1) # ❌ error (string + number)
age_text is a string.age = int(input("How old are you? "))
print(age + 1) # ✅ works
width = float(input("Enter the width (m): "))
height = float(input("Enter the height (m): "))
area = width * height
print(f"Area = {area} square metres")
⚠️ Common mistakes (and fixes)
number = input("Enter a number: ")
print(number * 2) # prints text twice, not doubled
number = int(input("Enter a number: "))
print(number * 2)
# ❌ Hard to read
name = input("Enter your name")
# ✅ Clear
name = input("Enter your name: ")
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)
- Asks the user for their age
- Converts it to a number
- Prints how old they will be next year
Hint
int() before adding 1.Solution
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}")
Hint
float() instead of int().Solution
width = float(input("Enter width: "))
height = float(input("Enter height: "))
area = width * height
print(f"Area = {area}")
- 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.
+adds numbers+joins strings==compares values=assigns values
➕ Arithmetic operators
- 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
// and % are extremely useful for checking even/odd numbers and splitting things into groups.🔍 Comparison operators
!= 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
= 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
- 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)
Hint
Use the modulo operator%.
Solution
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
Hint
Use a comparison operator inside anif statement.
Solution
score = int(input("Enter score: "))
if score >= 50:
print("Pass")
else:
print("Fail")
- You can write a correct
ifblock 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.
if condition:
# indented block runs only when condition is True
do_something()
- The colon
:at the end of the line - Indentation under the if/elif/else
🧠 How if / elif / else works together
- Python checks the
ifcondition. - If it’s True, Python runs that block and skips the rest.
- If it’s False, Python checks the first
elif. - It keeps checking
elifblocks in order until one is True. - If none are True, Python runs the
elseblock (if there is one).
👀 Examples: simple decisions to multi-branch decisions
temperature = int(input("Temperature (°C): "))
if temperature >= 30:
print("It is hot today.")
else.number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
score = int(input("Score (0-100): "))
if score >= 85:
print("A")
elif score >= 70:
print("B")
elif score >= 50:
print("C")
else:
print("D")
score >= 50 first, it would catch 85 too, and you’d never get an A.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.")
.lower() so "YES", "Yes", "yes" all behave the same.⚠️ Common mistakes (and fixes)
= assigns. == compares. In an if condition, you almost always want ==.# ❌ Wrong
# if score = 50:
# ✅ Right
# if score == 50:
# ❌ Wrong
# if age >= 13
# print("OK")
# ✅ Right
# if age >= 13:
# print("OK")
# ❌ 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)
- Positive if it’s greater than 0
- Zero if it’s exactly 0
- Negative if it’s less than 0
Hint
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")
"platypus"). Ask the user to enter a password.
- If it matches, print Access granted
- Otherwise, print Access denied
Hint
.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")
- You can use a
forloop to repeat a fixed number of times. - You can use a
whileloop 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.
- repeat actions cleanly
- scale your program easily
- change behaviour by updating one line
🔁 for loops: repeating a known number of times
for i in range(5):
print(i)
i is the loop variable : it changes automatically each time.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
count = 0
while count < 5:
print(count)
count = count + 1
while loop must change something that affects its condition.⚠️ Common mistakes (and fixes)
# ❌ Infinite loop
count = 0
while count < 5:
print(count)
for loop: Python already does that.🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
for loop to count down from 10 to 1.Hint
Userange() with a negative step.
Solution
for i in range(10, 0, -1):
print(i)
Hint
Use awhile loop that runs until the guess is correct.
Solution
secret = 7
guess = -1
while guess != secret:
guess = int(input("Guess the number: "))
print("Correct!")
- 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)
🔎 Indexing and slicing strings
word = "python"
print(word[0]) # p
print(word[1]) # y
print(word[-1]) # n (last character)
text = "computer science"
print(text[0:8]) # computer
print(text[9:]) # science
print(text[:8]) # computer
[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']
⚠️ Common mistakes (and fixes)
# ❌ Not allowed
word = "cat"
# word[0] = "b"
word = "cat"
word = "b" + word[1:]
print(word)
answer = input("Yes or no? ")
if answer == "yes":
print("OK")
answer = input("Yes or no? ").strip().lower()
if answer == "yes":
print("OK")
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
Hint
Usestrip() and lower().
Solution
username = input("Enter username: ").strip().lower()
print(username)
Hint
Use indexing with[0] and [-1].
Solution
word = input("Enter a word: ")
print(word[0])
print(word[-1])
- 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.
🧱 Creating lists and accessing items
fruits = ["apple", "banana", "mango"]
numbers = [3, 7, 10, 12]
mixed = ["Ava", 14, True]
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # mango (last item)
🛠️ Changing a list: append, remove, and update
teams = ["red", "blue", "green"]
teams[1] = "yellow"
print(teams) # ['red', 'yellow', 'green']
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
fruits = ["apple", "banana", "mango"]
fruits.remove("banana")
print(fruits)
remove() removes by value. If the value is not in the list, Python gives an error.🔁 Looping through a list
pets = ["dog", "cat", "fish"]
for pet in pets:
print(pet)
pet to each item in the list, one by one.pets = ["dog", "cat", "fish"]
for i in range(len(pets)):
print(i, pets[i])
📦 Tuples: like lists, but fixed
coords = (10, 20)
days = ("Mon", "Tue", "Wed")
⚠️ Common mistakes (and fixes)
names = ["Ava", "Noah", "Zoe"]
# print(names[3]) # ❌ error
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)
- Print the first name
- Print the last name
- Replace the third name with a different name
- Print the whole list
Hint
2. Use names[2] = "NewName".Solution
names = ["Ava", "Noah", "Zoe", "Liam", "Mia"]
print(names[0])
print(names[-1])
names[2] = "Kai"
print(names)
for loop to add them up and print the total.
Hint
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)
labelled data (like a student profile) or unique values (no duplicates).
That’s where dictionaries and sets shine.
- 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
student = {
"name": "Ava",
"year": 9,
"age": 14
}
names = {"Ava", "Noah", "Zoe"}
If you need a label (like "score" or "age") → dictionary.
If you need no duplicates (unique values) → set.
🧠 Dictionaries: key → value pairs
profile = {
"name": "Ava",
"year": 9,
"favourite_subject": "Science"
}
print(profile["name"])
print(profile["year"])
print(profile["favourite_subject"])
profile["school"] = "Example High"
print(profile)
profile["year"] = 10
print(profile)
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
names = ["Ava", "Noah", "Ava", "Zoe", "Noah"]
unique_names = set(names)
print(unique_names)
colours = {"red", "blue", "green"}
print(colours)
colours.add("yellow")
print(colours)
inused_names = {"Ava", "Noah", "Zoe"}
name = input("Enter a name: ")
if name in used_names:
print("Already used")
else:
print("Available")
⚠️ Common mistakes (and fixes)
profile = {"name": "Ava", "year": 9}
# ❌ Wrong idea:
# print(profile[0])
# ✅ Correct:
print(profile["name"])
scores = {"Ava": 85}
name = input("Enter name exactly: ")
print(scores[name])
numbers = [3, 1, 3, 2]
print(set(numbers))
{} 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)
student with keys:
"name""year""favourite_subject"
Hint
student["name"], student["year"], etc.Solution
student = {
"name": "Ava",
"year": 9,
"favourite_subject": "Science"
}
print(student["name"])
print(student["year"])
print(student["favourite_subject"])
Hint
set(your_list).Solution
items = ["pen", "pen", "book", "pen", "ruler"]
unique_items = set(items)
print(unique_items)
Functions let you package instructions into a reusable block with a clear name.
- 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
printandreturn.
📌 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
🧱 Defining and calling a function
def greet():
print("Hello!")
greet()
greet()
📥 Parameters and arguments
def greet(name):
print("Hello", name)
greet("Ava")
greet("Noah")
Argument = the actual value you pass in.
📤 Return vs print
printdef add_print(a, b):
print(a + b)
add_print(3, 4)
returndef 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)
def greet():
print("Hello")
# ❌ Nothing happens
greet().def greet(name):
print(name)
# greet() ❌ error
greet("Ava").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)
say_hello that takes a name and prints a greeting.Hint
print() inside the function.Solution
def say_hello(name):
print("Hello", name)
say_hello("Ava")
Hint
return, not print, inside the function.Solution
def add(a, b):
return a + b
result = add(5, 7)
print(result)
- 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
✍️ Writing to a file
with open("notes.txt", "w") as file:
file.write("Hello world\n")
file.write("This is saved text.")
📖 Reading from a file
with open("notes.txt", "r") as file:
content = file.read()
print(content)
⚠️ Common mistakes (and fixes)
Using
"w" deletes old content. Use "a" to append instead.Make sure the file name matches exactly.
🎮 Try it: mini practice tasks
name.txt.name.txt and prints the name.Imports let you use those tools instead of reinventing them.
- You can use
importto 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
🧱 Basic import pattern
import random
number = random.randint(1, 10)
print(number)
module_name.function_name().🎲 Useful modules (starter pack)
import random
coin = random.choice(["Heads", "Tails"])
print(coin)
import time
print("Get ready...")
time.sleep(2)
print("Go!")
🧠 Another pattern: from ... import ...
from random import randint
number = randint(1, 10)
print(number)
import random is often clearer.⚠️ Common mistakes (and fixes)
random.py, Python might import your file instead of the real module.dice_game.py).randint is a function — it needs brackets to run.# ❌ Wrong:
# number = random.randint
# ✅ Correct:
number = random.randint(1, 10)
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
random and simulate a dice roll (number 1 to 6). Print the result.Hint
random.randint(1, 6).Solution
import random
roll = random.randint(1, 6)
print("You rolled:", roll)
time. Create a countdown from 3 to 1, pausing 1 second between each number. Print Go! at the end.Hint
time.sleep(1).Solution
import time
for i in range(3, 0, -1):
print(i)
time.sleep(1)
print("Go!")
Your job is to read what Python is telling you, work out what went wrong, and fix it.
- 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
NameError: name 'scroe' is not defined means you used a variable name that doesn't exist. Often it’s a spelling mistake.🧾 How to read an error message (traceback)
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(score)
NameError: name 'score' is not defined
- The last line (error type + message)
- The line number shown above it
- Your code on that line
🧪 The #1 debugging tool: print what you THINK is happening
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)
print("DEBUG: total =", total)
🧩 The most common error types (what they mean + how to fix)
SyntaxError: Python can't understand your code
# Common SyntaxError example:
age = 14
if age > 13
print("Teen")
: after the if.IndentationError: your blocks don't line up
if, for, while, or function must be indented consistently. Python uses indentation to know what belongs inside the block.if True:
print("Hi")
NameError: you used a name Python doesn't know
score = 10
print(scroe)
score not scroe).TypeError: you used the wrong type of data
age = input("Age: ")
print(age + 1)
int(age).print("DEBUG:", age, type(age))
ValueError: the type is right, but the value is wrong
"hello" into an integer.text = input("Enter a number: ")
number = int(text)
try and except. For now: focus on reading the error and checking the input.IndexError: list index out of range
names = ["Ava", "Noah", "Zoe"]
print(names[3])
len(names) and check your indexes.print("DEBUG: len(names) =", len(names))
print("DEBUG: names =", names)
KeyError: dictionary key not found
scores = {"Ava": 85, "Noah": 72}
print(scores["ava"])
print(scores.keys())
🧠 Logic bugs: when your code runs but gives the wrong answer
age = 14
if age > 14:
print("You can go")
else:
print("You cannot go")
>=.- Choose one test input (like
age = 14). - Predict what should happen before you run it.
- Run it and compare the result.
- Add debug prints to show the values used in decisions.
🎮 Try it: mini practice tasks (2 tasks • hints + solutions inside)
score = 10
print(scroe)
Hint
Solution
score = 10
print(score)
a = 5
b = 7
c = 2
total = a + b
total = c
print(total)
Hint
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)