/ Coding Help

GCSE Help

Core Python concepts for GCSE - code examples with explanations and a guide to the most common built-in functions.

Code Examples

📦
Variables
Store and label information
# Variables hold data - use = to assign
name = "Alice"       # text (string)
age = 14             # whole number (integer)
score = 9.5          # decimal (float)
is_playing = True    # true or false (boolean)

print(name)          # Alice
print(age)           # 14
print(type(score))   # <class 'float'>

# You can change a variable at any time
age = age + 1        # age is now 15
age += 1             # shorthand - age is now 16
print(age)
= assigns, == compares Strings use " " or ' ' Names are case-sensitive
🔀
If Statements
Make decisions in your code
score = 85

# if / elif / else - only one block runs
if score >= 90:
    print("Excellent!")
elif score >= 70:
    print("Good job!")
elif score >= 50:
    print("Keep practising!")
else:
    print("See your teacher.")

# Comparing text - use .lower() for safety
name = input("Enter name: ").lower()

if name == "alice":
    print("Welcome back, Alice!")
elif name == "bob":
    print("Hey Bob!")
else:
    print("Hello,", name)
Colon : after condition Indent body 4 spaces elif = else if
🔃
Match / Case
Python's switch statement - match a value against cases
# match/case checks a value against multiple options
# Introduced in Python 3.10

day = input("Enter a day: ").lower()

match day:
    case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
        print("It's a weekday.")
    case "saturday" | "sunday":
        print("It's the weekend!")
    case _:             # _ is the default - like 'else'
        print("That's not a valid day.")

# Works great for menu selections
choice = input("Menu - choose 1, 2 or 3: ")

match choice:
    case "1":
        print("You chose: Start game")
    case "2":
        print("You chose: View scores")
    case "3":
        print("You chose: Quit")
    case _:
        print("Invalid option - please enter 1, 2 or 3")
| means OR between cases _ is the default case Cleaner than long if/elif chains
🔄
While Loops
Keep repeating until a condition becomes false
# Basic while loop - always update the variable!
count = 1
while count <= 5:
    print(count)
    count += 1        # without this it loops forever!

# Keep asking until the user types something valid
answer = ""
while answer != "quit":
    answer = input("Type 'quit' to stop: ")
    print("You typed:", answer)

# break exits a loop immediately
for i in range(100):
    if i == 5:
        break         # stops the loop at 5
    print(i)          # prints 0 1 2 3 4

# continue skips the rest of the current loop step
for i in range(6):
    if i == 3:
        continue      # skips 3
    print(i)          # prints 0 1 2 4 5
Always update the variable! break exits loop continue skips to next
🔁
For Loops
Repeat code for each item in a sequence
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Loop a fixed number of times with range()
for i in range(5):
    print(i)          # prints 0 1 2 3 4

# range(start, stop, step)
for i in range(2, 11, 2):
    print(i)          # 2 4 6 8 10

# Loop through characters in a string
word = "Python"
for letter in word:
    print(letter)     # P y t h o n

# Use enumerate() to get index AND value
for i, fruit in enumerate(fruits):
    print(i, fruit)   # 0 apple, 1 banana...
range(5) = 0 to 4 Works on lists, strings Indent body 4 spaces
🔤
String Manipulation
Work with and transform text
word = "Hello, World!"

# Indexing and slicing
print(word[0])        # H  (first character)
print(word[-1])       # !  (last character)
print(word[0:5])      # Hello  (chars 0–4)
print(word[7:])       # World!

# Common string methods
print(word.upper())         # HELLO, WORLD!
print(word.lower())         # hello, world!
print(word.replace("World", "Python"))  # Hello, Python!
print(word.find("World"))   # 7  (index where it starts)
print(len(word))            # 13

# Split and join
csv = "Alice,Bob,Charlie"
names = csv.split(",")      # ['Alice', 'Bob', 'Charlie']
print(names[1])             # Bob
print(", ".join(names))     # Alice, Bob, Charlie

# f-strings - easiest way to build strings
name = "Alice"
score = 95
print(f"{name} scored {score}%")   # Alice scored 95%
Index starts at 0 Strings are immutable f"..." for formatting
📋
Lists/Arrays
Store multiple items in a single variable
colours = ["red", "green", "blue"]

