GCSE Python Docs

A quick reference guide for all core programming concepts required for GCSE Computer Science (AQA, OCR, Edexcel).

Variables & Data Types

Variables are named storage locations in memory. Constants (values that shouldn't change) are typically written in uppercase.

Data Types

  • str - Text (String)
  • int - Whole number (Integer)
  • float - Decimal number (Real)
  • bool - True or False (Boolean)
variables.py
# Assigning variables
name = "Alice"       # String
age = 16             # Integer
height = 1.75        # Float
is_student = True    # Boolean

# Constants (Convention is UPPER_CASE)
PI = 3.14159
MAX_SCORE = 100

# Outputting to the console
print("Name:", name)
print(f"Age: {age}") 
print(f"Area: {PI * 5 * 5}") # Calculation inside f-string

# Checking types
print(type(name))   # 
print(type(age))    # 

Comments

Comments are ignored by the computer but help humans understand the code.

comments.py
# This is a single-line comment
x = 5 # Comments can go at the end of a line

'''
This is a multi-line comment.
It can span multiple lines.
Useful for explaining complex logic.
'''
print("Comments are invisible to the computer!")

Casting

Casting is converting one data type into another. This is crucial when taking input (which is always a string by default).

casting.py
# String to Integer
num_str = "50"
num_int = int(num_str) 

# Integer to String
score = 100
message = "Score: " + str(score)

# Input is always string, wrap in int() for maths
# Try running this and entering a number!
try:
    age = int(input("Enter your age: "))
    next_year = age + 1
    print(f"Next year you will be {next_year}")
except ValueError:
    print("Please enter a valid whole number")

Operators

Type Operator Description Example
Arithmetic + - * / Basic Maths 5 + 2 # 7
// Integer Division (Quotient) 7 // 2 # 3
% Modulus (Remainder) 7 % 2 # 1
Comparison == != > < >= <= Returns Boolean 5 == 5 # True

String Manipulation

Strings can be indexed, sliced, and modified using methods.

strings.py
text = "Computer Science"

# Length
print(len(text))        # 16

# Case conversion
print(text.upper())     # "COMPUTER SCIENCE"
print(text.lower())     # "computer science"

# Indexing (Starts at 0)
print(text[0])          # "C"
print(text[-1])         # "e" (last character)

# Slicing [start:stop]
print(text[0:8])        # "Computer" (stops before index 8)
print(text[9:])         # "Science" (to the end)

# Advanced Slicing [start:stop:step]
print(text[::-1])       # "ecneicS retupmoC" (Reverse)

# Replacement
new_text = text.replace("Science", "Programming")
print(new_text)         # "Computer Programming"

# Splitting to list
sentence = "Coding is fun"
words = sentence.split(" ") 
print(words)            # ['Coding', 'is', 'fun']

# Concatenation (Joining)
first = "Hello"
second = "World"
combined = first + " " + second # "Hello World"

Selection (Branching)

Making decisions in code using if, elif, and else. Indentation is critical in Python.

selection.py
# Example 1: Simple Grades
score = 75

if score >= 80:
    print("Grade: A")
elif score >= 60:
    print("Grade: B")
elif score >= 40:
    print("Grade: C")
else:
    print("Grade: U")
    
# Example 2: Nested Selection and Logic
age = 15
has_ticket = True

if has_ticket:
    if age >= 18:
        print("Allowed entry (Adult)")
    elif age >= 12:
        print("Allowed entry (Teen)")
    else:
        print("Too young for this movie")
else:
    print("Please buy a ticket first")

# Logical Operators: and, or, not
day = "Saturday"
sunny = True

if (day == "Saturday" or day == "Sunday") and sunny:
    print("Let's go to the beach!")

Iteration (Loops)

Count-controlled (For Loop)

Used when you know how many times you want to loop.

for_loops.py
# Range(start, stop, step)
for i in range(5):
    print(i)        # Prints 0, 1, 2, 3, 4

print("---")

for i in range(10, 0, -1):
    print(i)        # Countdown from 10 to 1

# Totaling example
total = 0
for i in range(1, 6):
    total = total + i
print(f"Sum of 1 to 5 is: {total}")

Condition-controlled (While Loop)

Used when you want to loop until a condition changes.

while_loops.py
# Basic password check
password = ""
while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Wrong password, try again.")
print("Access Granted")

# Using break to exit early
print("Type 'exit' to stop")
while True:
    user_input = input("> ")
    if user_input == "exit":
        print("Goodbye!")
        break
    print(f"You said: {user_input}")

Lists (Arrays)

Lists allow you to store multiple items in a single variable.

lists.py
fruits = ["Apple", "Banana", "Cherry"]

# Accessing items
print(fruits[0])      # Apple
print(len(fruits))    # Length is 3

# Modifying items
fruits[1] = "Blueberry"

# Adding items
fruits.append("Date")       # Adds to end
fruits.insert(0, "Apricot") # Adds to start

# Removing items
fruits.pop()          # Removes last item
fruits.remove("Apple") # Removes specific item

# Numerical Lists & Functions
numbers = [5, 2, 9, 1, 8]
print(max(numbers))   # 9
print(min(numbers))   # 1
print(sum(numbers))   # 25

numbers.sort()        # Sorts list in-place
print(numbers)        # [1, 2, 5, 8, 9]

# Looping through a list
for fruit in fruits:
    print(fruit)

Dictionaries

Dictionaries store data in Key: Value pairs. They are useful for creating records about a single object.

dictionaries.py
# Creating a dictionary (record)
student = {
    "name": "Alex",
    "age": 16,
    "grade": "A",
    "is_enrolled": True
}

# Accessing data
print(student["name"])  # Alex

# Modifying data
student["age"] = 17

# Adding new data
student["email"] = "[email protected]"

# Looping through keys and values
for key, value in student.items():
    print(f"{key}: {value}")

2D Lists

A list inside a list, used to create grids or tables of data.

2d_lists.py
# A 3x3 grid (like a Tic-Tac-Toe board)
grid = [
    ["X", "O", "X"],
    ["O", "X", "O"],
    ["O", "X", "O"]
]

print(grid[0][0])  # Top-left
print(grid[1][1])  # Center

# Changing a value
grid[2][2] = "X"

# Nested loop to print grid nicely
for row in grid:
    for item in row:
        print(item, end=" ")
    print() # New line at end of row

Subprograms (Functions)

Blocks of reusable code. Parameters allow you to pass data in, and return allows you to send data back.

functions.py
# Procedure (performs action, no return)
def greet(name, time_of_day="Day"): # Default parameter
    print(f"Good {time_of_day}, {name}!")

# Function (calculates and returns value)
def check_grade(score):
    if score >= 50:
        return "Pass"
    else:
        return "Fail"

# Main Program
greet("Sam", "Morning") 
greet("Alex") # Uses default "Day"

my_score = 65
result = check_grade(my_score)
print(f"Student got: {result}")

Scope (Global vs Local)

Local variables only exist inside the function they were created in. Global variables exist everywhere.

scope.py
score = 0 # Global variable

def increase_score():
    global score # We must tell Python we want to use the global 'score'
    score = score + 1
    print(f"Score inside function: {score}")

increase_score()
print(f"Score outside function: {score}")

def local_demo():
    my_secret = "Hidden" # Local variable
    print(my_secret)

local_demo()
# print(my_secret) # This would cause an Error!

Error Handling

Defensive design ensures your program doesn't crash if the user enters unexpected data. We use try and except blocks.

error_handling.py
valid_input = False

while not valid_input:
    try:
        # This code might crash if user types text
        number = int(input("Enter a number to divide 100 by: "))
        result = 100 / number
        print(f"Result: {result}")
        valid_input = True # Only runs if lines above succeed
        
    except ValueError:
        print("Error: You must enter a whole number.")
        
    except ZeroDivisionError:
        print("Error: You cannot divide by zero.")
        
    except Exception as e:
        print(f"Unknown error occurred: {e}")

File Handling

Reading from and writing to external text files. Using with ensures the file closes automatically. (Note: File operations might not work in online editors like Trinket without special setup).

files.py
# Writing to a file ('w' overwrites, 'a' appends)
with open("data.txt", "w") as file:
    file.write("Hello World\n")
    file.write("Python is fun")

# Reading from a file ('r' read mode)
try:
    with open("data.txt", "r") as file:
        content = file.read() 
        print(content)
except FileNotFoundError:
    print("File does not exist yet.")

# Reading line by line into a list
with open("data.txt", "r") as file:
    lines = file.readlines()
    print(f"There are {len(lines)} lines in the file.")

Standard Libraries

Python comes with built-in modules that you can import to add extra functionality like random numbers, time delays, and complex maths.

libraries.py
import random
import time
import math

# --- Random ---
roll = random.randint(1, 10)
print(f"You rolled a {roll}")
print(f"Random choice: {random.choice(['Red', 'Blue'])}")

# --- Time ---
print("Wait for it...")
time.sleep(1) # Pauses program for 1 second
print("Done!")

# --- Math ---
print(f"Pi is roughly {math.pi}")
print(f"Square root of 16 is {math.sqrt(16)}")
print(f"Floor (round down): {math.floor(4.9)}")
print(f"Ceil (round up): {math.ceil(4.1)}")