← All tools

Programming Concepts – Part 3

SQL & databases, file handling, and sub-programs — with key meanings, a look at the Pets table, and three separate timed challenges (one for each topic): build an SQL query, a file handling quiz, and a sub-programs matching game. Help with the extension challenges is at the bottom.

Key Meanings

The important terms from this lesson, grouped by topic.

Storing Data & Keys

Table
Data stored in a program as rows (records) and columns (fields), just like a spreadsheet.
Field
A single column in a table — every value in a field has the same data type.
Record
A single row in a table — one complete set of data, e.g. one pet.
Primary key
A field that is unique to each record, used to find one exact record — e.g. Pet_id.
Secondary key
Any other field in the table that isn't the primary key.

SQL Basics

SQL
Structured Query Language — used to create, update and search (query) a database.
CREATE TABLE
Builds a brand new, empty table with named fields and data types.
INSERT INTO ... VALUES
Adds a new record (row) to an existing table.
SELECT ... FROM
Fetches data from a table — SELECT * fetches every field.
UPDATE ... SET
Changes the value of a field in an existing record.

Filtering & Sorting with SQL

WHERE
Filters the records returned, based on a condition — e.g. WHERE Weight > 20.
AND / OR
Combines two conditions in a WHERE clause — AND needs both true, OR needs either.
LIKE
Searches for a pattern inside text — e.g. LIKE "%a" looks for names containing "a".
ORDER BY
Sorts the results — e.g. by weight, smallest (ascending) to biggest.

File Handling

File handling
Reading or writing data to a file outside the program's own code — e.g. saving results to a text file.
open()
Opens a file ready for reading or writing — creates it first if it doesn't exist yet.
"a" (append mode)
Adds new data to the end of the file, keeping what's already there.
"w" (write mode)
Opens the file for writing — this erases any existing content first.
write() / close()
write() adds a line of data; close() closes the file so it saves properly.

Sub-Programs

Sub-program
A named, reusable block of code that can be called instead of writing the same code out again.
Procedure
Takes zero, one or more parameters and carries out a task, but doesn't return a value.
Function
Takes zero, one or more parameters and carries out a task, then returns a value.
Parameter / Argument
A parameter is the named placeholder in the sub-program's definition; an argument is the actual value passed in when it's called.
Local / Global variable
A local variable only exists inside the sub-program it was created in; a global variable can be used anywhere in the program.

The Pets Table

Every SQL example on this page — and every question in the Build the Query challenge below — uses this table. Pet_id is the primary key: it's the one field guaranteed to be unique to each record, so it's always the safest way to find one exact pet.

Pet_id Primary key Name Age DOB Weight Neutered
1Clifford51/4/201413.5No
2Claws1015/3/200933.5Yes
3Felix1513/1/200421.2Yes
4Betsy321/6/201515.4Yes

Challenge 1 — SQL: Build the Query

10 SQL commands and clauses, all using the Pets table above. Drag each one (or click one, then click a query) onto the query it completes. The clock starts on your first move.

Drag each SQL fragment onto the query it correctly completes.

Challenge 2 — File Handling Quiz

10 multiple-choice questions on reading and writing files in Python, based on the example below. A timer starts as soon as you press Start, and the answer options are shuffled into a new order every question.

The example this quiz is based on:

name = input("What is your name?: ")
score = input("What score did you get out of 100?: ")

file = open("scores.txt", "a")
file.write(name + "," + score + "\n")

file.close()
print("Done!")

Challenge 3 — Sub-Programs: Match the Output

3 small Python sub-programs. Drag each output (or click one, then click a sub-program) onto the code it belongs to. The clock starts on your first move.

Drag each output onto the sub-program that produces it.

Challenge Help

Stuck on one of the Python extension challenges? Expand a hint below — the example code is there to check your work against once you've had a proper go yourself, not to copy and paste (the code can't be selected or copied).

Challenge 1 — Flip Two Coins

Flip 2 coins 100 times. Both heads — win £20. Both tails — lose £10. One of each — lose £5. Keep a running total.

Tips

  • Import random and use random.choice(["Heads", "Tails"]) for each coin.
  • A for loop with range(100) repeats the flip 100 times.
  • Use elif to check "both tails" separately from "one of each", and a running total variable that starts at 0.
Show example
import random

balance = 0

for i in range(100):
    coin1 = random.choice(["Heads", "Tails"])
    coin2 = random.choice(["Heads", "Tails"])

    if coin1 == "Heads" and coin2 == "Heads":
        balance = balance + 20
    elif coin1 == "Tails" and coin2 == "Tails":
        balance = balance - 10
    else:
        balance = balance - 5

print("Final balance after 100 flips: £" + str(balance))

Challenge 2 — Quiz Game with File Handling

Make a quiz game using random numbers. Keep track of the score, then write the player's name and score to a text file — this is where file handling from earlier comes in.

Tips

  • Use random.randint(1, 10) to generate two numbers for each question.
  • Compare the player's answer to the real answer with == and add to a score variable.
  • After the loop, open() a file in "a" mode, write() the name and score, then close() it.
Show example
import random

name = input("What is your name? ")
score = 0

for i in range(5):
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    answer = int(input(str(num1) + " x " + str(num2) + " = "))
    if answer == num1 * num2:
        print("Correct!")
        score = score + 1
    else:
        print("Wrong — it was " + str(num1 * num2))

print("Final score: " + str(score) + "/5")

file = open("quiz_scores.txt", "a")
file.write(name + "," + str(score) + "\n")
file.close()

Challenge 3 — List of Names

Create a list of names using a for loop, storing each one in a list (array). Let the user choose a number from the list to read a name back out.

Tips

  • Start with an empty list names = [], then .append() each new name inside the loop.
  • Lists are indexed from 0, not 1 — the first item is names[0].
  • Cast the user's chosen number to int() before using it as an index.
Show example
names = []

for i in range(5):
    new_name = input("Enter a name: ")
    names.append(new_name)

choice = int(input("Pick a number from 0 to 4: "))
print("You chose: " + names[choice])

Challenge 4 — Sub-Program for Pythagoras

Use a sub-program (function) to calculate the hypotenuse using Pythagoras' theorem, when the user gives two side lengths as input.

Tips

  • Import math so you can use math.sqrt(), or use ** 0.5 instead.
  • The function takes two parameters (the two sides) and returns the result — that makes it a function, not a procedure.
  • Cast the user's inputs to float(), since side lengths can have decimals.
Show example
import math

def pythagoras(a, b):
    c = math.sqrt(a ** 2 + b ** 2)
    return c

side1 = float(input("Enter the first side length: "))
side2 = float(input("Enter the second side length: "))

hypotenuse = pythagoras(side1, side2)
print("The hypotenuse is: " + str(hypotenuse))

Challenge 5 — Noughts and Crosses Board

Use a 2D array (a list of lists) to store a 3×3 noughts and crosses board, and let the player mark a square.

Tips

  • A 2D array is a list where each item is itself a list — one inner list per row.
  • Use a nested for loop (a loop inside a loop) to print every row of the board.
  • Access one square with two indexes: board[row][col].
Show example
board = [["-", "-", "-"],
         ["-", "-", "-"],
         ["-", "-", "-"]]

def print_board():
    for row in board:
        print(" ".join(row))

print_board()

row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
board[row][col] = "X"

print_board()