# Access items by index - counting starts at 0
print(colours[0])     # red
print(colours[1])     # green
print(colours[-1])    # blue  (last item)

# Change, add, and remove items
colours[0] = "orange"         # change
colours.append("purple")      # add to end
colours.remove("green")       # remove by value
colours.insert(1, "yellow")   # insert at position

# Useful list operations
print(len(colours))           # number of items
print("blue" in colours)      # True or False
colours.sort()                # sort alphabetically

# Loop through every item
for colour in colours:
    print(colour)
Index starts at 0 -1 = last item Square brackets [ ]
🗃️
2D Lists/Arrays
A list of lists - like a grid or table
# A 2D list is a list where each item is also a list
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access with [row][column] - both start at 0
print(grid[0][0])   # 1  (row 0, col 0)
print(grid[1][2])   # 6  (row 1, col 2)
print(grid[2][1])   # 8  (row 2, col 1)

# Change a value
grid[0][0] = 99
print(grid[0])      # [99, 2, 3]

# Loop through every row and column
for row in grid:
    for item in row:
        print(item, end=" ")
    print()         # new line after each row

# Useful for things like: seating plans, game boards,
# exam mark grids, pixel colours in images
[row][col] to access Both indexes start at 0 Nested for loops to iterate
⚙️
Methods - Procedures
A named block of code that does something but returns nothing
# A procedure does a job - it has NO return value
# Define with def, call by name

def greet(name):
    print("Hello,", name + "!")

def print_line(char="-", length=20):
    print(char * length)

def display_score(player, score):
    print_line()
    print(f"Player: {player}")
    print(f"Score:  {score}")
    print_line()

# Call each procedure
greet("Alice")           # Hello, Alice!
greet("Bob")             # Hello, Bob!
display_score("Alice", 95)

# Procedures are great for repetitive output tasks
# They change things (print, modify lists) but return None
No return statement def to define Call with ()
🔧
Methods - Functions
A named block of code that calculates and returns a value
# A function computes something and returns the result
# The caller stores or uses the returned value

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

def is_even(n):
    return n % 2 == 0

def clamp(value, low, high):
    return max(low, min(value, high))

# Parameters can have default values
def power(base, exponent=2):
    return base ** exponent

# Use the returned values
result = add(3, 4)
print(result)             # 7
print(is_even(9))         # False
print(clamp(150, 0, 100)) # 100  (capped at maximum)
print(power(3))           # 9
print(power(2, 10))       # 1024
return sends value back Store result in a variable Default params use =
📁
File Handling
Read from and write to files
# Write to a file (creates it if it doesn't exist)
with open("scores.txt", "w") as f:
    f.write("Alice: 95\n")
    f.write("Bob: 82\n")

# Read the whole file
with open("scores.txt", "r") as f:
    contents = f.read()
    print(contents)

# Read line by line
with open("scores.txt", "r") as f:
    for line in f:
        print(line.strip())   # strip removes \n

# Append to an existing file
with open("scores.txt", "a") as f:
    f.write("Charlie: 91\n")
"w" write (overwrites) "r" read "a" append

Common Functions

