To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenโt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Introduction: Your First Step in Programming Starts with Variables and Data Types
Hello to everyone stepping into the world of website creation! Once you get used to creating layouts with HTML and CSS, the next step is to add "interactivity" and "data processing"โthe world of programming awaits. Among the many languages, Python is chosen by many web creators for its simplicity and ease of learning.
When learning to program, the first things everyone encounters are "variables" and "data types." These are the most fundamental mechanisms for a program to handle data, forming what you could call the skeleton of programming.
You might be thinking, "This sounds a bit difficult..." but don't worry! In this article, we'll gently explain Python's variables and data types using familiar analogies. All the code snippets we introduce can be run on your computer just by copying and pasting. We hope you'll feel the joy of programming not just by "reading and understanding," but by "running the code and experiencing it."
Now, let's explore the world of Python together and take your web creation skills to the next level!
Chapter 1: What Are Variables? A Magic Box for Storing Data
In programming, a variable is, in short, like a "box for holding data." You can give this box any name (a label) you like, put data such as numbers or text inside, and then freely take it out or replace the contents later.
For example, let's say you're creating a self-introduction. You have the sentence, "My name is John Smith. I am 30 years old." It would be a hassle to edit the text in multiple places every time the name or age changes, right? That's where variables come in.
1-1. How to Create a Variable (Assignment)
Putting data into a variable "box" is called "assignment" in the programming world. In Python, you write it using the = (equals) sign.
You can easily create a variable just by writing variable_name = data. Let's try it out.
The following code puts the string "John Smith" into a variable named name, and the number 30 into a variable named age.
# Assign the string "John Smith" to a variable named name
name = "John Smith"
# Assign the number 30 to a variable named age
age = 30
1-2. Let's See What's Inside a Variable (Output)
Just putting data into a variable doesn't do anything. You want to actually check the contents, right? That's when you use the print() function. If you put the variable name inside the parentheses of print(), the data stored in that variable will be displayed (output).
name = "John Smith"
age = 30
# Output the content of the name variable
print(name)
# Output the content of the age variable
print(age)
1-3. The Contents of a Variable Can Be Changed
The convenient thing about variables is that you can overwrite them with new data even after you've already stored something. Think of it as swapping out the contents of the box.
In the example below, we first put "Web Designer" into the job variable, and then later change it to "Web Director". When you output it with print(), you can see that the content has indeed changed.
job = "Web Designer"
print(job) # At this point, "Web Designer" is displayed
# Assign new data to the same variable (overwrite)
job = "Web Director"
print(job) # "Web Director" is displayed
Chapter 2: What Are Data Types? The Kinds of Things You Put in the Box
I explained that you can put various kinds of data into the variable "box." This "kind of data" is called a data type.
Why are data types important? For example, if you have the data "100," is it the number 100, or is it the text "100"? A human can judge from context, but you need to explicitly tell a computer the difference. If it's a number, you can do addition and subtraction, but you can't if it's text, right?
Python has many data types, but let's start by learning the basic ones that are especially common in web development.
2-1. String - For Representing Text
The string type handles sequences of characters, like sentences and words. In Python, it's represented as str. The rule for handling strings in a program is to enclose them in either " " (double quotes) or ' ' (single quotes).
# A string using double quotes
greeting = "Hello, World!"
print(greeting)
# A string using single quotes
site_name = 'Web Creator Box'
print(site_name)
2-2. Number - Leave the Calculations to Me
As the name suggests, this is a data type for handling numbers. In Python, we mainly use two types.
Integer: Numbers without a decimal point, like 1, 100, and -50. Represented as int.
Float: Numbers with a decimal part, like 1.5, 3.14, and -0.01. Represented as float.
You write numbers as they are, without enclosing them in " ". If you do enclose them, they become strings, not numbers, so be careful.
# Integer type (int)
user_count = 150
print(user_count)
# Float type (float)
tax_rate = 1.10
print(tax_rate)
# You can also perform calculations with numbers
total_price = 5000 * tax_rate
print(total_price)
2-3. Boolean - A Yes/No Choice
The boolean type is a very simple data type that can only have one of two values: True or False. It's represented as bool.
It's extremely useful for managing states that can be answered with a Yes/No, such as "Is the user logged in?" or "Is the publish setting on?" It's frequently used in implementing website features.
# Represent the user's logged-in state with True
is_logged_in = True
print(is_logged_in)
# Represent an unpublished article state with False
is_published = False
print(is_published)
2-4. List - Storing Multiple Items in Order
The list type is used when you want to store multiple pieces of data in a single variable while keeping them in order. You surround the whole thing with [ ] (square brackets) and separate each item with a , (comma).
It's useful when you want to handle multiple items together, like a "News List" or "Product Category List" on a website. The data types of the items inside can be mixed.
# Manage hobbies with a list
hobbies = ["Reading", "Watching movies", "Programming", "Walking"]
print(hobbies)
# Access data using its zero-based index number
print(hobbies[0]) # Displays the first element, "Reading"
print(hobbies[2]) # Displays the third element, "Programming"
2-5. Dictionary - Managing with Key-Value Pairs
The dictionary type, like a list, can store multiple pieces of data, but there's a big difference. While a list manages data by "order," a dictionary manages it using "key" and "value" pairs.
You surround the whole thing with { } (curly braces) and write the data in a "key": value format.
It's perfect for when you want to attach meaningful labels to each piece of data, such as a person's profile information where "name" is "Jane Doe" and "age" is "25."
# Manage a user profile with a dictionary
user_profile = {
"name": "Jane Doe",
"age": 25,
"job": "Web Engineer",
"is_student": False
}
print(user_profile)
# Access data by specifying the key
print(user_profile["name"]) # Displays "Jane Doe"
print(user_profile["job"]) # Displays "Web Engineer"
2-6. Checking Data Types with the `type()` Function
When you want to check, "What data type is currently in this variable?", the type() function is very handy. Just put the variable name inside the parentheses, and it will tell you its data type.
Once you've learned the basic data types, let's look at how to combine or convert them. Being able to do this will greatly expand your range of expression.
3-1. String Concatenation
You can join strings together using the + operator.
You'll often want to embed a variable's value within a sentence, like "Your score is 100 points." The "f-string" (formatted string literal) is extremely useful for this.
By putting an f before the opening quote of the string and enclosing variables in { }, you can easily combine strings and variables. This is a modern and very common way of writing Python.
user_name = "Guest"
points = 120
# Create a string using an f-string
message = f"The current score for {user_name} is {points} points."
print(message)
3-3. Data Type Conversion (Casting)
When you're programming, you'll encounter situations where you want to "treat a number as a string" or, conversely, "treat a string of digits as a number for calculations." Converting a data type to another like this is called casting.
str(data): Converts data to a string.
int(data): Converts data to an integer.
float(data): Converts data to a float.
In the example below, if you join the strings "100" and "50" with +, they are concatenated as text, resulting in "10050". By converting them to numbers with int() before adding, we correctly get the calculation result of 150.
# Data from user input is initially treated as a string, even if it's a number
input_str_num1 = "100"
input_str_num2 = "50"
# Concatenate as strings
print(input_str_num1 + input_str_num2) # Results in "10050"
# Convert to numbers with int() before calculating
num1 = int(input_str_num1)
num2 = int(input_str_num2)
print(num1 + num2) # Correctly displays 150
Chapter 4: Putting It to Use in Web Development! Let's Generate HTML with Python
Now, let's try a practical example that's familiar to all you web creators, using the variables and data types we've learned so far. This is an advanced example where we use a Python program to dynamically generate an HTML file itself.
For instance, imagine a staff introduction page on a website. It's a lot of work to manually update the HTML every time a new staff member joins. But with Python, you can automatically generate a profile page HTML based on the staff's data (managed as a dictionary).
[Complete Example] Generating a Profile Page HTML with Python
The following Python code is a program that writes an HTML file named profile.html based on the profile information stored in a dictionary called profile_data.
Try copying this code, saving it with a name like profile_generator.py, and running it. A file named profile.html should be generated in the same folder.
# profile_generator.py
# Manage profile data with a dictionary
profile_data = {
"name": "Alice Johnson",
"job": "Web Designer",
"skills": ["HTML", "CSS", "JavaScript", "Python"],
"introduction": "I strive to create designs that are both beautiful and have clean code. Lately, I'm hooked on using Python for work automation!"
}
# Create the HTML structure using an f-string
# We are embedding data from the dictionary and list
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{profile_data['name']}'s Profile</title>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.7; color: #333; background-color: #fdfdfd; max-width: 800px; margin: 2rem auto; padding: 0 1.5rem; }}
.profile-card {{ background: #fff; border: 1px solid #e0e0e0; border-radius: 12px; padding: 2.5rem; box-shadow: 0 6px 12px rgba(0,0,0,0.08); }}
h1 {{ color: #2c3e50; font-size: 2.5rem; margin-bottom: 0.5rem; }}
h2 {{ color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 0.5rem; margin-top: 2rem; }}
p {{ margin: 1rem 0; }}
.job-title {{ color: #7f8c8d; font-size: 1.2rem; font-weight: bold; margin-bottom: 2rem; }}
.skills-list {{ list-style: none; padding: 0; margin-top: 1rem; }}
.skills-list li {{ background: #3498db; color: white; padding: 0.3rem 1rem; border-radius: 16px; display: inline-block; margin: 0.3rem; font-size: 0.9rem; }}
</style>
</head>
<body>
<div class="profile-card">
<h1>{profile_data['name']}</h1>
<p class="job-title">{profile_data['job']}</p>
<h2>Introduction</h2>
<p>{profile_data['introduction']}</p>
<h2>Skills</h2>
<ul class="skills-list">
{''.join([f'<li>{skill}</li>' for skill in profile_data['skills']])}
</ul>
</div>
</body>
</html>
"""
# Open the file in write mode and write the content
try:
with open("profile.html", "w", encoding="utf-8") as f:
f.write(html_content)
print("โ Success: profile.html has been generated. Open the file to check it out.")
except IOError as e:
print(f"โ Error: Failed to write to file. {e}")
The Complete Code of the Generated HTML File
When you run the Python script above, a profile.html file with the following content will be created. If you open it in a browser, a profile page with simple styling should be displayed.
In this way, by skillfully using Python's variables and data types (especially dictionaries and lists), you can move one step beyond a simple static website to create data-driven content.
Chapter 5: Important Points to Remember About Variables and Data Types
Finally, let's introduce a few points that beginners often stumble on when dealing with variables and data types, and some good rules to know.
Follow Naming Conventions
You can't just name a variable anything. In Python, you use a combination of lowercase letters, numbers, and underscores (_). The "snake_case" style, where words are separated by underscores (e.g., user_name, total_price), is recommended. Choose names that are easy to understand and consistent.
You Can't Use Reserved Words
Words that have a special meaning in Python's syntax (like if, for, class, print, etc.) cannot be used as variable names. These are called "reserved words."
Case Matters
A variable named name and a variable named Name are treated as two completely different things. Be careful, as this can cause unexpected errors.
Understand That It's a Dynamically Typed Language
Python is a "dynamically typed language," where the type of a variable is automatically determined by the data you put into it. While this makes it easy to write, it also means you can later assign a string to a variable that initially held a number. It's a good habit to occasionally check if the type has changed unintentionally using the type() function.
Conclusion: Solidify Your Programming Basics and Move to the Next Step!
In this article, we've covered the core of Python programmingโ"variables" and "data types"โfrom basic usage to practical examples in web development.
Variables are "named boxes" for storing data.
Data types are the kinds of data you put in the boxes, such as strings (str), numbers (int, float), lists (list), and dictionaries (dict).
By combining these, you can efficiently manage data and automate things like generating web pages.
Variables and data types are the foundation for all the basic Python syntax you will learn next, such as conditional branching (if statements), loops (for loops), and functions. Building a solid foundation here is the key to smooth learning in the future.
Please try running the code in this article over and over to fully enjoy the fun of "making your own code work." The accumulation of these small successful experiences will surely guide you to become a better creator.
Next, let's advance to the world of "conditional branching," where the boolean type (True/False) we learned about today plays an active role!