To repeat a function in Python, the easiest way is with a for loop.

def multiplyBy2(num):
    return num*2

x = 2

for i in range(0,4):
    x = multiplyBy2(x)

print(x)

#Output:
32

You can also use a while loop to repeat a function in Python.

def multiplyBy2(num):
    return num*2

x = 2

while x < 30:
    x = multiplyBy2(x)

print(x)

#Output:
32

When working with data in our Python programs, iteration can be incredibly useful to perform tasks for us many times. We can use iteration to repeat functions easily in Python.

Iteration in Python comes in two forms, for loops and while loops.

In a for loop, we define the number of times you want a block of code to repeat explicitly.

For example, if I want to create a loop which will run five times, I can use the range() function to build a range from 0 to 5.

for i in range(0,5):
    print(i)

#Output:
0
1
2
3
4

We can repeat functions in Python easily with for loops.

For example, if we have a function which multiplies a number by 2, and we want to multiply another number by 2 five times, we can loop five times and repeat the function five times.

Below is an example in Python of how to repeat a function five times with a for loop.

def multiplyBy2(num):
    return num*2

x = 2

for i in range(0,4):
    x = multiplyBy2(x)

print(x)

#Output:
32

Repeating Functions with While Loops in Python

You can also repeat functions with Python by using while loops. While loops allow us to iterate depending on the conditions we pass the loop.

For example, with while loops you need to use a logical expression which will determine whether to keep iterating or not.

In our example above, we wanted to loop five times to multiply our number by 2 five times.

Let's instead use a while loop which will keep multiplying until our number is at least 30.

Below is an example using Python of how to use a while loop to repeat a function.

def multiplyBy2(num):
    return num*2

x = 2

while x < 30:
    x = multiplyBy2(x)

print(x)

#Output:
32

Hopefully this article has been useful for you to learn how to repeat a function in Python.

Categorized in:

Python,

Last Update: March 15, 2024