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.
The important terms from this lesson, grouped by topic.
Pet_id.SELECT * fetches every field.WHERE Weight > 20.AND needs both true, OR needs either.LIKE "%a" looks for names containing "a".write() adds a line of data; close() closes the file so it saves properly.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 |
|---|---|---|---|---|---|
| 1 | Clifford | 5 | 1/4/2014 | 13.5 | No |
| 2 | Claws | 10 | 15/3/2009 | 33.5 | Yes |
| 3 | Felix | 15 | 13/1/2004 | 21.2 | Yes |
| 4 | Betsy | 3 | 21/6/2015 | 15.4 | Yes |
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.
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!")
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.
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).
Flip 2 coins 100 times. Both heads — win £20. Both tails — lose £10. One of each — lose £5. Keep a running total.
Tips
random and use random.choice(["Heads", "Tails"]) for each coin.for loop with range(100) repeats the flip 100 times.elif to check "both tails" separately from "one of each", and a running total variable that starts at 0.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))
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
random.randint(1, 10) to generate two numbers for each question.== and add to a score variable.open() a file in "a" mode, write() the name and score, then close() it.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()
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
names = [], then .append() each new name inside the loop.names[0].int() before using it as an index.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])
Use a sub-program (function) to calculate the hypotenuse using Pythagoras' theorem, when the user gives two side lengths as input.
Tips
math so you can use math.sqrt(), or use ** 0.5 instead.float(), since side lengths can have decimals.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))
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
for loop (a loop inside a loop) to print every row of the board.board[row][col].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()