🐍 Python Starter Pack for GCSE Success

OCR COMPUTER SCIENCE

Your complete Python programming guide aligned with OCR GCSE specification

🚀 Welcome to Python Programming!

This comprehensive guide covers everything you need to master Python for your GCSE Computer Science exam.

What's included:

  • All OCR specification Python topics
  • Step-by-step syntax explanations
  • Common errors and how to fix them
  • Exam-style code examples
  • Practice exercises with solutions
  • Links to the best learning resources
  • Debugging strategies that work

Learning Path

📚 Part 1: Python Fundamentals
🔄 Part 2: Control Flow
📊 Part 3: Data Structures
🔧 Part 4: Functions & Procedures
📁 Part 5: File Handling
🎯 Part 6: OCR Exam Algorithms
🐛 Part 7: Debugging Strategies

📚 Part 1: Python Fundamentals

Variables & Data Types

The building blocks of every program

# Integer (whole numbers) age = 16 score = 100 # Float (decimal numbers) price = 19.99 pi = 3.14159 # String (text) name = "Alice" message = 'Hello World' # Boolean (True/False) is_student = True game_over = False
OCR Exam Tip: Always use meaningful variable names!
❌ x = 16
✅ student_age = 16

Input & Output

Interacting with users

# Getting input (always returns string!) name = input("Enter your name: ") age = int(input("Enter your age: ")) height = float(input("Height in metres: ")) # Output print("Hello", name) print(f"You are {age} years old") print("Height: " + str(height) + "m")
⚠️ Common Error: Forgetting to convert input!
age = input("Age: ") # This is a string!
age = int(input("Age: ")) # Convert to integer

Arithmetic Operators

Mathematical operations in Python

# Basic operations add = 10 + 5 # 15 subtract = 10 - 5 # 5 multiply = 10 * 5 # 50 divide = 10 / 5 # 2.0 (float) # Special operators power = 2 ** 3 # 8 (2³) floor_div = 10 // 3 # 3 (integer division) modulus = 10 % 3 # 1 (remainder) # Order of operations (BIDMAS) result = 2 + 3 * 4 # 14, not 20!
✅ Pro Tip: Use brackets to make your code clearer:
result = (2 + 3) * 4 # Now it's 20!

🔄 Part 2: Control Flow

1

Selection (IF Statements)

# Simple if statement age = int(input("Enter your age: ")) if age >= 18: print("You can vote!") # If-else statement password = input("Enter password: ") if password == "secret123": print("Access granted") else: print("Access denied") # If-elif-else (multiple conditions) grade = int(input("Enter your mark: ")) if grade >= 90: print("Grade 9 - Outstanding!") elif grade >= 80: print("Grade 8 - Excellent!") elif grade >= 70: print("Grade 7 - Very good!") elif grade >= 60: print("Grade 6 - Good!") else: print("Keep practising!") # Combining conditions age = 16 has_permission = True if age >= 15 and has_permission: print("You can attend") # Using 'or' and 'not' day = "Saturday" if day == "Saturday" or day == "Sunday": print("It's the weekend!") if not game_over: print("Keep playing!")
OCR Pattern Recognition: Examiners love nested if statements!
username = input("Username: ") if len(username) >= 3: password = input("Password: ") if len(password) >= 8: print("Account created!") else: print("Password too short") else: print("Username too short")
2

Iteration (Loops)

# FOR loop - when you know how many times for i in range(5): print(i) # Prints 0, 1, 2, 3, 4 for i in range(1, 6): print(i) # Prints 1, 2, 3, 4, 5 for i in range(2, 11, 2): print(i) # Prints 2, 4, 6, 8, 10 (step by 2) # Looping through a string word = "Python" for letter in word: print(letter) # WHILE loop - when you don't know how many times password = "" while password != "quit": password = input("Enter password (or 'quit'): ") if password == "secret": print("Access granted!") break # Exit the loop early # Counting with while count = 0 while count < 5: print(count) count = count + 1 # or count += 1 # Input validation loop age = -1 while age < 0 or age > 120: age = int(input("Enter valid age (0-120): "))
⚠️ Avoid Infinite Loops:
# WRONG - infinite loop! x = 1 while x > 0: print(x) # x never changes! # CORRECT x = 5 while x > 0: print(x) x = x - 1 # x decreases each time

📊 Part 3: Data Structures

Lists (Arrays)

Storing multiple values

