Save every quiz score in a SQLite database, and show the top scores in a table that is still there after the app restarts.
A quiz is more fun when it remembers who got what.
Optional, and it uses the SQL course (lessons 1 to 8 first). It also uses pandas, from Data detective lesson 3: pd.DataFrame(...) turns rows into a table the app can show. Last lesson the quiz marked your answers and forgot you. Now each score is saved in a database file, scores.db, and a scoreboard table shows the best five. The database is the memory: the app asks it in SQL and shows the answer.
Make your prediction first. Help opens once you've locked it in.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE scores (name TEXT, score INTEGER)")
conn.execute("INSERT INTO scores VALUES ('Ada', 2)")
conn.execute("INSERT INTO scores VALUES ('Sam', 3)")
conn.execute("INSERT INTO scores VALUES ('Zoe', 1)")
for row in conn.execute("SELECT name FROM scores ORDER BY score DESC LIMIT 2"):
print(row[0])
Play the quiz as yourself, then as a friend. Press Run again: the scoreboard is still there, because it is stored in scores.db.
| Part | What it does |
|---|---|
db() |
Opens scores.db and makes the table the first time |
INSERT INTO scores ... VALUES (?, ?) |
Saves one attempt |
ORDER BY score DESC, id LIMIT 5 |
The five best, with ties going to whoever played first |
pd.DataFrame(rows, columns=[...]) |
Turns the rows into a table the app can show |
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 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()
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 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()
Two players with the same score.
Where does a list live?
Change the scoreboard so it shows only the top three scores.
Before a hint: what kind of stuck is this? Try a strategy first
Look at the LIMIT in top_scores.
Change LIMIT 5 to LIMIT 3.
Show only the top three scores.
Run your program. This ticks when your code does all of the above.
Right now one player can fill the scoreboard by playing again and again. Change the query so each player appears once, with their best score.
Before a hint: what kind of stuck is this? Try a strategy first
You want one row for each player, with their best score.
SELECT name, MAX(score) FROM scores GROUP BY name ORDER BY MAX(score) DESC LIMIT 5
Show each player once, with their best score.
Run your program. This ticks when your code does all of the above.
Lesson done. You've finished every step you need.
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. About 35 minutes.
Open the teacher guide: answers, solutions, slides and a worksheet.
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.
Seeing which part is SQL and which is Python. Colour the SQL strings in one colour.
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.
Next: on to machine learning, or back to the Flask course for a web version.