🐍 Python Coach
CHEAT SHEET

🐍 Python Coach - Python Cheat Sheet

Full lesson content for AQA, OCR, and Edexcel specifications

💡 How to use this document:
• Press Ctrl+F (or Cmd+F) to search for any topic or keyword
• Use the floating menu (bottom-right ☰) to jump between lessons
• Keep this tab open alongside your challenges for quick reference

📚 Quick Navigation

Lesson 1

Print Statements

AQA OCR Edexcel

Why Print Statements?

Print statements let you display messages on the screen - like sending a message to the user. Every program needs to communicate with its users!

What is print()?

The print() function displays text on the screen. Think of it like a loudspeaker for your code.

How to use print():

  • Write print()
  • Put your message inside the parentheses
  • Wrap text in quotes: "like this" or 'like this'

Example 1: Hello World

The simplest program! Print displays text on screen.

print("Hello, World!")

Example 2: Multiple Messages

Each print() creates a new line of output.

Example 3: Numbers Don't Need Quotes

Text needs quotes, but numbers work without them!

print(42) print(2025) print(100)

Example 4: Real Use

Real programs use print() to give users feedback.

print("Welcome to my game!") print("Loading...") print("Ready to play!")

Common Mistakes

Wrong Right Explanation
print(Hello) print("Hello") Forgot quotes around text - text always needs quotes!
print("Hello] print("Hello") Mismatched quotes - both must match
Print('Hi') print('Hi') Python is case-sensitive - must be lowercase 'print'
print("42") print(42) Numbers don't need quotes - quotes make it text!

✅ You're Ready!

  • Write a print() statement with text in quotes
  • Know that text needs quotes, but numbers don't
  • Print multiple lines using print() multiple times
  • Understand print() displays information to users
Lesson 2

Comments

AQA OCR Edexcel

Why Comments?

Comments let you add notes in your code that Python ignores - like sticky notes for programmers! Professional programmers use comments to explain what their code does.

What are Comments?

Comments are notes in your code that Python completely ignores. They help you (and others) understand what the code does.

How to write comments:

  • Start with the # symbol
  • Write your note after the #
  • Python ignores everything after # on that line

Example 1: Your First Comment

Comments are written with # and Python ignores them completely.

# This is a comment print("Hello, World!")

Example 2: Explaining Code

Use comments to explain what your code does - helpful when you come back later!

# Print a welcome message print("Welcome to Python!") # Print the year print(2025)

Example 3: Comments with Variables

Comments help document what variables store - very useful in longer programs.

# Store the user's name name = "Alex" # Store the user's age age = 15 # Display the information print(name) print(age)

Common Mistakes

Wrong Right Explanation
This is a comment # This is a comment Forgot the # symbol - without it, Python tries to run it as code and gives an error!
print("Hello") This is wrong print("Hello") # This is right Comments on the same line need # before them
/* This style doesn't work */ # This style works in Python Python uses # for comments, not /* */ like some other languages

✅ You're Ready!

  • Write comments using the # symbol
  • Add explanatory notes to your code
  • Know that Python ignores everything after #
  • Use comments to document what variables store
Lesson 3

Variables

AQA OCR Edexcel

Why Variables?

Variables are like labeled boxes that store information - you can put things in them, take things out, and use them later! They're the most fundamental building block of programming.

What are Variables?

A variable is a named storage location. Think of it like a labeled box where you store information.

How to create a variable:

  • Choose a name (like name or age)
  • Use an equals sign =
  • Put the value: name = "Alex"
  • The = means "store this value" - it's called assignment

Example 1: Storing Your Name

Store your name in a variable and print it.

name = "Alex" print(name)

Example 2: Numbers Work Too!

Variables can store numbers (no quotes needed for numbers).

age = 12 print(age)

Example 3: Changing Values

You can change what's stored in a variable anytime!

score = 0 print(score) score = 100 print(score)

Common Mistakes

Wrong Right Explanation
name = Alex name = "Alex" Forgot quotes around text - text needs quotes!
print("name") print(name) Quotes make it literal text, not the variable's value
my name = 'Jo' my_name = 'Jo' Variable names can't have spaces - use underscore _
123abc = 'test' abc123 = 'test' Variable names can't start with numbers

✅ You're Ready!

  • Create a variable using = to assign a value
  • Know that text needs quotes, but numbers don't
  • Print a variable to see what's stored in it
  • Understand variables are like labeled storage boxes
Lesson 4

Data Types & Type Conversion

AQA OCR Edexcel

Why Data Types?

Python treats numbers, text, and true/false values differently - understanding types prevents errors! Knowing data types is essential for working with user input and calculations.

What are Data Types?

Every value in Python has a type that determines what you can do with it. There are 4 main types you need to know:

The 4 Main Types:

  • int - Whole numbers like 42, -17, 0
  • float - Decimal numbers like 3.14, -2.5, 0.0
  • str - Text in quotes like "Hello", '123'
  • bool - True or False (no quotes!)

Check types: Use type(value) to see what type something is!

Example 1: Checking Types

Use type() to check what type a value is - this is super useful for debugging!

print(type(42)) # int (whole number) print(type(3.14)) # float (decimal) print(type("Hello")) # str (text) print(type(True)) # bool (True/False)

Example 2: Converting with int()

input() always gives you a string - use int() to convert to a number for math!

age = input("Enter age: ") # User types: 15 print(type(age)) # str (it's text!) age = int(age) # Convert to number print(type(age)) # int (now it's a number!) print(age + 5) # Now we can do math!

Example 3: Converting to float()

Use float() when you need decimal numbers for precise calculations.

price = "19.99" # Text from user print(type(price)) # str price = float(price) # Convert to decimal print(type(price)) # float total = price * 2 # Calculate print(total) # 39.98

Example 4: Converting to str()

Use str() to convert numbers to text so you can combine them with + for display.

score = 100 lives = 3 # Can't do: "Score: " + score (error!) # Must convert number to text first: message = "Score: " + str(score) + ", Lives: " + str(lives) print(message)

Common Mistakes

Wrong Right Explanation
age = input("Age? ")
print(age + 5)
age = int(input("Age? "))
print(age + 5)
input() gives text! Must convert with int() before doing math
print("Score: " + 100) print("Score: " + str(100)) Can't combine text and numbers with + - use str() to convert the number first
number = int("3.14") number = float("3.14") int() can't convert decimals! Use float() for numbers with decimal points

✅ You're Ready!

  • Know the 4 main types: int, float, str, bool
  • Use type() to check what type a value is
  • Convert input() to numbers with int() or float()
  • Convert numbers to text with str() for combining
Lesson 5

Arithmetic Operators

AQA OCR Edexcel

Why Arithmetic Operators?

Python can do all the math you need - from simple addition to powerful calculations! Understanding operators is essential for games, calculators, and data analysis.

What are Arithmetic Operators?

Operators are symbols that perform calculations on numbers. Python has 7 main arithmetic operators:

The 7 Operators:

  • + Addition (10 + 5 = 15)
  • - Subtraction (10 - 5 = 5)
  • * Multiplication (10 * 5 = 50)
  • / Division (10 / 5 = 2.0) - Always returns a float
  • // Floor Division (10 // 3 = 3) - Returns whole number
  • % Modulus (10 % 3 = 1) - Returns remainder
  • ** Exponent (2 ** 3 = 8) - Power of

Operator Precedence (BIDMAS/PEMDAS)

Order matters! Python follows BIDMAS/PEMDAS rules:

  • Brackets / Parentheses ()
  • Indices / Exponents **
  • Division /, Multiplication *, Modulus %, Floor Division // (left to right)
  • Addition +, Subtraction - (left to right)

Example 1: Basic Math

x = 10 y = 3 print("Addition:", x + y) # 13 print("Subtraction:", x - y) # 7 print("Multiplication:", x * y) # 30

Example 2: Division Types

Notice the difference between / and // (Floor Division).

print(10 / 3) # 3.3333333333333335 (Float/Decimal) print(10 // 3) # 3 (Integer/Whole Number) print(10 % 3) # 1 (Remainder/Modulus)

Example 3: Order of Operations

Multiplication happens before addition (PEMDAS/BIDMAS). Use parentheses () to force a different order.

# Default order: 3 * 4 = 12, then 2 + 12 = 14 print(2 + 3 * 4) # = 14 # Use parentheses to force order: (2 + 3) = 5, then 5 * 4 = 20 print((2 + 3) * 4) # = 20

Common Mistakes

Wrong Right Explanation
print(10 / 2) expecting 5 print(10 // 2) gets 5 / always gives decimals (5.0). Use // for whole numbers (5)
print(5^2) print(5**2) Python uses ** for exponent, not ^

✅ You're Ready!

  • Use all 7 arithmetic operators (+, -, *, /, //, %, **)
  • Understand operator precedence (BIDMAS/PEMDAS)
  • Use parentheses () to force calculation order
Lesson 6

Input Function

AQA OCR Edexcel

Why User Input?

User input makes programs interactive - it's like having a conversation with your code! Every game, app, and website needs to get information from users.

What is input()?

The input() function asks the user a question and waits for their answer. You must store the answer in a variable to use it later.

How to use input():

  • Write input() with your question in quotes
  • Store the answer in a variable
  • Example: name = input("What's your name? ")
  • IMPORTANT: input() always gives you text (a string), even if the user types a number!

Example 1: Basic Input

Ask a question and store the answer in a variable.

name = input("What is your name? ") print(name)

Example 2: Personalized Greeting

Use + to combine the user's input with your message.

name = input("What is your name? ") print("Hello " + name + "!")

Example 3: Multiple Inputs

You can ask multiple questions and use all the answers!

first = input("First name? ") last = input("Last name? ") print("Hello " + first + " " + last)

Example 4: Input with Numbers

Remember: input() gives you text! Convert to numbers with int() or float().

age = input("How old are you? ") # Gets "15" as text age = int(age) # Convert to number print("Next year you'll be " + str(age + 1))

Common Mistakes

Wrong Right Explanation
input("What's your name?") name = input("What's your name?") Must store the answer in a variable!
age = input("Age? ")
print(age + 5)
age = int(input("Age? "))
print(age + 5)
input() gives text! Use int() to convert for math
print("Hello " + input()) name = input("Name? ")
print("Hello " + name)
Store input in a variable first for clearer code

✅ You're Ready!

  • Use input() to ask the user a question
  • Store the user's answer in a variable
  • Remember input() always gives text (strings)
  • Convert to numbers with int() or float() for math
Lesson 7

String Concatenation

AQA OCR Edexcel

Why String Concatenation?

String concatenation lets you join pieces of text together - like building sentences from smaller parts! It's how programs create personalized messages.

What is String Concatenation?

Concatenation means joining strings together. Think of it like linking train carriages - you connect them end-to-end!

How to use the + operator:

  • Put the + symbol between strings
  • Python joins them automatically
  • Example: "Hello" + "World" gives you "HelloWorld"
  • Add spaces: "Hello " + "World" gives you "Hello World"

Example 1: Basic Joining

The + operator joins two strings into one.

print("Hello" + "World")

Output: HelloWorld

Example 2: Adding Spaces

Don't forget spaces! "Hello " + "World" is different from "Hello" + "World"

print("Hello " + "World") print("Python " + "is " + "awesome!")

Output:
Hello World
Python is awesome!

Example 3: Variables with Concatenation

You can join variables and strings together.

first_name = "Alex" last_name = "Smith" print(first_name + " " + last_name)

Output: Alex Smith

Example 4: Building Messages

Real programs use concatenation to create personalized output.

user = "Sam" game = "Python Quest" print("Player: " + user) print("Now playing: " + game)

Output:
Player: Sam
Now playing: Python Quest

Common Mistakes

Wrong Right Explanation
print("Score: " + 100) print("Score: " + str(100)) Can't join strings and numbers! Use str() to convert
print("Hello"+"World") print("Hello " + "World") Forgot space between words! Add " " or space in string
name = "Jo"
print("Hello name")
name = "Jo"
print("Hello " + name)
Quotes make it literal text! Use + to add the variable

✅ You're Ready!

  • Use + to join two strings together
  • Combine variables with strings using +
  • Remember to add spaces where needed
  • Convert numbers to strings with str() before joining
Lesson 8

String Methods

AQA OCR Edexcel

Why String Methods?

String methods are like tools that let you transform and manipulate text - make it LOUD, quiet, or measure it! They're essential for processing user input and formatting text.

What are String Methods?

Methods are special functions that belong to strings. You call them by putting a dot after a string.

Useful String Methods:

  • .upper() - Converts all letters to UPPERCASE
  • .lower() - Converts all letters to lowercase
  • len() - Counts characters (length) - NOTE: This one doesn't use a dot!
  • .strip() - Removes spaces from start and end

Example 1: Making Text LOUD

The .upper() method converts all letters to uppercase.

text = "hello" print(text.upper())

Output: HELLO

Example 2: Making Text Quiet

The .lower() method converts all letters to lowercase.

text = "PYTHON" print(text.lower())

Output: python

Example 3: Counting Characters

len() tells you how many characters are in a string (including spaces!).

message = "Hello World" length = len(message) print(length)

Output: 11

Example 4: Real-World Use

Methods are perfect for cleaning up user input and making comparisons case-insensitive.

answer = input("Do you agree? (yes/no) ") answer = answer.lower().strip() # Clean and lowercase if answer == "yes": print("Great!") else: print("No problem")

Common Mistakes

Wrong Right Explanation
text.upper text.upper() Forgot the parentheses! Methods need () to work
text = "hi"
text.upper()
print(text)
text = "hi"
text = text.upper()
print(text)
Methods don't change the original! Store the result
text.len() len(text) len() is not a method! It goes before the string

✅ You're Ready!

  • Use .upper() and .lower() to change case
  • Use len() to count characters
  • Understand methods come after strings with a dot: string.method()
  • Remember to store the result or print it directly
Lesson 9

String Slicing & Advanced Methods

AQA OCR Edexcel

Why String Slicing?

Strings are like lists of characters you can slice, dice, and manipulate! This is essential for processing data, extracting information, and text manipulation.

What is String Slicing?

Every character in a string has a position (index). Python counts from 0!

Key Techniques:

  • text[0] - Get single character (index 0 = first character)
  • text[0:5] - Slice (characters from index 0 up to, but NOT including, index 5)
  • text[-1] - Last character (negative indexing counts from end)
  • .split() - Split string into a list at spaces
  • .replace() - Replace text with new text

Example 1: Accessing Characters by Index

Use square brackets [] with an index number to get a specific character.

word = "Python" print(word[0]) # First character print(word[-1]) # Last character

Output:
P
n

Example 2: Slicing Strings

Use [start:stop] to get a section. The stop position is NOT included!

text = "Hello World" print(text[0:5]) # Characters 0,1,2,3,4 print(text[6:]) # From index 6 to end

Output:
Hello
World

Example 3: Splitting Strings into Lists

Use .split() to break text into separate words (creates a list).

sentence = "Hello my name is Alex" words = sentence.split() print(words) print(words[0]) # Access first word

Output:
['Hello', 'my', 'name', 'is', 'Alex']
Hello

Example 4: Replacing Text

Use .replace(old, new) to swap text.

message = "Hello World" new_message = message.replace("World", "Python") print(new_message)

Output: Hello Python

Example 5: Combining Techniques

Real programs combine multiple string operations.

email = " [email protected] " email = email.strip().lower() parts = email.split("@") print("Username:", parts[0]) print("Domain:", parts[1])

Output:
Username: user
Domain: example.com

Common Mistakes

Wrong Right Explanation
word = "Hi"
print(word[2])
word = "Hi"
print(word[1])
Index out of range! "Hi" has indices 0 and 1 only
text[0:5] includes index 5 text[0:5] goes up to but NOT including index 5 Stop index is exclusive - not included in result
words = text.split
print(words)
words = text.split()
print(words)
Forgot parentheses! Methods need () to execute

✅ You're Ready!

  • Access characters with [index] (starts at 0)
  • Slice strings with [start:stop]
  • Use .split() to break strings into lists
  • Use .replace(old, new) to swap text
  • Combine methods for powerful text processing
Lesson 10

If Statements

AQA OCR Edexcel

Why If Statements?

If statements let your program make decisions - like choosing different paths based on conditions! This is how programs become intelligent and responsive.

What are If Statements?

If statements check whether something is true or false, then execute code accordingly.

Basic Structure:

  • if condition: - Check if condition is true
  • Don't forget the colon (:)
  • Indent the code inside (4 spaces or Tab)
  • Use comparison operators: >, <, == (equals), != (not equals), >=, <=

Example 1: Simple If Statement

Check a condition and run code only if it's true.

age = 16 if age >= 13: print("You can create a social media account")

Output: You can create a social media account

Example 2: Comparison Operators

Different ways to compare values.

score = 85 if score == 100: print("Perfect score!") if score >= 75: print("Great job!") if score != 0: print("You scored some points")

Output:
Great job!
You scored some points

Example 3: If-Else (Two Paths)

Use else to handle when the condition is false.

score = 45 if score >= 50: print("You passed!") else: print("Keep trying!")

Output: Keep trying!

Example 4: If-Elif-Else (Multiple Paths)

Use elif to check multiple conditions in order. Python stops at the first true condition!

temperature = 25 if temperature > 30: print("Hot day!") elif temperature > 20: print("Nice weather") else: print("Bit chilly")

Output: Nice weather

Example 5: Compound Conditions with 'and'

Use and when BOTH conditions must be true. Use or when at least ONE must be true.

age = 15 has_ticket = True if age > 12 and has_ticket == True: print("You can watch the movie") if age < 12 or has_ticket == False: print("Entry not allowed") else: print("Enjoy the show!")

Output:
You can watch the movie
Enjoy the show!

Common Mistakes

Wrong Right Explanation
if age > 12
print("Old enough")
if age > 12:
print("Old enough")
Forgot colon (:) and indentation!
if age = 18: if age == 18: Use == for comparison, = is for assignment!
if age > 12 and < 18: if age > 12 and age < 18: Must repeat the variable in compound conditions
if age >= 18:
print("Adult")
print("More")
if age >= 18:
print("Adult")
print("More")
All code in the if block must be indented the same amount

✅ You're Ready!

  • Use if, elif, and else for decision making
  • Use comparison operators: ==, !=, >, <, >=, <=
  • Combine conditions with and / or
  • Remember the colon (:) and indentation (4 spaces)
  • Use == for comparison (not = which is for assignment)
Lesson 11

Elif and Else

AQA OCR Edexcel

Why Elif and Else?

Programs often need to choose between MORE than two options - like grades A, B, C, D, or F! Elif and else let you handle multiple paths elegantly.

What are Elif and Else?

Elif (short for "else if") lets you check multiple conditions in sequence. Python checks them in order and stops at the first true one.

The Three-Part Structure:

  • if - First condition to check
  • elif - Additional conditions (can have multiple!)
  • else - Fallback when nothing else is true

Example 1: Grade Calculator

Check conditions in order - Python stops at the first match!

score = 75 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")

Output: Grade: C

Example 2: Age Categories

Handle multiple age ranges with elif.

age = 15 if age < 13: print("Child") elif age < 18: print("Teenager") elif age < 65: print("Adult") else: print("Senior")

Output: Teenager

Example 3: Menu Selection

Real programs use elif for menu choices.

choice = input("Choose: 1=Start, 2=Load, 3=Quit: ") if choice == "1": print("Starting new game...") elif choice == "2": print("Loading saved game...") elif choice == "3": print("Goodbye!") else: print("Invalid choice!")

Common Mistakes

Wrong Right Explanation
if score >= 70:
if score >= 60:
if score >= 70:
elif score >= 60:
Use elif, not multiple ifs! Multiple ifs check ALL conditions
if age > 18:
else age > 13:
if age > 18:
elif age > 13:
else doesn't take a condition! Use elif for more conditions
elif score >= 90:
if score >= 80:
if score >= 90:
elif score >= 80:
Must start with if! Can't begin with elif

✅ You're Ready!

  • Use if for the first condition
  • Use elif for additional conditions
  • Use else as the final fallback
  • Understand Python stops at the first true condition
Lesson 12

Boolean Logic

AQA OCR Edexcel

Why Boolean Logic?

Real programs need to check multiple conditions at once - like "if age > 18 AND has_license"! Boolean logic powers every decision in games, apps, and websites.

What is Boolean Logic?

Boolean logic lets you combine multiple True/False conditions using three special operators:

The Three Operators:

  • and - True only if BOTH sides are True
  • or - True if AT LEAST ONE side is True
  • not - Reverses the value (True becomes False, False becomes True)

Example 1: Using 'and' - Both Must Be True

Both conditions must be True for the code to run.

age = 20 has_license = True # Both conditions must be True if age >= 18 and has_license: print("You can drive!") else: print("Cannot drive yet")

Output: You can drive!

Example 2: Using 'or' - At Least One Must Be True

Only ONE condition needs to be True for the code to run.

is_weekend = True is_holiday = False # Only ONE needs to be True if is_weekend or is_holiday: print("Sleep in!") else: print("Set alarm for 7am")

Output: Sleep in!

Example 3: Using 'not' - Reversing a Condition

The not operator flips True to False and False to True.

is_raining = False if not is_raining: print("Go outside!") else: print("Stay indoors")

Output: Go outside!

Example 4: Combining Operators

You can combine and, or, and not in complex conditions.

age = 16 has_permission = True is_banned = False if age >= 13 and has_permission and not is_banned: print("Access granted") else: print("Access denied")

Output: Access granted

Common Mistakes

Wrong Right Explanation
if age > 18 && has_license: if age > 18 and has_license: Python uses 'and', not && like other languages
if age > 18 || age < 65: if age > 18 or age < 65: Python uses 'or', not || like other languages
if age > 18 and < 65: if age > 18 and age < 65: Must repeat the variable in each condition

✅ You're Ready!

  • Use 'and' when BOTH conditions must be True
  • Use 'or' when AT LEAST ONE condition must be True
  • Use 'not' to reverse/flip a condition
  • Combine operators for complex logic
Lesson 13

For Loops

AQA OCR Edexcel

Why For Loops?

For loops let you repeat code a specific number of times - perfect for counting, processing lists, or repeating tasks! When you know HOW MANY times to repeat, use a for loop!

What are For Loops?

For loops repeat code for each item in a sequence.

Key Concepts:

  • for i in range(5): - Repeat 5 times (counts 0, 1, 2, 3, 4)
  • for item in list: - Repeat once for every item in a list
  • Don't forget the colon (:) and indentation
  • range(n) starts at 0 and goes up to n-1

Example 1: Using range()

The simplest for loop - i will be 0, 1, 2, 3, 4 automatically!

for i in range(5): print(i)

Output:
0
1
2
3
4

Example 2: Repeating Actions

Use for loops to repeat the same action multiple times.

for i in range(3): print("Hello!")

Output:
Hello!
Hello!
Hello!

Example 3: Custom Starting Number

Use range(start, stop) to count from a specific number.

# Count from 1 to 5 for i in range(1, 6): print("Count: " + str(i))

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Example 4: Looping Through a List

For loops can iterate through every item in a list.

names = ['Alex', 'Sam', 'Jo'] for name in names: print("Hello, " + name)

Output:
Hello, Alex
Hello, Sam
Hello, Jo

Example 5: Calculating a Total

Use for loops to process data and accumulate results.

scores = [85, 92, 78, 95] total = 0 for score in scores: total = total + score print("Total:", total) print("Average:", total / len(scores))

Output:
Total: 350
Average: 87.5

Common Mistakes

Wrong Right Explanation
for i in range(5)
print(i)
for i in range(5):
print(i)
Forgot colon (:) and indentation!
for i in range(1, 5):
# Expecting 1,2,3,4,5
for i in range(1, 6):
# Gets 1,2,3,4,5
range() stops BEFORE the end number (5 is not included!)
for i in range(5):
total = 0
total = total + i
total = 0
for i in range(5):
total = total + i
Initialize variables BEFORE the loop, not inside!

✅ You're Ready!

  • Use for loops to repeat code a specific number of times
  • Use range(n) to loop n times (0 to n-1)
  • Loop through lists using 'for item in list'
  • Remember: range(1, 5) goes 1, 2, 3, 4 (NOT 5!)
Lesson 14

While Loops

AQA OCR Edexcel

Why While Loops?

While loops let your code repeat actions automatically - like counting, checking, or waiting until something happens! Use while loops when you DON'T know exactly how many times to repeat.

What are While Loops?

While loops repeat code over and over as long as a condition is true. Think of them like saying "keep doing this WHILE something is true."

Key Points:

  • You must change the condition inside the loop, or you'll get an infinite loop!
  • Structure: while condition:
  • Use comparison operators: <, >, ==, !=, <=, >=

Example 1: Counting Up

A simple while loop that counts from 1 to 5.

count = 1 while count <= 5: print(count) count = count + 1

Output:
1
2
3
4
5

Example 2: Simple Countdown

Count down from 5 to 1, then blast off!

countdown = 5 while countdown > 0: print(countdown) countdown = countdown - 1 print("Blast off!")

Output:
5
4
3
2
1
Blast off!

Example 3: Loop Until User Says Stop

Keep asking the user until they type "stop".

answer = "" while answer != "stop": answer = input("Type 'stop' to exit: ") print("Loop finished!")

Output (if user enters 'go' then 'stop'):
Type 'stop' to exit: go
Type 'stop' to exit: stop
Loop finished!

Example 4: Number Guessing Game

Loop until the user guesses correctly.

secret = 7 guess = 0 while guess != secret: guess = int(input("Guess the number (1-10): ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") print("Correct!")

Common Mistakes

Wrong Right Explanation
count = 1
while count <= 5:
print(count)
count = 1
while count <= 5:
print(count)
count = count + 1
Forgot to update the variable! Creates infinite loop
while count = 5: while count == 5: Use == for comparison, not = (which is assignment)
while True:
print("Hi")
while True:
answer = input()
if answer == "stop":
break
Infinite loop! Need a way to exit (use break or change condition)

✅ You're Ready!

  • Use while loops to repeat code while a condition is true
  • Always update the counter/variable inside the loop
  • Use comparison operators: <, >, ==, !=, <=, >=
  • Avoid infinite loops by changing the condition
Lesson 15

Lists

AQA OCR Edexcel

Why Lists?

Lists let you store multiple values in one variable - like a shopping list, a to-do list, or a collection of scores! Instead of making 10 variables, make 1 list!

What are Lists?

Lists are containers that hold multiple values in order. Each item has a position (index).

Key Concepts:

  • Use square brackets [ ] to create them
  • Values inside are separated by commas
  • Python starts counting at 0, not 1!
  • Use len() to count items
  • Use .append() to add items to the end

Example 1: Creating Lists

Create a list with square brackets and commas between items.

names = ['Alex', 'Sam', 'Jo'] scores = [85, 92, 78, 95] mixed = ['Python', 3, True, 3.14] print(names) print(scores)

Output:
['Alex', 'Sam', 'Jo']
[85, 92, 78, 95]

Example 2: Accessing Items by Index

IMPORTANT: Python starts counting at 0, not 1!

names = ['Alex', 'Sam', 'Jo'] first = names[0] # First item (index 0) second = names[1] # Second item (index 1) last = names[-1] # Last item (negative index) print(first) print(second) print(last)

Output:
Alex
Sam
Jo

Example 3: Counting Items with len()

Use len() to find out how many items are in a list.

names = ['Alex', 'Sam', 'Jo', 'Taylor'] count = len(names) print("Total names:", count)

Output: Total names: 4

Example 4: Adding Items with .append()

Use .append() to add items to the end of a list.

tasks = ['homework', 'practice'] tasks.append('read') print('Total tasks:', len(tasks)) print('First task:', tasks[0]) print(tasks)

Output:
Total tasks: 3
First task: homework
['homework', 'practice', 'read']

Example 5: Looping Through Lists

Combine lists with for loops to process every item.

scores = [85, 92, 78, 95] for score in scores: print("Score:", score)

Output:
Score: 85
Score: 92
Score: 78
Score: 95

Common Mistakes

Wrong Right Explanation
names = ['Alex', 'Sam', 'Jo']
print(names[3])
names = ['Alex', 'Sam', 'Jo']
print(names[2])
Index out of range! List has indices 0, 1, 2 only
names = ['Alex', 'Sam']
print(names[1])
# Expecting 'Alex'
names = ['Alex', 'Sam']
print(names[0])
# Gets 'Alex'
Lists start at index 0, not 1!
scores.append(85, 92) scores.append(85)
scores.append(92)
.append() adds ONE item at a time

✅ You're Ready!

  • Create lists using square brackets [ ]
  • Access items using [0] for first, [1] for second, etc.
  • Use len() to count items
  • Use .append() to add items to the end
  • Remember: Python counts from 0!
Lesson 16

2D Lists

AQA OCR Edexcel

Why 2D Lists?

Games, spreadsheets, and maps all use grids - 2D lists let you store data in rows and columns! Essential for tic-tac-toe, battleship, seating charts, and image processing.

What are 2D Lists?

A 2D list is a list of lists - like a table with rows and columns.

Key Concepts:

  • The outer list holds the rows
  • Each inner list is a row containing the columns (items)
  • Use list[row][column] to access items
  • Row index comes first, then column index

Example 1: Creating a 2D List

Create a grid by making a list of lists.

# Create a 3x3 grid (3 rows, 3 columns) grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(grid)

Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Example 2: Accessing Specific Items

Use [row][column] with TWO separate brackets!

grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Access specific items print(grid[0][0]) # Row 0, Column 0 print(grid[0][2]) # Row 0, Column 2 print(grid[1][1]) # Row 1, Column 1 print(grid[2][0]) # Row 2, Column 0

Output:
1
3
5
7

Example 3: Changing an Item

Update a specific position in the grid.

game_board = [ ['.', '.', '.'], ['.', 'X', '.'], ['.', '.', '.'] ] # Player 'O' plays at row 0, column 1 game_board[0][1] = 'O' print(game_board[0])

Output: ['.', 'O', '.']

Example 4: Looping Through 2D Lists

Use nested for loops to access every item in a 2D list.

grid = [ [1, 2, 3], [4, 5, 6] ] for row in grid: for item in row: print(item, end=' ') print() # New line after each row

Output:
1 2 3
4 5 6

Example 5: Tic-Tac-Toe Board

2D lists are perfect for game boards!

board = [ ['X', 'O', 'X'], ['O', 'X', 'O'], ['.', '.', 'X'] ] # Print the board for row in board: print(row)

Output:
['X', 'O', 'X']
['O', 'X', 'O']
['.', '.', 'X']

Common Mistakes

Wrong Right Explanation
grid[0, 1] grid[0][1] Need TWO separate brackets [row][column], not one!
grid[1][3]
# 3 columns only
grid[1][2]
# Valid access
Index out of range! Columns are 0, 1, 2
grid[column][row] grid[row][column] Wrong order! Row comes first, then column

✅ You're Ready!

  • Create 2D lists by putting lists inside a list
  • Access items with [row][column] - TWO separate brackets!
  • Remember: row index first, column index second
  • Use nested for loops to process all items
Lesson 17

Functions (Basic)

AQA OCR Edexcel

Why Functions?

Don't Repeat Yourself! Functions let you write code once and use it many times! Real programmers use functions for EVERYTHING - they make code organized, readable, and maintainable.

What Are Functions?

A function is a named, reusable block of code that performs a specific task. They make code organized, easier to read, and simpler to debug.

Key Concepts:

  • Define with the def keyword
  • Must end with a colon (:)
  • Code inside must be indented (4 spaces)
  • Call it by name followed by parentheses: do_something()

Example 1: Defining and Calling

Create a simple function and call it multiple times.

def greet(): print("Hello!") greet() greet()

Output:
Hello!
Hello!

Example 2: Functions Make Code Reusable

Write the code once, use it many times!

def welcome_message(): print("Welcome to Python Coach!") print("Let's learn together!") welcome_message() # Call the function

Output:
Welcome to Python Coach!
Let's learn together!

Example 3: Functions Without Parameters

Simple functions that do the same thing every time.

def show_menu(): print("1. Start Game") print("2. Load Game") print("3. Quit") show_menu()

Output:
1. Start Game
2. Load Game
3. Quit

Common Mistakes

Wrong Right Explanation
def greet()
print("Hi")
def greet():
print("Hi")
Forgot colon (:) and indentation!
def greet():
print("Hi")

greet
def greet():
print("Hi")

greet()
Forgot parentheses ()! Need them to call the function
Def greet(): def greet(): Python is case-sensitive! Must be lowercase 'def'

✅ You're Ready!

  • Define functions using def and a colon :
  • Call functions with parentheses ()
  • Indent the code inside functions (4 spaces)
  • Understand functions make code reusable
Lesson 18

Functions (Parameters & Return)

AQA OCR Edexcel

Why Parameters and Return?

Parameters let functions receive information, and return lets functions give back results! This makes functions incredibly powerful and flexible.

What are Parameters?

Parameters are variables listed inside the parentheses in the function definition. They let the function receive information when it's called.

Key Concepts:

  • Parameters - Variables in the function definition
  • Arguments - Actual values passed when calling
  • return - Sends a value back to the caller

Example 1: Parameters (Giving Data to a Function)

Parameters make functions flexible - they can work with different data!

def greet_user(name): print("Hello, " + name + "!") greet_user("Alex") greet_user("Sam")

Output:
Hello, Alex!
Hello, Sam!

Example 2: Multiple Parameters

Functions can accept multiple pieces of information.

def calculate_area(width, height): area = width * height print("Area:", area) calculate_area(5, 10) calculate_area(3, 7)

Output:
Area: 50
Area: 21

Example 3: The Return Statement

The return keyword sends a value back to the code that called the function.

def add_two(num): return num + 2 result = add_two(10) print(result) answer = add_two(50) print(answer)

Output:
12
52

Example 4: Return vs Print

Return gives data back, print just displays it. Return is more powerful!

def add(a, b): return a + b total = add(5, 3) print("Total:", total) # Can use the result in calculations! double_total = add(5, 3) * 2 print("Double:", double_total)

Output:
Total: 8
Double: 16

Example 5: Real-World Function

Combine parameters and return for powerful, reusable code.

def calculate_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" else: return "F" grade1 = calculate_grade(95) grade2 = calculate_grade(75) print("Grade 1:", grade1) print("Grade 2:", grade2)

Output:
Grade 1: A
Grade 2: C

Common Mistakes

Wrong Right Explanation
def greet(name):
print("Hi " + name)

greet()
def greet(name):
print("Hi " + name)

greet("Alex")
Function expects a parameter! Must provide an argument
def add(a, b):
return a + b

add(5, 3)
def add(a, b):
return a + b

result = add(5, 3)
print(result)
Return value is lost! Must store it in a variable or use it
def add(a, b):
print(a + b)

total = add(5, 3)
def add(a, b):
return a + b

total = add(5, 3)
print doesn't return! Use return to get values back

✅ You're Ready!

  • Use parameters to give information to functions
  • Return values from functions with return
  • Store returned values in variables to use them
  • Understand the difference between return and print
Lesson 19

File Handling (Write)

AQA OCR Edexcel

Why File Writing?

File writing is crucial for saving settings, recording high scores, logging program activity, or creating output reports. It lets your program persistently store information!

What is File Writing?

To write data, you must open the file in the correct mode:

Two Writing Modes:

  • "w" (Write Mode) - Creates a new file or overwrites an existing file (erases old content!)
  • "a" (Append Mode) - Creates a new file or adds content to the end of an existing file
  • Use .write(content) to put data into the file
  • You must manually add \n for new lines

Example 1: Overwriting with "w"

Write mode creates a new file or completely replaces existing content.

with open("report.txt", "w") as file: file.write("New report started.\n") file.write("Score: 100\n")

Warning: If run again, the previous content is erased!

Example 2: Appending with "a"

Append mode adds content to the end without erasing existing data.

name = "Alex" score = "45" with open("scores.txt", "a") as file: file.write(name + " - " + score + "\n")

Note: Each time this runs, a new entry is ADDED to the end.

Example 3: Writing Multiple Lines

Remember to add \n for each new line!

with open("log.txt", "w") as file: file.write("Program started\n") file.write("Loading data\n") file.write("Ready!\n")

Example 4: Saving User Data

Real programs save user input to files.

username = input("Enter username: ") score = input("Enter score: ") with open("game_saves.txt", "a") as file: file.write("Player: " + username + "\n") file.write("Score: " + score + "\n") file.write("---\n")

Common Mistakes

Wrong Right Explanation
file.write("Line 1")
file.write("Line 2")
file.write("Line 1\n")
file.write("Line 2\n")
Forgot \n! Lines will run together without newlines
with open("data.txt") as file: with open("data.txt", "w") as file: Must specify "w" or "a" mode for writing!
with open("scores.txt", "w") as file:
file.write("Score 1\n")
# Run again - Score 1 lost!
with open("scores.txt", "a") as file:
file.write("Score 1\n")
# Run again - Score 1 kept!
Using "w" when you meant "a" - erases existing data!

✅ You're Ready!

  • Use "w" mode to create or overwrite files
  • Use "a" mode to append (add to the end)
  • Use .write(content) to save data
  • Add \n manually to force new lines
Lesson 20

Dictionaries

AQA OCR Edexcel

Why Dictionaries?

Store information with labels! Like a real dictionary: look up a word (key) to get its meaning (value). Perfect for storing user profiles, game stats, and settings.

What are Dictionaries?

A dictionary is a collection of key-value pairs. Keys must be unique (like words in a dictionary), and they point to a value (the definition).

Key Concepts:

  • Use curly braces { } to create them
  • Key and value separated by a colon (:)
  • Pairs separated by commas
  • Keys must be unique
  • Access values using dict['key']

Example 1: Creating a Dictionary

Create a dictionary with curly braces and key:value pairs.

user = {'name': 'Sam', 'age': 16, 'score': 95} print(user)

Output: {'name': 'Sam', 'age': 16, 'score': 95}

Example 2: Accessing Values

Access values using the key in square brackets.

user = {'name': 'Sam', 'age': 16, 'score': 95} name = user['name'] age = user['age'] print("Name:", name) print("Age:", age)

Output:
Name: Sam
Age: 16

Example 3: Adding New Key-Value Pairs

Add new data by assigning to a new key.

user = {'name': 'Sam', 'age': 16} # Add new key-value pair user['city'] = 'New York' user['score'] = 95 print(user)

Output: {'name': 'Sam', 'age': 16, 'city': 'New York', 'score': 95}

Example 4: Changing Values

Update existing values by reassigning to the key.

user = {'name': 'Sam', 'score': 95} user['score'] = 100 # Update score print("New score:", user['score'])

Output: New score: 100

Example 5: Looping Through Items

Loop through all key-value pairs using .items() method.

user = {'name': 'Sam', 'age': 16, 'score': 95} for key, value in user.items(): print(key + " is " + str(value))

Output:
name is Sam
age is 16
score is 95

Common Mistakes

Wrong Right Explanation
user = {'name' 'Sam'} user = {'name': 'Sam'} Forgot the colon (:) between key and value!
user = {name: 'Sam'} user = {'name': 'Sam'} Keys must be in quotes (strings)!
print(user.name) print(user['name']) Use square brackets [], not dot notation!
print(user['city'])
# Key doesn't exist
user['city'] = 'London'
print(user['city'])
KeyError! Must add the key before accessing it

✅ You're Ready!

  • Create dictionaries using curly braces { }
  • Use key:value pairs separated by colons
  • Access values using square brackets: dict['key']
  • Use .items() to loop through pairs
Lesson 21

Linear Search

AQA OCR Edexcel

Why Linear Search?

How do you find something in a list? Check each item, one by one, until you find it! This is called Linear Search - the most fundamental searching algorithm.

What is Linear Search?

Linear search is an algorithm that finds a target value by checking every single item in a list sequentially, from the first item to the last.

Key Characteristics:

  • Simple and works on any type of list
  • Slow for very large lists (might check every item)
  • Best for small lists or unsorted data
  • Returns the index where found, or -1 if not found

Example 1: Basic Search Logic

Use a for loop with range(len(list)) to get the indices.

fruits = ['apple', 'banana', 'kiwi', 'mango'] target = 'kiwi' for i in range(len(fruits)): if fruits[i] == target: print("Found at index:", i)

Output: Found at index: 2

Example 2: Linear Search Function

Wrap the search logic in a function that returns the index, or -1 if not found.

def linear_search(data_list, target): for i in range(len(data_list)): if data_list[i] == target: return i # Found it! Return index return -1 # Not found (loop finished)

Example 3: Using the Search Function

Call the function and check if the item was found.

fruits = ['apple', 'banana', 'kiwi', 'mango'] index = linear_search(fruits, 'mango') if index != -1: print("Mango is at index", index) else: print("Mango not found")

Output: Mango is at index 3

Example 4: Searching for Numbers

Linear search works with any data type!

def linear_search(data_list, target): for i in range(len(data_list)): if data_list[i] == target: return i return -1 scores = [85, 92, 78, 95, 88] result = linear_search(scores, 95) if result != -1: print("Score 95 found at position", result) else: print("Score not found")

Output: Score 95 found at position 3

Example 5: Counting Comparisons

Understand how linear search works by counting comparisons.

def linear_search_with_count(data_list, target): comparisons = 0 for i in range(len(data_list)): comparisons += 1 if data_list[i] == target: print("Found after", comparisons, "comparisons") return i print("Not found after", comparisons, "comparisons") return -1 numbers = [10, 20, 30, 40, 50] linear_search_with_count(numbers, 50)

Output: Found after 5 comparisons

Common Mistakes

Wrong Right Explanation
for item in data_list:
if item == target:
return item
for i in range(len(data_list)):
if data_list[i] == target:
return i
Need to return the INDEX, not the item itself!
def search(list, target):
for i in range(len(list)):
if list[i] == target:
return i
def search(data_list, target):
for i in range(len(data_list)):
if data_list[i] == target:
return i
return -1
Forgot to return -1 when not found! Also, don't name variables 'list'
return i
return -1
return i
return -1
return -1 must be OUTSIDE the loop (not indented)!

✅ You're Ready!

  • Linear search checks each item one by one
  • Use range(len(list)) to get indices
  • Return the index when found
  • Return -1 when not found (after checking all)
Lesson 22

Error Handling

AQA OCR Edexcel

Why Error Handling?

Stop your programs from crashing! Handle errors gracefully and keep your code running smoothly. Professional programs don't crash - they handle errors intelligently.

What is Error Handling?

Python provides the try...except structure to manage errors (exceptions) that could cause the program to stop.

Key Concepts:

  • try: - Put the code that might cause an error here
  • except: - Put the code that handles the error here
  • If no error occurs in try, the except block is skipped
  • ValueError - Common error when converting invalid data

Example 1: Handling Invalid Input

The int(input()) conversion causes a ValueError if the user types letters.

try: age = int(input("Enter your age: ")) print("Age:", age) except: print("Error: Please enter only numbers!")

Output (if user enters 'hello'):
Error: Please enter only numbers!

Example 2: Specific Error Types

Catch specific errors to provide better error messages.

try: number = int(input("Enter a number: ")) result = 100 / number print("Result:", result) except ValueError: print("That's not a valid number!") except ZeroDivisionError: print("Cannot divide by zero!")

Example 3: Validating Input in a Loop

Combine try/except with a while loop to force valid input.

while True: try: age = int(input("Enter age (0-120): ")) if age < 0 or age > 120: print("Age must be between 0 and 120") else: break # Exit loop only if valid! except ValueError: print("Invalid input. Try again.") print("Age accepted:", age)

Example 4: File Handling with Error Protection

Handle errors when working with files that might not exist.

try: with open("data.txt", "r") as file: content = file.read() print(content) except FileNotFoundError: print("Error: File not found!") except: print("An error occurred while reading the file")

Example 5: Division Calculator with Error Handling

Complete example combining multiple error types.

try: num1 = int(input("First number: ")) num2 = int(input("Second number: ")) result = num1 / num2 print("Result:", result) except ValueError: print("Please enter valid numbers!") except ZeroDivisionError: print("Cannot divide by zero!") except: print("Something went wrong!")

Common Mistakes

Wrong Right Explanation
try
x = int(input())
try:
x = int(input())
Forgot the colon (:) after try!
try:
x = int(input())
print("Done")
try:
x = int(input())
except:
print("Error")
try must have a matching except block!
while True:
age = int(input())
break
while True:
try:
age = int(input())
break
except:
print("Error")
No error handling! Will crash on invalid input

✅ You're Ready!

  • Use try: to wrap risky code
  • Use except: to handle errors gracefully
  • Handle ValueError for invalid conversions
  • Combine try/except with while for validation
Lesson 23

Reading Files

AQA OCR Edexcel

Why File Reading?

Real programs need to load data from files - user settings, game saves, and datasets! File reading lets your programs persist data and work with external information.

What is File Reading?

You need to open a file, read its content, and then close it.

Key Concepts:

  • open("data.txt", "r") - Opens the file "data.txt" in read ("r") mode
  • Best Practice: Use with open(...) as file: statement
  • It automatically closes the file, even if errors occur
  • .read() - Reads entire file into a single string
  • .readlines() - Reads all lines into a list of strings

Example 1: Reading the Whole File

Use .read() to get all content as one string.

# Assume message.txt contains: Hello from the file! with open("message.txt", "r") as file: content = file.read() print(content)

Output: Hello from the file!

Example 2: The 'with' Statement

The with statement automatically closes the file - best practice!

# Good practice - file closes automatically with open("data.txt", "r") as file: content = file.read() print(content)

Example 3: Reading Line by Line

Use .readlines() to get a list of all lines. Use .strip() to remove newline characters.

with open("data.txt", "r") as file: lines = file.readlines() for line in lines: print(line.strip()) # .strip() removes \n

Output (for a file with two lines):
First line.
Second line.

Example 4: Processing File Data

Read a file and process each line.

# File contains scores, one per line with open("scores.txt", "r") as file: lines = file.readlines() total = 0 for line in lines: score = int(line.strip()) total = total + score print("Total score:", total)

Example 5: Error Handling with Files

Combine file reading with try/except for robust code.

try: with open("data.txt", "r") as file: content = file.read() print(content) except FileNotFoundError: print("Error: File not found!") except: print("An error occurred")

Common Mistakes

Wrong Right Explanation
file = open("data.txt", "r")
content = file.read()
with open("data.txt", "r") as file:
content = file.read()
Use 'with' to automatically close the file!
with open("data.txt") as file: with open("data.txt", "r") as file: Should specify "r" mode for clarity (though it's default)
lines = file.readlines()
for line in lines:
print(line)
lines = file.readlines()
for line in lines:
print(line.strip())
Forgot .strip()! Each line has \n at the end

✅ You're Ready!

  • Use open(filename, "r") to open files for reading
  • Use with open() for automatic file closing (best practice!)
  • Use .read() for entire file, .readlines() for list of lines
  • Use .strip() to remove \n from the end of lines
Lesson 24

Bubble Sort

AQA OCR Edexcel

Why Bubble Sort?

Imagine bubbles rising in water - the biggest ones float to the top first! That's exactly how bubble sort works with numbers. Bubble sort is the simplest sorting algorithm - perfect for learning how sorting works!

What is Bubble Sort?

Bubble sort repeatedly compares adjacent pairs of items and swaps them if they are in the wrong order. Each pass moves the next largest item to its final position at the end of the list (like a bubble rising).

Key Concepts:

  • Requires nested loops
  • The outer loop runs for the number of passes (i)
  • The inner loop runs for the comparisons (j)
  • Compare adjacent items: items[j] and items[j + 1]
  • Swap if in wrong order using Python's swap syntax

Example 1: The Swap Operation

Python makes swapping easy with simultaneous assignment.

numbers = [5, 2, 8, 1] # Swap positions 0 and 1 numbers[0], numbers[1] = numbers[1], numbers[0] print(numbers)

Output: [2, 5, 8, 1]

Example 2: Basic Bubble Sort

The complete bubble sort algorithm with nested loops.

numbers = [64, 34, 25, 12, 22] # Outer loop - number of passes for i in range(len(numbers) - 1): # Inner loop - comparisons for j in range(len(numbers) - 1 - i): # Compare adjacent items if numbers[j] > numbers[j + 1]: # Swap if wrong order numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(numbers)

Output: [12, 22, 25, 34, 64]

Example 3: Bubble Sort with Visualization

See how bubble sort works by printing after each pass.

numbers = [5, 2, 8, 1, 9] for i in range(len(numbers) - 1): print("Pass", i + 1) for j in range(len(numbers) - 1 - i): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(numbers) print("Final sorted:", numbers)

Output:
Pass 1
[2, 5, 1, 8, 9]
Pass 2
[2, 1, 5, 8, 9]
Pass 3
[1, 2, 5, 8, 9]
Pass 4
[1, 2, 5, 8, 9]
Final sorted: [1, 2, 5, 8, 9]

Example 4: Bubble Sort Function

Wrap bubble sort in a reusable function.

def bubble_sort(items): for i in range(len(items) - 1): for j in range(len(items) - 1 - i): if items[j] > items[j + 1]: items[j], items[j + 1] = items[j + 1], items[j] scores = [85, 92, 78, 95, 88] bubble_sort(scores) print(scores)

Output: [78, 85, 88, 92, 95]

Example 5: Descending Order

Change the comparison operator to sort in descending order.

numbers = [5, 2, 8, 1, 9] for i in range(len(numbers) - 1): for j in range(len(numbers) - 1 - i): # Change > to < for descending order if numbers[j] < numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(numbers)

Output: [9, 8, 5, 2, 1]

Common Mistakes

Wrong Right Explanation
for j in range(len(numbers)): for j in range(len(numbers) - 1): Index out of range! Need -1 because accessing j+1
temp = numbers[j]
numbers[j] = numbers[j+1]
numbers[j+1] = temp
numbers[j], numbers[j+1] = numbers[j+1], numbers[j] Python's swap is much simpler! No temp variable needed
for i in range(len(numbers)):
for j in range(len(numbers)):
for i in range(len(numbers) - 1):
for j in range(len(numbers) - 1 - i):
Need -1 in both loops! Also optimize with -i

✅ You're Ready!

  • Compare adjacent pairs and swap if wrong order
  • Use nested loops: outer for passes, inner for comparisons
  • Inner loop range: range(len(items) - 1 - i)
  • Use > for ascending order, < for descending
  • Simple but slow for large lists
Lesson 25

Merge Sort

AQA OCR Edexcel

Why Merge Sort?

Merge sort is used because simple sorts like bubble sort are SLOW. For 1000 items, bubble sort is ~50 times slower than merge sort. Merge sort uses divide and conquer - it's how Python's built-in sort() works!

What is Merge Sort?

The core idea is Divide, Conquer, and Combine.

The Three Steps:

  • 1. Divide: The list is split into two halves
  • 2. Conquer: Each half is recursively sorted until the list size is 1 (base case)
  • 3. Combine (Merge): The two sorted halves are merged back together
  • A single item list is the base case and is considered sorted
  • The merging step compares the first items of the two lists

Example 1: Understanding the Divide Step

Split the list into two halves using the middle index.

numbers = [38, 27, 43, 3, 9, 82, 10] middle = len(numbers) // 2 left_half = numbers[:middle] right_half = numbers[middle:] print("Original:", numbers) print("Left half:", left_half) print("Right half:", right_half)

Output:
Original: [38, 27, 43, 3, 9, 82, 10]
Left half: [38, 27, 43]
Right half: [3, 9, 82, 10]

Example 2: The Merge Function

Merge two sorted lists into one sorted list.

def merge(left, right): result = [] i = 0 j = 0 # Compare items from both lists while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # Add remaining items result.extend(left[i:]) result.extend(right[j:]) return result left = [3, 27, 38] right = [9, 10, 82] merged = merge(left, right) print(merged)

Output: [3, 9, 10, 27, 38, 82]

Example 3: Complete Merge Sort

The full recursive merge sort algorithm.

def merge_sort(items): # Base case: list of 0 or 1 item is sorted if len(items) <= 1: return items # Divide middle = len(items) // 2 left = items[:middle] right = items[middle:] # Conquer (recursive calls) left = merge_sort(left) right = merge_sort(right) # Combine return merge(left, right) def merge(left, right): result = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result numbers = [38, 27, 43, 3, 9, 82, 10] sorted_numbers = merge_sort(numbers) print(sorted_numbers)

Output: [3, 9, 10, 27, 38, 43, 82]

Example 4: Visualizing Merge Sort

See the divide and conquer process in action.

def merge_sort_visual(items, depth=0): indent = " " * depth print(f"{indent}Dividing: {items}") if len(items) <= 1: print(f"{indent}Base case: {items}") return items middle = len(items) // 2 left = merge_sort_visual(items[:middle], depth + 1) right = merge_sort_visual(items[middle:], depth + 1) result = merge(left, right) print(f"{indent}Merged: {result}") return result numbers = [5, 2, 8, 1] merge_sort_visual(numbers)

Common Mistakes

Wrong Right Explanation
if len(items) == 1: if len(items) <= 1: Need <= to handle empty lists! Base case includes 0 and 1
merge_sort(items)
# Original unchanged
items = merge_sort(items)
print(items)
merge_sort returns a new list! Must capture the result
middle = len(items) / 2 middle = len(items) // 2 Need integer division //! Regular / gives float

✅ You're Ready!

  • Divide and conquer: split, sort, merge
  • Base case: len(items) <= 1 is sorted
  • Split with: middle = len(items) // 2
  • Merge by comparing the first items of the two halves
  • Merge sort is MUCH faster than bubble sort for big lists
Lesson 26

Stacks and Queues

AQA OCR Edexcel

Why Stacks and Queues?

Stacks and queues are fundamental data structures used everywhere in computing - from browser history (stack) to printer queues (queue)! Understanding these structures is essential for GCSE Computer Science.

What are Stacks?

A stack is a Last In, First Out (LIFO) data structure - like a stack of plates! The last plate you put on top is the first one you take off.

Stack Operations:

  • Push - Add an item to the top (use .append())
  • Pop - Remove and return the top item (use .pop())
  • Peek - Look at the top item without removing it (use [-1])
  • isEmpty - Check if stack is empty (use len() == 0)

Example 1: Stack Operations

Implement a stack using Python lists.

stack = [] # Push (add to top) stack.append("Page 1") stack.append("Page 2") stack.append("Page 3") print("Stack:", stack) # Peek (look at top) print("Top:", stack[-1]) # Pop (remove from top) removed = stack.pop() print("Removed:", removed) print("Stack:", stack)

Output:
Stack: ['Page 1', 'Page 2', 'Page 3']
Top: Page 3
Removed: Page 3
Stack: ['Page 1', 'Page 2']

What are Queues?

A queue is a First In, First Out (FIFO) data structure - like a queue of people! The first person in line is the first person served.

Queue Operations:

  • Enqueue - Add an item to the back (use .append())
  • Dequeue - Remove and return the front item (use .pop(0))
  • Front - Look at the front item (use [0])
  • isEmpty - Check if queue is empty (use len() == 0)

Example 2: Queue Operations

Implement a queue using Python lists.

queue = [] # Enqueue (add to back) queue.append("Customer 1") queue.append("Customer 2") queue.append("Customer 3") print("Queue:", queue) # Front (look at front) print("Front:", queue[0]) # Dequeue (remove from front) served = queue.pop(0) print("Served:", served) print("Queue:", queue)

Output:
Queue: ['Customer 1', 'Customer 2', 'Customer 3']
Front: Customer 1
Served: Customer 1
Queue: ['Customer 2', 'Customer 3']

Example 3: Stack - Browser History

Real-world example: implementing browser back button.

history = [] def visit_page(page): history.append(page) print("Visiting:", page) def go_back(): if len(history) > 1: history.pop() # Remove current page print("Back to:", history[-1]) else: print("No history!") visit_page("google.com") visit_page("youtube.com") visit_page("github.com") go_back() go_back()

Output:
Visiting: google.com
Visiting: youtube.com
Visiting: github.com
Back to: youtube.com
Back to: google.com

Example 4: Queue - Print Jobs

Real-world example: managing a printer queue.

print_queue = [] def add_job(job): print_queue.append(job) print(f"Added: {job}") def print_next(): if len(print_queue) > 0: job = print_queue.pop(0) print(f"Printing: {job}") else: print("No jobs in queue") add_job("Document 1") add_job("Document 2") add_job("Document 3") print_next() print_next() print("Remaining:", print_queue)

Output:
Added: Document 1
Added: Document 2
Added: Document 3
Printing: Document 1
Printing: Document 2
Remaining: ['Document 3']

Common Mistakes

Wrong Right Explanation
stack.pop(0)
# For stack
stack.pop()
# For stack
Stack removes from END! .pop() not .pop(0)
queue.pop()
# For queue
queue.pop(0)
# For queue
Queue removes from FRONT! .pop(0) not .pop()
if stack:
# Check empty
if len(stack) > 0:
# Check empty
Be explicit! Use len() for clarity

✅ You're Ready!

  • Stack (LIFO): Last In, First Out - like plates
  • Queue (FIFO): First In, First Out - like a line
  • Stack uses .append() and .pop()
  • Queue uses .append() and .pop(0)
  • Real uses: browser history (stack), print jobs (queue)
Lesson 27

Authentication

AQA OCR Edexcel

Why Authentication?

Every app and website needs to verify who's using it. Authentication means proving you are who you say you are (your identity). It's fundamental to modern computing security!

What is Authentication?

The core process is to Verify Identity using a Username + Password. Authorization is a different step that determines what you can do after logging in (your permissions).

Implementation Steps:

  • 1. Storage: Store users (e.g., in a dictionary: {username: password})
  • 2. Input: Ask the user for their username and password
  • 3. Check: Check if the username exists in your storage
  • 4. Validate: Compare the provided password with the stored password

Example 1: Basic User Storage

Store users in a dictionary with username as key and password as value.

users = { 'alice': 'password123', 'bob': 'securepass', 'charlie': 'mypass456' } print("Registered users:", list(users.keys()))

Output: Registered users: ['alice', 'bob', 'charlie']

Example 2: Simple Login

Check if username exists and password matches.

users = { 'alice': 'password123', 'bob': 'securepass' } username = input("Username: ") password = input("Password: ") if username in users: if users[username] == password: print("Login successful!") else: print("Incorrect password") else: print("Username not found")

Example 3: Registration Function

Let users create new accounts with validation.

users = {} def register(): username = input("Choose username: ") if username in users: print("Username already exists!") return password = input("Choose password: ") # Basic password validation if len(password) < 8: print("Password must be at least 8 characters!") return users[username] = password print("Registration successful!") register()

Example 4: Complete Authentication System

Combine registration and login with validation.

users = {'admin': 'admin123'} def register(): username = input("Username: ") if username in users: print("Username taken!") return False password = input("Password (min 8 chars): ") if len(password) < 8: print("Password too short!") return False users[username] = password print("Registered successfully!") return True def login(): username = input("Username: ") password = input("Password: ") if username in users and users[username] == password: print(f"Welcome {username}!") return True else: print("Invalid credentials!") return False # Menu system while True: choice = input("1=Register, 2=Login, 3=Quit: ") if choice == "1": register() elif choice == "2": if login(): break elif choice == "3": break

Security Best Practices

⚠️ Important Security Notes:

  • Hashing: NEVER store passwords in plain text! Real systems use hashing (one-way encryption)
  • Validation: Check password strength (length, numbers, symbols)
  • 2FA: Two-Factor Authentication adds extra security beyond passwords
  • Encryption: Protect data in transit and at rest

Example 5: Password Strength Validation

Check that passwords meet security requirements.

def is_strong_password(password): if len(password) < 8: print("Too short (min 8 chars)") return False has_digit = False has_letter = False for char in password: if char.isdigit(): has_digit = True if char.isalpha(): has_letter = True if not has_digit: print("Must include numbers") return False if not has_letter: print("Must include letters") return False return True password = input("Enter password: ") if is_strong_password(password): print("Strong password!")

Common Mistakes

Wrong Right Explanation
users = {'alice', 'bob'} users = {'alice': 'pass1', 'bob': 'pass2'} Need key:value pairs! Can't just store usernames
if password == users[username]: if username in users:
if password == users[username]:
Check username exists first! Otherwise KeyError
users[username] = password
# No validation
if len(password) >= 8:
users[username] = password
Always validate password strength!

✅ You're Ready!

  • Username + password verify identity
  • Store users in dictionary: {username: password}
  • Validate password strength (length, numbers, letters)
  • Real apps hash passwords, never plain text
  • Two-factor authentication adds extra security

📚 Complete Coverage: Lessons 1-27

This document contains full teaching content for all 27 lessons including: Input Function • String Operations • Selection Statements • Loops • Lists & 2D Lists • Functions • File Handling • Dictionaries • Algorithms (Linear Search, Bubble Sort, Merge Sort) • Error Handling • Stacks & Queues • Authentication

Use Ctrl+F to search for any topic across the complete curriculum

Python Coach - Complete GCSE Curriculum Reference

27 Comprehensive Lessons • 100% Specification Coverage

AQA 8525 | OCR J277 | Edexcel 1CP2

📚 Quick Navigation
1. Print Statements 2. Comments 3. Variables 4. Data Types 5. Arithmetic Operators 6. Input Function 7. String Concatenation 8. String Methods 9. String Slicing 10. If Statements 11. Elif and Else 12. Boolean Logic 13. For Loops 14. While Loops 15. Lists 16. 2D Lists 17. Functions (Basic) 18. Functions (Parameters) 19. File Handling (Write) 20. Dictionaries 21. Linear Search 22. Error Handling 23. Reading Files 24. Bubble Sort 25. Merge Sort 26. Stacks and Queues 27. Authentication