# Creating lists scores = [78, 92, 65, 88, 95] names = ["Alice", "Bob", "Charlie"] mixed = [42, "Hello", 3.14, True] empty_list = [] # Accessing elements (0-indexed!) print(scores[0]) # 78 (first element) print(scores[-1]) # 95 (last element) # Changing elements scores[2] = 70 # Change 65 to 70 # Adding elements scores.append(100) # Add to end scores.insert(0, 50) # Insert at position # Removing elements scores.remove(70) # Remove first 70 last = scores.pop() # Remove & return last del scores[0] # Delete at index # List operations length = len(scores) total = sum(scores) highest = max(scores) lowest = min(scores) average = sum(scores) / len(scores) # Checking if item exists if 92 in scores: print("92 is in the list!") # Looping through lists for score in scores: print(score) for i in range(len(scores)): print(f"Score {i}: {scores[i]}")

2D Lists (Tables)

Lists within lists

# Creating a 2D list (table/grid) grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Accessing elements print(grid[0][0]) # 1 (row 0, col 0) print(grid[1][2]) # 6 (row 1, col 2) # Changing elements grid[1][1] = 10 # Looping through 2D lists for row in grid: for item in row: print(item, end=" ") print() # New line after each row # Creating empty 2D list rows = 3 cols = 4 matrix = [] for i in range(rows): row = [] for j in range(cols): row.append(0) matrix.append(row)

Strings as Lists

String manipulation

text = "Hello World" # String indexing first = text[0] # 'H' last = text[-1] # 'd' # Slicing strings hello = text[0:5] # "Hello" world = text[6:11] # "World" reverse = text[::-1] # "dlroW olleH" # String methods upper = text.upper() # "HELLO WORLD" lower = text.lower() # "hello world" length = len(text) # 11 count = text.count('l') # 3 # Checking content if "World" in text: print("Found it!") # Splitting and joining words = text.split() # ["Hello", "World"] joined = "-".join(words) # "Hello-World" # String validation user_input = input("Enter numbers only: ") if user_input.isdigit(): number = int(user_input) else: print("Invalid input!")

🔧 Part 4: Functions & Procedures

3

Creating and Using Functions

# Simple function (no parameters, no return) def greet(): print("Hello!") print("Welcome to Python") # Calling the function greet() # Function with parameters def greet_person(name): print(f"Hello, {name}!") greet_person("Alice") greet_person("Bob") # Function with multiple parameters def calculate_area(length, width): area = length * width print(f"Area = {area}") calculate_area(5, 3) # Function with return value def add_numbers(a, b): result = a + b return result answer = add_numbers(10, 20) print(answer) # 30 # Function with multiple returns def get_min_max(numbers): return min(numbers), max(numbers) scores = [65, 78, 92, 88, 73] lowest, highest = get_min_max(scores) print(f"Range: {lowest} to {highest}") # Function with default parameters def power(base, exponent=2): return base ** exponent print(power(5)) # 25 (5²) print(power(5, 3)) # 125 (5³)
OCR Exam Pattern: Functions that validate input
def get_valid_age(): while True: try: age = int(input("Enter age (0-120): ")) if 0 <= age <= 120: return age else: print("Age must be between 0 and 120") except ValueError: print("Please enter a number") # Using the validation function user_age = get_valid_age() print(f"Valid age entered: {user_age}")

🎯 Part 6: OCR Exam Algorithms

Linear Search

def linear_search(items, target): """Search for target in items list""" for i in range(len(items)): if items[i] == target: return i # Return position return -1 # Not found # Example usage names = ["Alice", "Bob", "Charlie", "David"] position = linear_search(names, "Charlie") if position != -1: print(f"Found at position {position}") else: print("Not found")

Binary Search

def binary_search(items, target): """Binary search - list must be sorted!""" low = 0 high = len(items) - 1 while low <= high: mid = (low + high) // 2 if items[mid] == target: return mid # Found it! elif items[mid] < target: low = mid + 1 # Search upper half else: high = mid - 1 # Search lower half return -1 # Not found # Example usage numbers = [2, 5, 8, 12, 16, 23, 38, 45, 67] position = binary_search(numbers, 23) if position != -1: print(f"Found at position {position}") else: print("Not found")
Remember: Binary search ONLY works on sorted lists! It's much faster than linear search for large lists.

Bubble Sort

