Past Lesson Note

This note is from 3 weeks ago. You're viewing content from a previous lesson.

Daily Note for September 30, 2026 Past Lesson

We are done with basic programming. 

We will have a test for basic programming on Friday. On the test: 

 

Lesson 3: Make your button do something

Time: 60 minutes

Last lesson, you built an HTML page for your generator. It displayed an interface, but clicking on it did not make your Python code run. Today, you will add a button and a small JavaScript file so that clicking the button asks Flask for a new result and shows it on the page.

HTML describes what is on the page. JavaScript runs in the browser and makes the page do things.

By the end of this lesson, you should be able to:

  • Restart your Flask application using its virtual environment.

  • Add a button and a result area to your page using the id attribute.

  • Link a JavaScript file to your HTML page.

  • Use fetch to get data from a Python route and show it on the page.

  • Use the browser console to find and fix a JavaScript error.

 

Step 2: Restart your application – 5 minutes

2.1 Open your existing my_first_web_app folder in VS Code.

2.2 Open Terminal → New Terminal.

2.3 Activate your environment.

On macOS:

source .venv/bin/activate

On Windows (Command Prompt):

.venv\Scripts\activate.bat

2.4 Start Flask:

python -m flask --app app run --debug

2.5 Open your page from last lesson:

http://127.0.0.1:5000/static/index.html

If you used port 5001 last lesson, use 5001 in every address today.

Checkpoint: Your HTML page from Lesson 2 opens in the browser.

 


 

Step 3: Add a button and a result area – 10 minutes

3.1 Open static/index.html.

3.2 Add a button and a result paragraph under your welcome paragraph. Add a <script> line just before </body>. Your whole file should now look like this. Keep your own personalised text.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Generator</title>
</head>
<body>
    <h1>My Generator</h1>

    <p>Welcome! This application generates random fantasy items.</p>

    <button id="generate-button">Generate</button>

    <p id="result">Press the button to generate an item.</p>

    <h2>Example results</h2>

    <ul>
        <li>Ancient Sword</li>
        <li>Rusty Shield</li>
        <li>Glowing Staff</li>
    </ul>

    <p><a href="/api/generate">Open the generator data</a></p>

    <script src="/static/script.js"></script>
</body>
</html>

3.3 Save the file and refresh your browser. You should see a Generate button.

3.4 Click the button. Nothing happens yet. That is expected.

New code Purpose
<button id="generate-button"> Creates a button. The id gives it a unique name so JavaScript can find it.
<p id="result"> A paragraph where the generated result will appear.
<script src="/static/script.js"> Tells the browser to load and run a JavaScript file. We have not written it yet.

Checkpoint: Your page shows a Generate button. Tell your partner why clicking it does nothing yet.

 


 

Step 4: Connect the button with JavaScript – 15 minutes

4.1 Inside the static folder, create a new file named script.js. It sits next to index.html.

File or folder Location
app.py Inside my_first_web_app
static Inside my_first_web_app
index.html Inside static
script.js Inside static

4.2 Enter the following code in script.js:

const button = document.getElementById("generate-button");
const result = document.getElementById("result");

async function generate() {
    const response = await fetch("/api/generate");
    const data = await response.json();
    result.textContent = JSON.stringify(data);
}

button.addEventListener("click", generate);

4.3 Save the file.

4.4 Do a hard refresh in your browser: Cmd + Shift + R on macOS, Ctrl + Shift + R on Windows. This makes the browser load your newest script.js instead of an old saved copy.

4.5 Click Generate several times. The result paragraph should change each time.

Read the code line by line:

Code What it does
document.getElementById("generate-button") Finds the element on the page with that id. We store it in a variable called button.
async function generate() Defines a function. async means it is allowed to wait for things, like a reply from Flask.
await fetch("/api/generate") Sends a request to your Python route and waits for the reply.
await response.json() Turns the JSON reply into data JavaScript can use.
result.textContent = ... Replaces the text inside the result paragraph.
button.addEventListener("click", generate) Tells the browser: when the button is clicked, run generate.

Notice the path: the user clicks the button, JavaScript asks Flask, Flask runs your Python function, and the JSON comes back to the page. The same Python function you wrote in Lesson 1 is doing the work.