print()
Displays values to the console.
Use whenever you want to show output - text, numbers, or variable values.
print("Hello, world!") print("Score:", 95) print("Name:", name, "Age:", age)
input()
Pauses and asks the user to type something. Always returns text.
Use when your program needs information from the user. Wrap in int() or float() if you need a number.
name = input("What is your name? ") age = int(input("How old are you? ")) print("Hello,", name, "- you are", age)
int()
Converts a value to a whole number (integer).
Use after input() when you need to do maths with the result - input() always gives text.
age = int(input("Enter your age: ")) score = int("42") # 42 print(age + 1)
float()
Converts a value to a decimal number.
Use when you need decimal precision - e.g. prices, temperatures, averages.
price = float(input("Price: ")) print(price * 1.2) # add 20% tax pi = float("3.14159")
str()
Converts a value to text (a string).
Use when you want to join a number to a string using + (you can't mix types directly).
score = 95 message = "Your score: " + str(score) print(message) # Your score: 95
ord() / chr()
ord() converts a character to its ASCII number; chr() does the reverse.
Use for encryption/cipher tasks, checking if a character is a letter, or shifting characters (e.g. Caesar cipher).
print(ord("A")) # 65 print(ord("a")) # 97 print(chr(65)) # A print(chr(66)) # B # Caesar cipher - shift each letter by 1 letter = "H" shifted = chr(ord(letter) + 1) print(shifted) # I
.upper() / .lower()
Returns a copy of the string in ALL CAPS or all lowercase.
Use .lower() when comparing user input so "YES", "Yes", and "yes" all match.
answer = input("Continue? ").lower() if answer == "yes": print("Great!") print("LOUD".lower()) # loud
type()
Returns the data type of a value.
Use when debugging - it tells you whether something is a string, int, float, list, etc.
print(type(42)) # <class 'int'> print(type("hi")) # <class 'str'> print(type([1,2])) # <class 'list'>
len()
Returns how many items are in a string or list.
Use to count characters, check if a list is empty, or loop a dynamic number of times.
print(len("hello")) # 5 names = ["Alice", "Bob", "Charlie"] print(len(names)) # 3
range()
Generates a sequence of numbers.
Use with for loops to repeat code a set number of times, or to generate number sequences.
range(5) # 0 1 2 3 4 range(1, 6) # 1 2 3 4 5 range(0, 10, 2) # 0 2 4 6 8
round()
Rounds a decimal to the nearest whole number or to a given number of decimal places.
Use when displaying money, percentages, or any decimal that needs tidying up.
round(3.7) # 4 round(3.14159, 2) # 3.14 round(9.005, 2) # 9.0
.append()
Adds one item to the end of a list.
Use to build up a list gradually - e.g. collecting answers or scores during a loop.
scores = [] scores.append(85) scores.append(92) print(scores) # [85, 92]
.split()
Splits a string into a list of words (or parts split by a chosen character).
Use to break up text input - e.g. first and last name entered in one go.
full = "Alice Smith" parts = full.split() # split on spaces print(parts[0]) # Alice print(parts[1]) # Smith csv = "a,b,c".split(",") # ['a','b','c']
min()
Returns the smallest value from a sequence or from several arguments.
Use to find the lowest score, shortest word, or minimum number - the mirror image of max().
print(min(3, 7, 2, 9, 1)) # 1 scores = [45, 82, 67, 91, 58] print(min(scores)) # 45 words = ["cat", "elephant", "dog"] print(min(words, key=len)) # cat
max()
Returns the largest value from a sequence or from several arguments.
Use to find the highest score, the longest word, or the biggest number without writing a loop.
print(max(3, 7, 2, 9, 1)) # 9 scores = [45, 82, 67, 91, 58] print(max(scores)) # 91 words = ["cat", "elephant", "dog"] print(max(words, key=len)) # elephant
import
Loads a module (a library of extra functions) so you can use it in your program.
Use at the very top of your file whenever you need something not built in - e.g. random numbers, maths functions, or time.
import random import math print(random.randint(1, 10)) # random int 1–10 print(random.choice(["a","b"])) # random item print(math.sqrt(16)) # 4.0 print(math.pi) # 3.14159...
open() - read
Opens a file for reading; f.read() gets all the contents as a string. Always close the file when done.
Use to load saved data - scores, names, settings. Remember to call f.close() or the file stays locked.
f = open("scores.txt", "r") contents = f.read() print(contents) f.close() # Read line by line instead f = open("scores.txt", "r") for line in f: print(line.strip()) # strip removes \n f.close()
open() - write
Opens a file for writing ("w") or appending ("a"). "w" overwrites; "a" adds to the end. Always close when done.
Use "w" to save fresh results; use "a" to add new entries without losing existing ones. Call f.close() when finished.
f = open("scores.txt", "w") f.write("Alice: 95\n") f.write("Bob: 82\n") f.close() # Append - adds to existing file without erasing it f = open("scores.txt", "a") f.write("Charlie: 91\n") f.close()
VoxelForge Coding Lab -; Python Reference -; by Doxel Studio