Call function in loop python

I have the following python code that call a function that iterate over a dict. the code below not work as expected:

list1=["test1","test2","test3","test4"]
list2=["toto1","test1","test3","toto4"]

def functest(t):
    for l in list2:
        if t == l:
            return cond1
        else:
            return "rien"

for t in list1:
    titi=functest(t)
    print titi

When I print titi var I have toto1 printed 4 times.

If I remove the else inside my function the code seem to work.

How you can explain this behavior ?

Why when I add else with a returned string only the string is printed.

thanks

Call function in loop python

mmenschig

1,04014 silver badges22 bronze badges

asked Mar 8, 2017 at 20:12

3

Because return exits the function and returns your program back to the loop. So when you add the else statement within the loop, the current element of list1 is compared against 'toto1', enters the else statement, and the function returns "rien".

def functest(t):
    for l in list2:
        if t == l: 
            return cond1
        else:
            return "rien" # we always end up here on the first iteration, 
                          # when comparing against "toto1"

When you remove the else statement, you loop until you find a match in list2. However, assuming you still want to return "rien" given that none of the elements in list2 match the element in list1 which is being checked, you should move the return statement out of the loop, so that it is only returned after checking all elements.

def functest(t):
    for l in list2:
        if t == l:
            return "match found"
    return "rien"

Demo

>>> for t in list1:
       titi=functest(t)
       print (titi)

match found
rien
match found
rien

answered Mar 8, 2017 at 20:19

Call function in loop python

miradulomiradulo

27.3k6 gold badges75 silver badges92 bronze badges

0

I have tried to modify code in order to implement your logic.

list1=["test1","test2","test3","test4"]
list2=["toto1","test1","test3","toto4"]

def functest(t):
  newReturnList=[]
  for l in list2:
     if t == l:
        newReturnList.append(t+'-found') 
     else:
        newReturnList.append(t+'-NOT found')

return newReturnList


for t in list1:
    titi=functest(t)
   print (titi)

answered Jun 19, 2020 at 23:12

Call function in loop python

1

  • Introduction to Python call function
  • Getting started with Python call function
    • Syntax and example of the python call function
    • Calling python function with returned value
    • Calling python built-in functions
  • Python call function with arguments
    • Integer arguments in python call function
    • String arguments in python call function
  • Calling a function in python loop
    • Python call function inside for loop
    • Python call function inside while loop
  • Python call function from inside function itself
  • Summary
  • Further Reading

Introduction to Python call function

Python is well known for its various built-in functions and a large number of modules. These functions make our program more readable and logical. We can access the features and functionality of a function by just calling it. In this tutorial, we will learn about how the python call function works. We will take various examples and learned how we can call python built-in functions and user-defined functions. Moreover, we will cover how to call a function with arguments and without arguments.

At the same time, we will also discuss about the data types of these arguments and their order as well. In a conclusion, this tutorial covers all the concepts and details that you need to start working with functions and calling functions.

Getting started with Python call function

Before starting and learning how to call a function let us see what is a python function and how to define it in python. So, a Python function is a group of codes that allows us to write blocks of code that perform specific tasks. A function can be executed as many times as a developer wants throughout their code. The def keyword is used to define and declare a function. See the syntax below;

def name_of_funtion():
      function_statements

To run the code in a function, we must call the function. A function can be called from anywhere after the function is defined. In the following section, we will learn how we can call a function and how they return a value.

Syntax and example of the python call function

We already had learned how we can define a function, now let us see how we can call a function that we have defined. The following syntax is used to call a function.

# python call function
name_of_function()

Now let us create a function that prints welcome and see how we can call it using the above syntax. See the following example.

# creating function
def hello():

   # printing welcome
   print("welcome to python call function tutorials!")

# python call function
hello()

Output:

welcome to python call function tutorials!

Calling python function with returned value

In the above example, notice that it did not return any value or expression, it just prints out the welcome statement. In python, we can return a value from a function as well by using the return keyword. First, let us take the same example and return the welcome statement this time, instead of printing it out. See the example below:

# creating function
def hello():

   # return welcome statement
   return "welcome to python call function tutorials!"

# python call function
print(hello())

Output:

welcome to python call function tutorials!

Now if we check the type of function's return by using the python type method, we will get string type because this function returns a string value. See the example below:

# creating function
def hello():

   # return welcome statement
   return "welcome to python call function tutorials!"

# python call function and type method
print(type(hello()))

Output:

Note that the function type is a string. Now let us take one more example which returns the sum of two numbers. See the example below:

# creating function
def Sum():

   # return welcome statement
   return 2+7

# python call function
print(Sum())

Output:

9

Now let us check the type of function by using the python type method. See the example below:

# creating function
def Sum():

   # return welcome statement
   return 2+7

