How to Repeat a Function in Python?

Today, in the New York Python user group, one member asked about repeating a function in Python. This is a little tricky, but there are different methods. In this tutorial, I will explain how to repeat a function in Python using various methods and examples.

To repeat a function in Python using a for loop, you simply define the function and then use the loop to call it multiple times. For example, if you have a function greet() that prints “Hello, World!”, you can repeat it 5 times with the following code:

def greet():
    print("Hello, World!")

for i in range(5):
    greet()

This loop will call the greet() function five times, printing “Hello, World!” each time.

Let us check different methods to repeat a function in Python with examples.

Method 1: Using a for Loop

The best and recommended way to repeat a function in Python is by using a for loop. This method is simple and effective for a known number of repetitions.

Syntax

for i in range(n):
    function_name()

The range(n) function generates a sequence of numbers from 0 to n-1. The for loop iterates over this sequence, calling the specified function on each iteration.

Example

Let’s say you have a function that prints the name of a popular American city.

def print_city():
    print("New York")

# Repeat the print_city function 5 times
for i in range(5):
    print_city()

The output is shown in the screenshot below. I executed the above Python code using VS code.

repeat a function in python

Check out Return Multiple Values from a Function in Python

Method 2: Using a while Loop

A while loop can be used when the number of repetitions is not known beforehand or depends on a condition. We can use a while loop to repeat a function in Python.

Syntax

while condition:
    function_name()

The while loop continues to execute as long as the specified condition is True.

Example

Imagine you have a function that prints “Go Team USA!” and you want to repeat it 5 times.

def cheer():
    print("Go Team USA!")

count = 0
while count < 5:
    cheer()
    count += 1

Here is the output in the screenshot below:

how to repeat a function in python

Method 3: Using Recursion

Recursion involves a function calling itself. This method is less common for simple repetition but can be useful in specific scenarios.

Syntax

def repeat_function(n):
    if n > 0:
        function_name()
        repeat_function(n-1)

The function calls itself with a decremented counter until the base condition is met.

Example

Consider a function that prints “Welcome to California!” and you want to repeat it 5 times.

def welcome():
    print("Welcome to California!")

def repeat_welcome(n):
    if n > 0:
        welcome()
        repeat_welcome(n-1)

# Repeat the welcome function 5 times
repeat_welcome(5)

You can see the output in the screenshot below after I executed the above Python code.

python repeat a function

Method 4: Using itertools.repeat

The itertools.repeat function is a part of Python’s itertools module and provides a more advanced way to repeat a function.

Syntax

from itertools import repeat

for _ in repeat(None, n):
    function_name()

The repeat function generates an iterator that returns the same value (None in this case) a specified number of times.

Example

Suppose you have a function that prints “Enjoy your meal!” and you want to repeat it 5 times.

from itertools import repeat

def enjoy_meal():
    print("Enjoy your meal!")

# Repeat the enjoy_meal function 5 times
for _ in repeat(None, 5):
    enjoy_meal()

Method 5: Using Threading for Concurrent Repetition

If you need to repeat a function concurrently, you can use Python’s threading module.

Syntax

import threading

def function_name():
    # Function code

threads = []
for i in range(n):
    t = threading.Thread(target=function_name)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

This method creates multiple threads, each executing the function concurrently.

Example

Imagine you have a function that prints “Happy 4th of July!” and you want to repeat it 5 times concurrently.

import threading

def celebrate():
    print("Happy 4th of July!")

threads = []
for i in range(5):
    t = threading.Thread(target=celebrate)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

Conclusion

In this tutorial, I have explained how to repeat a function in Python using different methods, such as: using a for loop, while loop, recursion, itertools.repeat, or threading, etc. For each method, I explained its syntax and how to use it with an example. Still have a question? Feel free to leave a comment below.

Leave a Comment