πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ EspaΓ±ol | πŸ‡΅πŸ‡Ή PortuguΓͺs | πŸ‡ΉπŸ‡­ ΰΉ„ΰΈ—ΰΈ’ | πŸ‡¨πŸ‡³ δΈ­ζ–‡

Understanding Loops in Python with for and while Statements

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.

Hello, web creators! Have you ever felt like you're doing the same task over and over again in your web development or daily work? That's where programming's "repetitive processing (loops)" come in to automate those tedious tasks.

In this article, we've prepared a lot of "working code" for Python's basic repetitive processing, the for statement and the while statement, that even beginners can try right away. The goal is to first experience "making it work." The theory will follow later. Please feel free to copy and paste the code and experience the convenience of loops!


1. for Statements: Great for Repeating a Fixed Number of Times!

The for statement is good at taking out elements one by one in order from a collection of data, such as a list or string, and processing them. It is also used for processing a predetermined number of times, such as "repeat 10 times."

The most basic form is for variable in data_collection:. Let's take a look at some specific code right away.

Retrieving Elements from a List in Order

For example, let's say you have a list of categories for a website you manage. Let's display these category names one by one.


# Create a list of category names to display
categories = ["HTML", "CSS", "JavaScript", "Python", "Web Design"]

# Use a for loop to retrieve elements one by one from the list and display them on the screen
for category in categories:
  print(f"Category Name: {category}")

# Execution Result:
# Category Name: HTML
# Category Name: CSS
# Category Name: JavaScript
# Category Name: Python
# Category Name: Web Design
    

Repeating a Fixed Number of Times (range function)