Checkpoint: Clicking Generate shows new JSON on your page without reloading it. Point to the line of JavaScript that talks to Python.

 


 

Step 5: Show only the value you want – 5 minutes

Right now your page shows raw JSON, for example:

{"item": "Glowing Staff"}

The word before the colon is the key. The text after it is the value. Your key might be different from item.

5.1 Click Generate and read your JSON. Find your key.

5.2 In script.js, change this line:

result.textContent = JSON.stringify(data);

to this, using your key in place of item:

result.textContent = data.item;

5.3 Save, hard refresh, and click Generate.

If your page shows undefined, the key in your JavaScript does not match the key in your JSON. Check the spelling and capital letters.

Checkpoint: Your page shows only the generated value, such as Glowing Staff.

 


 

Step 6: Break it on purpose – 5 minutes

When JavaScript fails, the page often just does nothing. The browser console tells you why.

6.1 In script.js, change "generate-button" to "generate-btn". Save and hard refresh.

6.2 Click Generate. Nothing happens.

6.3 Open the console. In Chrome: View → Developer → JavaScript Console. In Safari: Develop → Show JavaScript Console.

6.4 Read the red error message. Find the file name and line number it mentions.

6.5 Change the id back to "generate-button", save, and hard refresh. Check that the button works again.

Checkpoint: Explain to your partner why a spelling mistake in an id stops the button from working.

 


 

Step 7: Practice quiz – 10 minutes

Work alone first. Write your answers on paper, then check them with the answer key. These questions are like the ones on Friday's test.

 

Question 1 (Variables, input and output)

age = input("Enter your age: ")
next_year = age + 1
print(next_year)

The user types 14. What happens?

A. It prints 15
B. It prints 141
C. It causes an error
D. It prints 14 1

 

Question 2 (Conditionals)

score = 75

if score >= 90:
    print("A")
elif score >= 70:
    print("B")
elif score >= 50:
    print("C")
else:
    print("D")

What is printed?

A. B
B. B and C
C. C
D. D

 

Question 3 (Conditionals - advanced)

temperature = 18
raining = True

if temperature > 15 and not raining:
    print("Go to the park")
elif temperature > 15 or raining:
    print("Visit the museum")
else:
    print("Stay home")

What is printed?

A. Go to the park
B. Visit the museum
C. Stay home
D. Nothing is printed

 

Question 4 (Lists)

colours = ["red", "green", "blue"]
colours.append("yellow")

print(colours[1])
print(len(colours))

What is printed?

A. red then 3
B. red then 4
C. green then 3
D. green then 4

 

Question 5 (Loops)

numbers = [3, 8, 2, 5]
total = 0

for n in numbers:
    if n > 4:
        total = total + n

print(total)

What is printed?

A. 18
B. 13
C. 8
D. 5

 

Show the answer key

Question 1: C. input() always gives back a string. Python cannot add the string "14" and the number 1, so it raises a TypeError. To fix it: age = int(input("Enter your age: ")).

Question 2: A. Python checks each condition from the top. 75 >= 90 is false. 75 >= 70 is true, so it prints B and skips every other branch. Only one branch of an if/elif/else chain ever runs.

Question 3: B. temperature > 15 is true, but not raining is false, so the and is false. In the elif, or needs only one side to be true, so it prints Visit the museum.

Question 4: D. List positions start at 0, so colours[1] is "green". append adds "yellow" to the end, so the list now has 4 items.

Question 5: B. Only 8 and 5 are greater than 4, so total becomes 0 + 8 + 5 = 13. The print is outside the loop, so it runs once at the end.

Checkpoint: Circle any question you got wrong. Review that topic using the links at the top of this page before Friday.

 


 

Step 8: Exit check – 5 minutes

Answer these in one or two sentences each:

8.1 In Lesson 2, your page displayed an interface. What did you add today that made it perform an action?

8.2 Put these in order: Flask runs your Python function, the user clicks the button, the page shows the result, JavaScript sends a request.

8.3 Which test topic do you most need to review before Friday?

Next lesson, we will style your page so it looks like a real application.