# python call function and python type method
print(type(Sum())

Output:

Notice that this time we got int type because our function returns an integer value.  The type changes each time because we are finding the returned type of a function using the python type function and applying it on the python call function. If we find the type of function without calling it, we will get "type function". See the example below:

# creating function
def Sum():

   # return welcome statement
   return 2+7

# python call function and python type method
print(type(Sum))

Output:

Calling python built-in functions

We know that python is well known for its various built-in functions. Some of these functions come with python and some with different modules. We can access the functionalities of these functions by calling the function. See the example below which call the sum function.

# python call function and built-in function
print(sum([2, 3, 4]))

Output:

9

Notice that we didn't define a function to return the sum of the given number, in fact, the sum is a Python built-in function that returns the sum of the given number. In a similar way, if want to access a function that is inside a module, we have to first import that module and then call the function. See the example below:

# importing math module
import math

# python call function and built-in function
print(math.sqrt(9))

Output:

3.0

In this way, we can access other python built-in functions as well.

Python call function with arguments

So far we have learned how we can call a function that does not takes any arguments, In this section, we will discuss different types of arguments that a function can take. A function can take single or multiple arguments depending on the definition of the function. The syntax of function with arguments looks like this:

# syntax of python call function with arguments
def function_name(arg1, arg1, ..., agrn):
      function statements

And we can call the function by passing arguments. See the syntax below:

# python call function with arguments
function_name(arg1, arg2, ...argn)

Integer arguments in python call function

Not let us take the example of the python function that takes integers as an argument and returns the sum of all the arguments. See the example below:

# defining a function
def main(arg1, arg2, arg3):

   # return the sum
   return arg1 + arg2 + arg3

# python call function
print(main(1, 2, 3)

Output:

6

If we provide the number of arguments greater than or less than the defined ones, we will get an error. See the following example.

# defining a function
def main(arg1, arg2, arg3):

   # return the sum
   return arg1 + arg2 + arg3

# python call function
print(main(1, 2, 3, 3 , 4))

Output:

Call function in loop python

String arguments in python call function

Now let us take the example of strings as an argument to python function. See the example which takes three strings as an argument and prints out them.

# defining a function
def main(arg1, arg2, arg3):

   # printing
   print("Your first name is: {}".format(arg1))
   print("your last name is  :{}".format(arg2))
   print("your shcool name is:{}".format(arg3))

# python call function
main("Bashir", "Alam","UCA")M/code>

Output:

Your first name is: Bashir
your last name is :Alam
your shcool name is:UCA

The order of arguments is very important in python otherwise we might get unexpected output. See the example below where we place our first name in the last and school name in the beginning. See the example below:

# defining a function
def main(arg1, arg2, arg3):

   # printing
   print("Your first name is: {}".format(arg1))
   print("your last name is  :{}".format(arg2))
   print("your shcool name is:{}".format(arg3))

# python call function
main("UCA", "Alam","Bashir")

Output:

Your first name is: UCA
your last name is :Alam
your shcool name is:Bashir

Notice that there is not any syntax error but the output is not logical, so the order of argument is very important in python.

Calling a function in python loop

We can even call a function inside from a loop as well. The function will be called each time the loop executes and will stop calling once the loop finishes. In this section, we see how we call a function from a loop.

Python call function inside for loop

A Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can call a function from inside of for loop. See the following example which demonstrates the working of the python call function from inside of for loop.

# defining a function
def main():
   print("calling function from for loop")

# for loop
for i in range(5):

   # python function call from for loop
   main()

Output:

calling function from for loop
calling function from for loop
calling function from for loop
calling function from for loop
calling function from for loop

Notice that the function was called each time the statement inside for loop executes.

Python call function inside while loop

A Python while Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. We can be called from a while loop and can be executed each time unless the loop terminates. See the example below:

# defining a function
def main():
   print("calling function from while loop")
num = 0https://www.golinuxcloud.com/wp-admin/admin.php?page=eos_dp_by_post_type

# while loop
while num<5:

   # python function call from for loop
   main()

   # increase num
   num +=1

Output:

calling function from while loop
calling function from while loop
calling function from while loop
calling function from while loop
calling function from while loop

Note the once the condition becomes false, the while loop terminates.

Python call function from inside function itself

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that we can loop through data to reach a result. Once the condition becomes false, it will stop calling a function, other wise it will continue to infinity.  Let us now take an example of the python call function from the inside function itself. See the example below:

# defining function
def main(num):

   # printing
   print("calling function")

   # if condition
   if num>0:

       # python calling function itself
       main(num-1)
   else:
       pass

# python call function
main(5)

Output:

calling function
calling function
calling function
calling function
calling function
calling function

Notice that the function is called five times from inside itself and once the condition becomes false, it stops calling.

Summary

Python function is a group of codes that perform a specific task.  To get the functionality and features of function, we have to call it. In this tutorial, we learned about the python call function. We learned how we can call built-in function and user-defined function. At the same time, we come across passing and call functions with multiple arguments with different data types. Furthermore, we also came across example and learned how the calling a function from python loops work. In a nutshell, in this tutorial, we learned everything that we need to learn about the python call function.

Further Reading

Python function
python built-in functions
python user-defining functions

Can you call a function within a loop Python?

Calling a function in python loop We can even call a function inside from a loop as well. The function will be called each time the loop executes and will stop calling once the loop finishes.

How do you execute a function in a for loop?

var condition; do { console. log((function(){})()); // output: undefined } while (condition); With a defined condition and a way to toggle it in the loop body, the function can be run as many times as we wish. In this demo, the output is expected since the return value of a function, when not specified, is undefined .

Can you put a function inside a loop?

Accepted Answer "function" as a keyword is only used for defining functions, and cannot be used inside a loop (or inside an "if" or "switch" or other control statement.) The only kinds of functions that can be defined within loops are anonymous functions.

Can I loop a function in Python?

A Python for loop iterates over an object until that object is complete. For instance, you can iterate over the contents of a list or a string. The for loop uses the syntax: for item in object, where “object” is the iterable over which you want to iterate. Loops allow you to repeat similar operations in your code.