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.
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.
Predict and Run 10 min · Investigate 7 min · Modify and Make 18 min
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.
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.
Pairs play for the top score. Then they try to cheat the board by replaying, and fix the query so it cannot be filled by one player.
Seeing which part is SQL and which is Python. Colour the SQL strings in one colour.
| What you will see | A question to ask | The 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. |
One possible solution for each task. Other correct programs are fine.
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()
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: Add a column for the time of the attempt using datetime('now').
Support: Give the SELECT and ask for the change to the LIMIT.
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.
Next: on to machine learning, or back to the Flask course for a web version.