← Apps with Gradio

A quiz with a scoreboard

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.

How this lesson works: Predict, Run, Investigate, Modify, Make
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

quiz.py
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])
What does it print?

RunRun it and compare the result with your prediction.

Run

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
quiz.py
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()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

quiz.py
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?

Two players both score 3. Why does `, id` come after `score DESC`?

What would happen to the scoreboard if the scores were kept in a list inside the program instead?

ModifyChange the code on purpose and check the result.

Modify

Change the scoreboard so it shows only the top three scores.

Try it yourselfYour edits are saved in this browser.
Build up to it
Which change makes the scoreboard show the best two scores?

Need a hint?

Before a hint: what kind of stuck is this? Try a strategy first

Look at the LIMIT in top_scores.

Another hint

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.

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Make

    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.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    Before a hint: what kind of stuck is this? Try a strategy first

    You want one row for each player, with their best score.

    Another hint

    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.

      Now you can
      Finished the course?Go over it: Apps with Gradio recapEvery idea in one place, to check you've got it.You reached the endBack to Apps with Gradio
      For teachers

      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.

      Students will be able to

      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.

      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

      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.

      Where it leads

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

      What each step is for