← Teacher guide

A quiz with a scoreboard

Students save quiz scores to a SQLite file and show the top scores in a table: INSERT with ?, ORDER BY and LIMIT for the scoreboard, then GROUP BY for each player's best.

Apps with Gradio · A quiz app · about 35 minutes · Open the student lesson

Classroom resources

Open these in Waypoints Prepare with one click. To share a file another way, copy its address and paste it into Load URL, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.

Students will be able to

Timing

Predict and Run 10 min · Investigate 7 min · Modify and Make 18 min

Before class

Optional extension for students who have done SQL lessons 1 to 8 and the Gradio quiz. scores.db is a real SQLite file kept in the browser with the course's files, so the scoreboard survives Run and a reload. The scoreboard table is a pandas DataFrame built from the rows, as in Data detective. The Make step is the GROUP BY idea from SQL lesson 5, now inside an app.

Running the lesson

  1. Predict: ask for the order before anyone runs it. The wrong options mix up ascending order and the LIMIT.
  2. Run: pairs play as each other and watch the table fill. Press Run again to show the scores survive.
  3. Make: let students find the cheating problem first (play five times as the same name), then fix it.

In class

On the slides at these points. Students can do the whole lesson on their own; these are for the room. In the deck, the Run, Modify and Make slides have the live playground in them (the tutorial link is the backup), and the notes above are in each slide's speaker notes.

The hard part (on purpose)

Seeing which part is SQL and which is Python. Colour the SQL strings in one colour.

When students get stuck

What you will seeA question to askThe fix
The scoreboard is empty.Have you pressed Submit with a name typed?A row is only saved when the quiz is submitted.
A column error from the database.What are the columns called in the scores table?They are name, score and id.
The old scores are in the way.Which file holds the scores?Delete scores.db in the Files tab and run again.

Answers to the checks

  1. Predict: What does it print?
    Sam, then Ada. ORDER BY score DESC puts the highest score first, and LIMIT 2 keeps the first two rows.
  2. Ties: Two players both score 3. Why does `, id` come after `score DESC`?
    The earlier score goes first
    It puts the player who finished first above the other. id goes up as each score is saved, so for equal scores the smaller id (the earlier attempt) comes first.
  3. Why a database?: What would happen to the scoreboard if the scores were kept in a list inside the program instead?
    It would be empty again every time the app started
    A list lives in memory while the program runs. A database file lives on until you delete it.

Solutions

One possible solution for each task. Other correct programs are fine.

Modify

import sqlite3
import gradio as gr
import pandas as pd

questions = [
    {"q": "Which planet is closest to the Sun?", "choices": ["Venus", "Mercury", "Mars"], "answer": "Mercury"},
    {"q": "How many legs does a spider have?", "choices": ["6", "8", "10"], "answer": "8"},
    {"q": "What is 7 x 8?", "choices": ["54", "56", "64"], "answer": "56"},
]


def db():
    conn = sqlite3.connect("scores.db")
    conn.execute("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
    return conn


def top_scores():
    conn = db()
    rows = conn.execute("SELECT name, score FROM scores ORDER BY score DESC, id LIMIT 3").fetchall()
    conn.close()
    return pd.DataFrame(rows, columns=["Name", "Score"])


def mark(name, a1, a2, a3):
    answers = [a1, a2, a3]
    score = 0
    for i in range(len(questions)):
        if answers[i] == questions[i]["answer"]:
            score = score + 1
    conn = db()
    conn.execute("INSERT INTO scores (name, score) VALUES (?, ?)", (name, score))
    conn.commit()
    conn.close()
    return str(score) + " out of " + str(len(questions)), top_scores()


inputs = [gr.Textbox(label="Your name")]
for q in questions:
    inputs.append(gr.Radio(q["choices"], label=q["q"]))

gr.Interface(
    fn=mark,
    inputs=inputs,
    outputs=[gr.Textbox(label="Score"), gr.Dataframe(label="Top scores")],
    title="Quick quiz with a scoreboard",
).launch()

Make

import sqlite3
import gradio as gr
import pandas as pd

questions = [
    {"q": "Which planet is closest to the Sun?", "choices": ["Venus", "Mercury", "Mars"], "answer": "Mercury"},
    {"q": "How many legs does a spider have?", "choices": ["6", "8", "10"], "answer": "8"},
    {"q": "What is 7 x 8?", "choices": ["54", "56", "64"], "answer": "56"},
]


def db():
    conn = sqlite3.connect("scores.db")
    conn.execute("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
    return conn


def top_scores():
    conn = db()
    rows = conn.execute("SELECT name, MAX(score) FROM scores GROUP BY name ORDER BY MAX(score) DESC LIMIT 5").fetchall()
    conn.close()
    return pd.DataFrame(rows, columns=["Name", "Score"])


def mark(name, a1, a2, a3):
    answers = [a1, a2, a3]
    score = 0
    for i in range(len(questions)):
        if answers[i] == questions[i]["answer"]:
            score = score + 1
    conn = db()
    conn.execute("INSERT INTO scores (name, score) VALUES (?, ?)", (name, score))
    conn.commit()
    conn.close()
    return str(score) + " out of " + str(len(questions)), top_scores()


inputs = [gr.Textbox(label="Your name")]
for q in questions:
    inputs.append(gr.Radio(q["choices"], label=q["q"]))

gr.Interface(
    fn=mark,
    inputs=inputs,
    outputs=[gr.Textbox(label="Score"), gr.Dataframe(label="Top scores")],
    title="Quick quiz with a scoreboard",
).launch()

Stretch and support

Stretch: Add a column for the time of the attempt using datetime('now').

Support: Give the SELECT and ask for the change to the LIMIT.

Exit ticket

Why does the quiz save scores in a database instead of a list?

A list disappears when the program stops. A database file keeps the scores between runs.

What each step is for

Where it leads

Next: on to machine learning, or back to the Flask course for a web version.