Lesson 4: Connecting Some Dots
Day 4: Bridging Python and HTML
Today, students connected two major parts of the course for the first time: Python programming and HTML webpages.
Until now, we had mostly treated these as separate topics. HTML was used to describe the structure of a webpage, while Python was used to work with variables, lists, loops, conditions, and functions.
In this class, we combined those ideas by using Python to generate HTML text and save it as a webpage.
There were several relationships happening at once, and many students found the complete flow difficult to follow at first. That is normal. To make those relationships easier to see, some of the examples in this article are colour-coded.
Colour guide used in this article:
- Blue represents collections of data and function names.
- Red represents one individual value being processed.
- Orange represents generated content being collected.
- Green represents HTML stored as text.
- Purple represents important Python keywords.
The Central Idea: HTML Is Text
The most important idea from today is that an HTML document is ultimately a text file.
A browser gives that text a special meaning because it recognizes HTML elements such as <h1>, <p>, and <ul>.
Python does not need to draw the webpage itself. Python only needs to produce correctly written HTML text. The browser can then interpret and display it.
message = "Hello"
html = "<p>" + message + "</p>"
print(html)
The program produces this text:
<p>Hello</p>
When that text is placed in an HTML file and opened in a browser, it appears as a paragraph.
Creating an HTML File With Python
We started with a complete HTML document stored inside a Python string.
Triple quotation marks allow us to create a string that continues across several lines:
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This HTML file was created using Python.</p>
</body>
</html>
"""
Although the string contains HTML, Python still treats the entire value as text.
We then wrote that text into a file:
with open("index.html", "w", encoding="utf-8") as file:
file.write(html_content)
print("HTML file saved successfully!")
Understanding open()
The open() function gives Python access to a file.
open("index.html", "w", encoding="utf-8")
- "index.html" is the name of the file we want to create or open.
- "w" means write mode. Python will create the file if it does not exist, or replace its contents if it already exists.
- encoding="utf-8" allows the file to correctly store a wide range of letters, symbols, and characters.
The following line writes the generated text into the file:
file.write(html_content)
After the program runs, we can find index.html in the project directory and open it with a browser.
Generating HTML From Lists
We then used lists containing names, ages, temperatures, and attendance values.
For example, we can store several temperatures in a single list:
temperatures = [21.5, 19.8, 23.1, 18.7, 20.4]
The name temperatures represents the complete collection.
A loop lets us visit each temperature individually:
for temperature in temperatures:
print(temperature)
During each pass through the loop, temperature represents one value from the list.
| Loop pass | Value stored in temperature |
|---|---|
| First pass | 21.5 |
| Second pass | 19.8 |
| Third pass | 23.1 |
| Fourth pass | 18.7 |
| Fifth pass | 20.4 |
Turning Each Value Into HTML
Instead of only printing the numbers, we placed each value inside an HTML paragraph:
temperatures = [21.5, 19.8, 23.1, 18.7, 20.4]
for temperature in temperatures:
html = "<p>Temperature: " + str(temperature) + "°C</p>"
print(html)
The loop produces:
<p>Temperature: 21.5°C</p>
<p>Temperature: 19.8°C</p>
<p>Temperature: 23.1°C</p>
<p>Temperature: 18.7°C</p>
<p>Temperature: 20.4°C</p>
Each temperature becomes part of a separate HTML paragraph.
Why We Used str()
The temperatures are numbers, but the HTML around them is text.
Python will not directly join a number and a string with the plus operator. We used str() to create a text version of each number:
str(temperature)
This lets Python join the temperature to the HTML string.
Collecting Generated HTML
Printing each HTML element is useful for demonstrating the result, but we usually want to collect all of the elements into one larger block.
ages = [14, 16, 15, 17, 13]
bodyContent = ""
for age in ages:
bodyContent += "<p>Age: " + str(age) + "</p>"
The variable bodyContent begins as an empty string:
bodyContent = ""
Every time the loop runs, another HTML paragraph is added to the end.
The += operator is a shorter way of writing:
bodyContent = bodyContent + new_content
We can think of this as gradually assembling the body of the page:
- Begin with an empty string.
- Create one HTML element.
- Add that element to the string.
- Repeat for every item in the list.
Generating an HTML List
We also used a Python list to generate an HTML unordered list.
student_names = [
"Alice",
"Brandon",
"Carlos",
"Diana",
"Ethan"
]
listItems = ""
for student in student_names:
listItems += "<li>" + student + "</li>"
bodyContent = "<ul>" + listItems + "</ul>"
This generates:
<ul>
<li>Alice</li>
<li>Brandon</li>
<li>Carlos</li>
<li>Diana</li>
<li>Ethan</li>
</ul>
If our Python list contained one hundred names, the same loop could generate one hundred HTML list items. We would not need to write each element manually.
Creating an HTML Boilerplate Function
A complete webpage contains a repeated outer structure:
- The document declaration
- The opening and closing HTML elements
- The head
- The body
Instead of rewriting that structure every time, we created a reusable helper function called htmlBoiler().
The function accepts two parameters:
- headContent contains the information placed inside the page's head.
- bodyContent contains the visible page content.
def htmlBoiler(headContent, bodyContent):
return f"""<!DOCTYPE html>
<html>
<head>
{headContent}
</head>
<body>
{bodyContent}
</body>
</html>"""
The function creates the repeated structure and inserts our custom content into the correct locations.
What Is a Parameter?
A parameter is a named input that a function receives.
In this function:
def htmlBoiler(headContent, bodyContent):
headContent and bodyContent are placeholders. Their actual values are supplied when we call the function.
What Does return Do?
The return keyword sends a result back to the part of the program that called the function.
Our function does not immediately print or save the page. It creates the page and returns the finished string so we can decide what to do with it.
Calling the Function
First, we create the changing parts of the page:
headContent = "<title>Student Ages</title>"
bodyContent = "<h1>Student Ages</h1>"
ages = [14, 16, 15, 17, 13]
for age in ages:
bodyContent += "<p>Age: " + str(age) + "</p>"
Then we pass those two values into the function:
completePage = htmlBoiler(
headContent,
bodyContent
)
The returned value is stored in completePage.
The relationship can be summarized like this:
headContent ────────┐
│
▼
htmlBoiler() ──────► Complete HTML document
▲
│
bodyContent ────────┘
Putting the Entire Program Together
The following example combines the list, loop, helper function, and file-writing operation:
def htmlBoiler(headContent, bodyContent):
return f"""<!DOCTYPE html>
<html>
<head>
{headContent}
</head>
<body>
{bodyContent}
</body>
</html>"""
temperatures = [21.5, 19.8, 23.1, 18.7, 20.4]
headContent = "<title>Temperatures</title>"
bodyContent = "<h1>Recorded Temperatures</h1>"
for temperature in temperatures:
bodyContent += "<p>Temperature: " + str(temperature) + "°C</p>"
completePage = htmlBoiler(headContent, bodyContent)
with open("index.html", "w", encoding="utf-8") as file:
file.write(completePage)
print("HTML file saved successfully!")
This program follows a complete flow:
- A Python list stores the data.
- A loop visits each value.
- Each value is placed inside an HTML element.
- The generated elements are collected in bodyContent.
- The helper function places the content inside a complete HTML document.
- The function returns the completed document.
- Python writes the document into index.html.
- The browser reads and displays the file.
Useful Operations on Lists
The class helper also included several built-in Python functions that can work with lists:
numbers = [8, 3, 12, 5, 9]
print(len(numbers))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
print(sorted(numbers))
| Function | Purpose | Result in this example |
|---|---|---|
len(numbers) |
Counts the values. | 5 |
min(numbers) |
Finds the smallest value. | 3 |
max(numbers) |
Finds the largest value. | 12 |
sum(numbers) |
Adds all the values. | 37 |
sorted(numbers) |
Returns the values in order. | [3, 5, 8, 9, 12] |
These tools can help us process data before placing the result into a webpage.
A Brief Look at Dictionaries
We also looked briefly at a Python dictionary.
A list stores values in an ordered collection. A dictionary stores values using named keys.
student = {
"name": "Alice",
"age": 15,
"grade": 10,
"average": 87.5,
"present": True
}
We can retrieve a particular value using its key:
print(student["name"])
print(student["average"])
We can also loop through a dictionary.
Looping Through Keys
for key in student:
print(key)
Looping Through Values
for value in student.values():
print(value)
Looping Through Keys and Values
for key, value in student.items():
print(key, ":", value)
Dictionaries will become important later because data from databases, forms, APIs, and web applications is often represented using named fields.
How This Relates to Real Websites
We also discussed what happens when a browser requests a file from another computer.
When a person enters a web address, the browser sends a request across a network to another computer called a server.
A server may already have a completed HTML file ready to return. However, many modern websites generate their HTML when a request arrives.
The server-side program might:
- Receive a request from a browser.
- Retrieve information from a file or database.
- Use loops to process several records.
- Use conditions to decide what should appear.
- Insert the information into HTML.
- Return the completed HTML to the browser.
A simplified request looks like this:
Browser requests a webpage
↓
Server receives the request
↓
Python code runs
↓
Data is retrieved and processed
↓
HTML is generated
↓
The server returns the HTML
↓
The browser displays the page
Our classroom program was not running as a web server yet. We generated an HTML file locally and opened it ourselves.
However, the central idea is similar: Python processes information and creates the HTML that a browser can display.
Why the Relationships Can Be Difficult to See
This lesson introduced several layers at the same time:
- The list stores the original data.
- The loop retrieves one value at a time.
- Python converts the value into text when necessary.
- The value is inserted into an HTML element.
- The HTML elements are collected into a larger string.
- The string is passed into a function.
- The function inserts it into a complete document.
- The document is written into a file.
- The browser interprets the file.
Each step is manageable on its own. The challenge is following a piece of information as it moves through the entire program.
This is why the examples were colour-coded. The colours make it easier to track which values represent the original data, which value is currently being processed, and where the generated HTML is being collected.
Students are not expected to understand the entire process immediately. Seeing the flow several times and building smaller examples will make the relationships clearer.
Why We Did Not Use CSS
We intentionally left CSS out of today's exercise.
The goal was not to create a polished visual design. The goal was to understand the flow between:
- Python data
- Loops
- Strings
- Functions
- HTML
- Files
- The browser
Once that flow is more familiar, CSS can be added to style the generated webpage.
Class Helper and Code Reference
During class, we used a separate helper article containing the code examples discussed in the lesson.
The helper includes examples of:
- Storing a complete HTML document in a Python string
- Writing HTML into an index.html file
- Creating the htmlBoiler() helper function
- Lists containing names, ages, temperatures, and attendance values
- Using len(), min(), max(), sum(), and sorted()
- Creating and iterating through a Python dictionary
Open the Day 4 Python and HTML class helper
The helper is intended to act like a shared class notebook. Students can use it to find the main code examples, copy them into VS Code, make changes, and observe what happens.
A Brief Introduction to Linux
One student asked about getting Linux and whether it would be useful.
Linux is an operating system, similar in purpose to Windows or macOS. It is widely used for web servers, cloud computing, cybersecurity, software development, scientific systems, and embedded devices.
Experimenting with Linux can be a valuable learning experience because it exposes students more directly to files, directories, permissions, programs, and the command line.
Linux is not required for this course. Students interested in programming or computer systems may still benefit from experimenting with it on a separate computer, in a virtual machine, or through the Windows Subsystem for Linux with appropriate guidance.
Basic Linux Commands
| Command | Purpose |
|---|---|
pwd |
Displays the current directory. |
ls |
Lists files and directories. |
cd folder |
Moves into a directory. |
cd .. |
Moves up one directory. |
mkdir website |
Creates a new directory named website. |
touch index.html |
Creates an empty file named index.html. |
cp source destination |
Copies a file or directory. |
mv source destination |
Moves or renames a file. |
rm filename |
Deletes a file. |
clear |
Clears the terminal display. |
Commands such as rm should be used carefully. Files removed through the terminal may not be moved into a recycle bin.
Course Schedule
The course will now take a short break. In-person classes will resume on August 4, 2026.
During the break, students can review the earlier articles, revisit the class helper, and experiment with generating their own HTML files using Python.
Useful practice ideas include:
- Generate a page containing a list of favourite games or sports.
- Generate paragraphs from a list of temperatures.
- Create a dictionary describing a student or organization.
- Change the title and body content passed into htmlBoiler().
- Write the completed document into a new HTML file.
- Open the generated file in a browser and inspect the result.
When classes resume, we will continue connecting data, programming logic, files, webpages, and server-side development.
Main Takeaways
During Day 4, students:
- Used Python lists containing names, ages, temperatures, and other values.
- Used loops to process one value at a time.
- Converted numerical values into strings when building HTML.
- Generated HTML paragraphs and list items.
- Collected repeated HTML inside a larger string.
- Created a reusable HTML boilerplate function.
- Passed head and body content through function parameters.
- Returned a complete HTML document from a function.
- Wrote generated HTML into a file.
- Used several built-in functions to examine list data.
- Received a brief introduction to dictionaries.
- Discussed how servers generate and return HTML.
- Received a brief introduction to Linux and terminal commands.
This lesson represented an important transition in the course. Students are no longer only writing static HTML by hand. They are beginning to see how a programming language can process data and use it to create webpage content automatically.
The complete relationship may not feel natural yet. That understanding will develop through repetition. The important first step is recognizing that HTML is text, Python can generate that text, and a browser can interpret the result as a webpage.