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:
1 2 3 4 5 |
# This function receives a number and prints its square def print_square(n): print(n ** 2) |
Step 2: Creating a list
Next, create a list of numbers that you want to pass to the function. Here’s an example:
1 2 |
# This is a list of numbers numbers = [1, 2, 3, 4, 5] |
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:
1 2 3 |
# For each number in the list, the function print_square is called with the current number for num in numbers: print_square(num) |
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:
1 2 3 4 5 6 7 8 9 10 |
# This function receives a number and prints its square def print_square(n): print(n ** 2) # This is a list of numbers numbers = [1, 2, 3, 4, 5] # For each number in the list, the function print_square is called with the current number for num in numbers: print_square(num) |
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.