If you simply want to repeat a process a fixed number of times, like "create 5 sample blog posts," the range() function is convenient. Writing range(5) generates numbers from 0 to 4 in order (the key point is that it doesn't include 5!).


# Loop a total of 5 times, from 0 to 4
for i in range(5):
  # Use an f-string to display which loop it is (add 1 since i starts from 0)
  print(f"This is the {i + 1}st/nd/rd/th process.")

# Execution Result:
# This is the 1st process.
# This is the 2nd process.
# This is the 3rd process.
# This is the 4th process.
# This is the 5th process.
    

Repeating While Knowing the Element Number (enumerate function)

When retrieving elements from a list, you may also want to know "which element number it is now." In that case, use the enumerate() function. It's useful for displaying things in a ranking format.


# List of popular article rankings
ranking = ["Python Introduction", "Responsive Design with CSS", "Asynchronous Processing in JavaScript"]

# Use enumerate to retrieve the rank (index) and article title (element) at the same time
# By setting start=1, the rank can start from 1
for rank, title in enumerate(ranking, start=1):
  print(f"{rank}st/nd/rd: {title}")

# Execution Result:
# 1st: Python Introduction
# 2nd: Responsive Design with CSS
# 3rd: Asynchronous Processing in JavaScript
    

2. while Statement: Repeating While a Specific Condition is Met

The while statement is a type of loop that "continues processing as long as this condition is true (True)." Unlike the for statement, it is often used when the number of repetitions is not fixed. For example, it is useful in interactive programs such as "continue processing until the user enters a specific character" or in cases such as "continue until the processing time exceeds 10 seconds."

The basic form is while condition:. The process inside continues to be executed as long as the condition is True.

Repeating Until a Counter Reaches a Specific Number

First, a simple example. Prepare a counter variable and continue the loop only while that number meets a specific condition. Be careful, as forgetting to change the counter value in the loop can lead to an infinite loop (described later).


# Initialize the counter variable to 0
count = 0

# Continue the loop while count is less than 5
while count < 5:
  print(f"Current count: {count}")
  # This line is important! Increment the value of count by 1
  count += 1

print("The loop has finished.")

# Execution Result:
# Current count: 0
# Current count: 1
# Current count: 2
# Current count: 3
# Current count: 4
# The loop has finished.
    

3. Applied Example: Let's Generate an HTML File with Loop Processing

Now, let's apply the knowledge we've gained so far to a more practical example for web creators. This is a program that automatically generates the HTML code for a website's navigation menu using Python's loop processing.

When you run this code, a file called `navigation.html` will be created, and a list-style menu will be written inside it. This saves you the trouble of writing many <li> tags by hand!

[Fully-working complete HTML example]
The following code is the Python script itself. If you have Python installed in your local environment, you can save this code with a name like `generate_html.py` and run `python generate_html.py` in your terminal or command prompt, and `navigation.html` will be generated in the same directory.


# -*- coding: utf-8 -*-

# List of items to display in the menu
menu_items = {
  "Home": "index.html",
  "About Us": "about.html",
  "Services": "services.html",
  "Blog": "blog.html",
  "Contact": "contact.html"
}

# Variable to store HTML fragments
html_content = """<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Auto-generated Navigation</title>
  <style>
    body { font-family: sans-serif; }
    nav ul { list-style: none; padding: 0; display: flex; gap: 1rem; }
    nav a { text-decoration: none; color: #007BFF; padding: 0.5rem 1rem; border: 1px solid #ddd; border-radius: 5px; }
    nav a:hover { background-color: #f0f0f0; }
  </style>
</head>
<body>

  <h1>Navigation Menu</h1>
  <nav>
    <ul>
"""

# Use a for loop to retrieve the key (text) and value (link) from the dictionary and generate <li> tags
for text, link in menu_items.items():
  html_content += f'      <li><a href="{link}">{text}</a></li>\n'

# Add the footer part of the HTML
html_content += """    </ul>
  </nav>

</body>
</html>
"""

# Open a file named "navigation.html" and write the contents to it
try:
  with open("navigation.html", "w", encoding="utf-8") as f:
    f.write(html_content)
  print("βœ… Successfully generated navigation.html!")
except IOError as e:
  print(f"❌ An error occurred while writing the file: {e}")

    

4. Points to Note: Loop Control Techniques

Loop processing is very convenient, but there are some control methods you should know to avoid unintended behavior. In particular, "infinite loops," "break," and "continue" are important concepts.

Beware of Infinite Loops!

An "infinite loop" is particularly likely to occur with the while statement. This is a phenomenon where the program stops responding because the condition for exiting the loop remains True forever. In the example below, the value of count does not change, so the condition count < 5 is permanently met.


# ⚠️ Be careful when running this code as it will result in an infinite loop!
count = 0
while count < 5:
  print("This message will be displayed infinitely...")
  # The process to update the value of count (such as count += 1) is missing!
    

Exiting a Loop in the Middle (break)

In the middle of a loop, you may want to completely terminate the process if a certain condition is met. In that case, use break. For example, if you find a specific element in a list, you don't need to search any further. That's when break comes in handy.


# File to search for
target_file = "python.png"
file_list = ["style.css", "index.html", "script.js", "python.png", "logo.svg"]

# Check the file list in order
for filename in file_list:
  print(f"Checking: {filename}")
  if filename == target_file:
    print(f"πŸŽ‰ Found it!: {target_file}")
    # The target file has been found, so exit the loop
    break

# Execution Result:
# Checking: style.css
# Checking: index.html
# Checking: script.js
# Checking: python.png
# πŸŽ‰ Found it!: python.png
    

You can see that when break is executed, the loop ends without checking "logo.svg".


Skipping Only the Current Process (continue)

While break terminates the loop itself, continue is a command to "skip only the current process and proceed to the next iteration." For example, it is useful when you want to process only image files (.jpg, .png) from a large number of files.


file_list = ["memo.txt", "photo_01.jpg", "document.pdf", "photo_02.png", "archive.zip"]

# Loop through the file list
for filename in file_list:
  # If the file name does not end with ".jpg" or ".png"...
  if not (filename.endswith(".jpg") or filename.endswith(".png")):
    # ...skip this process and go to the next file
    continue
  
  # This line is only executed for image files
  print(f"Processing image file: {filename}")

# Execution Result:
# Processing image file: photo_01.jpg
# Processing image file: photo_02.png
    

Summary

In this article, we've explained the basics of Python's repetitive processing, the for statement and the while statement.

It may seem difficult at first, but please start by copying and pasting to get it working, then gradually change the numbers, change the contents of the list, and observe the changes in behavior. If you master repetitive processing, your web production and work will become much more efficient!


As a next step, why not learn about "functions" that group processes together?

How to Create and Use Functions in Python