Different homeworks for the students with pure Python

We are going to use Python (download it at python.org) and its built in module to create a GUI (graphic user interface) tkinter.

Let’s check out this code I did earlier to see if I can modify it to do different, random, exercises for many students, also with the solutions, just writing one exercise and nothing more. So, from one exercise you can get infinite exercise for as many students as you want, getting the result calculated by the computer.

In the example we will make exercises to calcultate the amount of euro you can get from an amount of dollars and viceversa.

The process is this:

The code

from random import choice
import tkinter as tk


print("(c) https://pythonprogramming.altervista.org Giovanni Gatto 2019")


def test_maker(counter):
    # =================== 1 Exercises for all ===============
    solutions = ""
    template = "How many dollars you can get for 100 € at a eur/usd of 1.10?\n" * 20
    template = template.splitlines()
    # ALTERNATIVE WORDS
    ch1 = ["dollars", "euro"]
    # Money you change
    ch2 = [2000, 3000, 4000, 250, 500, 700, 800, 950, 560, 355, 125]
    ch3 = [1.1, 1.2, 0.9, 1.3, .98, 1.05, 0.85, .8]
    # ================= Exercises generator from template
    # substituting randomly the words
    for n, frase in enumerate(template):
        # THIS REPLACE 'ACQUISTATE MERCI'
        money_to_get = choice(ch1)
        template[n] = str(n + 1) + ") " + template[n].replace(
            "dollars", money_to_get)
        # THIS REPLACE 1.500
        money = str(choice(ch2))
        val = "$" if money_to_get == "euro" else "€"
        template[n] = template[n].replace("100 €", money + " " + val)
        # The exchange rate
        exchange = str(choice(ch3))
        template[n] = template[n].replace("1.10", exchange)
        template[n] = template[n] + "\n"
        result = round((int(money)*float(exchange)) if money_to_get=="dollars" else (int(money)/float(exchange)), 2)
        solutions += "[" + str(n + 1) + "=" + str(result) + "]"
        # template[n] = template[n] + "Result: " + str(result) + "\n"
    # ===================== Create the text joining the list of exercises =====
    x = "".join(template)
    text.insert("1.0", str(counter) + ")\n" + x + "\n\n")
    text.insert("1.0", str(counter) + ") " + solutions + "\n\n\n")
    return x


def clear():
    text.delete("1.0", tk.END)


def works():
    for x in range(24):
        test_maker(x)


root = tk.Tk()
root.title("Testmkr 2.0")
menu = tk.Menu(root)
menu.add_command(label="Clear", command=clear)
menu.add_command(label="Generate", command=works)
root.config(menu=menu)
text = tk.Text(root, wrap=tk.WORD)
text.pack(fill=tk.BOTH, expand=1)
root.mainloop()

Live coding video about exercise with Python and tkinter

Utilities