How to Call a Function in a For Loop Python

In Python, functions are defined blocks of code designed to do a specific task that can be reused in other parts of the program. If you want to perform an action on every element in a sequence like a list, you can use a For loop to call a function. In this tutorial, we will show how you can call a function in a For loop in Python.

Step 1: Defining a function

The first step is to create a function that you want to call for each item in a list. Let’s consider a simple function that receives a number and prints its square:

Step 2: Creating a list

Next, create a list of numbers that you want to pass to the function. Here’s an example:

Step 3: Using the For loop to call the function

Now, you can use a For loop to iterate over each item in the list. For each item, you call the function, passing the current item to it. Look at how it is done:

Note: Be sure that the indentation is correct. The call to the function should be inside the For loop.

Step 4: Running the code

If you run the code now, it will go through each number in the list and print its square. This is the expected output:

1
4
9
16
25

Here is the complete code:

Conclusion

Calling a function in a For loop is a common practice in Python. It allows you to perform an action for each item in a list or any iterable. This simplifies code and makes it easier to maintain.

By defining a function and calling it in a For loop, you can make your programs more modular, flexible, and efficient. This was a simple demonstration, and the concept can be used in more complex scenarios and applications.