def bubble_sort(items): """Sort list in ascending order""" n = len(items) for i in range(n): swapped = False # Last i elements are already sorted for j in range(0, n - i - 1): if items[j] > items[j + 1]: # Swap elements items[j], items[j + 1] = items[j + 1], items[j] swapped = True # If no swaps, list is sorted if not swapped: break return items # Example usage scores = [64, 34, 25, 12, 22, 11, 90] print("Original:", scores) bubble_sort(scores) print("Sorted:", scores)

Insertion Sort

def insertion_sort(items): """Sort list using insertion sort""" for i in range(1, len(items)): key = items[i] j = i - 1 # Move elements greater than key one position ahead while j >= 0 and items[j] > key: items[j + 1] = items[j] j = j - 1 # Insert key at correct position items[j + 1] = key return items # Example usage numbers = [12, 11, 13, 5, 6] print("Original:", numbers) insertion_sort(numbers) print("Sorted:", numbers)

🐛 Part 7: Debugging Strategies

Common Errors & Fixes

1. IndentationError
# WRONG if age >= 18: print("Adult") # Not indented! # CORRECT if age >= 18: print("Adult") # Indented with 4 spaces
2. NameError
# WRONG print(username) # Variable not defined! # CORRECT username = "Alice" print(username)
3. IndexError
# WRONG numbers = [1, 2, 3] print(numbers[3]) # Index 3 doesn't exist! # CORRECT print(numbers[2]) # Last element at index 2

Testing Techniques

Print Statement Debugging
def calculate_grade(marks): print(f"DEBUG: marks = {marks}") # Check input percentage = (marks / 80) * 100 print(f"DEBUG: percentage = {percentage}") # Check calculation if percentage >= 90: grade = 9 elif percentage >= 80: grade = 8 else: grade = 7 print(f"DEBUG: grade = {grade}") # Check output return grade # Test with different values result = calculate_grade(72) print(f"Final grade: {result}")

Testing Checklist:

Normal data: Expected values (e.g., age = 25)
Boundary data: Edge cases (e.g., age = 0, 120)
Erroneous data: Invalid input (e.g., age = -5, "abc")
Empty data: No input (e.g., empty string)

📊 OCR Trace Tables

Track variable values step by step - essential for OCR Paper 2!

Example 1: Simple Loop Trace

total = 0 for i in range(1, 4): total = total + i print(total)
Line i total Output
1 - 0 -
2-4 1 1 1
2-4 2 3 3
2-4 3 6 6

Example 2: While Loop with Condition

x = 10 count = 0 while x > 5: x = x - 2 count = count + 1 print(count)
Line x count x > 5? Output
1-2 10 0 - -
3 10 0 True -
4-5 8 1 True -
4-5 6 2 True -
4-5 4 3 False -
6 4 3 - 3
✅ OCR Exam Tip: Always show EVERY iteration in your trace table, even if the loop exits early. Show the condition check that causes the loop to end!

📈 Track Your Python Progress

Use this tracker to monitor your Python learning journey!

Variables & Data Types 0%
Master the basics!
Selection (IF Statements) 0%
Make decisions!
Iteration (Loops) 0%
Repeat with power!
Lists & Arrays 0%
Store multiple values!
Functions 0%
Reusable code!
File Handling 0%
Work with files!
Algorithms 0%
Search and sort!

🌐 Part 8: Essential Resources

🎮 Fun Python Projects to Try:

• Number guessing game
• Rock, Paper, Scissors
• Simple calculator
• Password generator
• Quiz game with scoring
• To-do list manager
• Basic text adventure
• Hangman word game

✅ Part 9: Quick Reference Sheet

Comments: # This is a comment
Variables: name = "Alice"
Input: age = int(input("Age: "))
Output: print(f"Hello {name}")
If Statement: if x > 0: print("Positive")
For Loop: for i in range(10): print(i)
While Loop: while x < 10: x += 1
List: scores = [78, 92, 65]
Append to List: scores.append(88)
Function: def add(a, b): return a + b
Random Number: import random; num = random.randint(1, 10)
String Length: length = len("Hello")
Type Conversion: str(), int(), float(), bool()
Logical Operators: and, or, not

🚀 Ready to Master Python?

Join my Python Programming Group Sessions!

What You'll Get:

✓ Live coding sessions
✓ Weekly challenges
✓ 1-to-1 debugging help
✓ Exam-style problems
✓ Project portfolio building
✓ OCR-specific preparation
✓ Certificate on completion
✓ Lifetime resource access