Looping a Set Number of Times in Python: Using the range() Function

In programming, regardless of the number of elements in a list, there are times when you want to execute a loop a specific number of times, such as “I want to repeat a process only 5 times” or “I want to retry 10 times.”

In Python, you can achieve this concisely by combining the for statement with the built-in function range().

This article explains how to implement a loop a specific number of times using the range() function and the common method for writing it when you don’t handle the loop variable.

目次

Basic Syntax

To repeat a process a specified number of times, pass the number of times (integer) you want to repeat as an argument to the range() function.

Syntax:

for variable in range(count):
    # Process to repeat

range(N) generates a sequence of integers from 0 to N-1. As a result, the process inside the block is executed N times.

1. When Using a Loop Variable (Counter)

If you want to know which iteration is currently being processed inside the loop, use the variable in the for statement (typically i or index is used).

The following example is a program that simulates connecting to a server and displays the number of attempts.

# Maximum retry count
max_retries = 5

print("--- Starting connection process ---")

# Repeat 5 times from 0 to 4
for i in range(max_retries):
    # Since i starts from 0, add +1 for display
    attempt_number = i + 1
    print(f"Attempting to connect to server... ({attempt_number} / {max_retries})")

print("--- Process complete ---")

Execution Result:

--- Starting connection process ---
Attempting to connect to server... (1 / 5)
Attempting to connect to server... (2 / 5)
Attempting to connect to server... (3 / 5)
Attempting to connect to server... (4 / 5)
Attempting to connect to server... (5 / 5)
--- Process complete ---

Since range(5) generates the numbers 0, 1, 2, 3, 4 in order, these values are assigned to the variable i sequentially.

2. When Not Using a Loop Variable (Underscore _)

There are cases where you simply want to repeat a process and do not use the information about the current iteration count (loop variable) in the code.

In such cases, it is a Python convention to use an _ (underscore) as the variable name. This makes it clear to anyone reading the code that “this variable is intentionally unused.”

# Simulation of repeating data transmission 3 times
repeat_count = 3

print("Start sending data")

# Specify '_' because the variable is not used
for _ in range(repeat_count):
    print("Packet sent.")

print("Sending complete")

Execution Result:

Start sending data
Packet sent.
Packet sent.
Packet sent.
Sending complete

Although using i as the variable name works fine, using _ makes it easier for static analysis tools to recognize that the variable is unused and clarifies the code’s intent.

Summary

  • Use for i in range(count): to loop a specified number of times.
  • range(N) generates values from 0 to N-1.
  • If you do not use the loop variable value (current iteration count), it is common to use _ for the variable name.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次