3

I've written a function in python to see If i know what I'm doing but unfortunately I'm not. I thought my defined arg variable will hold a number and multiply each of the numbers which *args variable holds and print it all at a time. But, it is giving me the first result only.

This is what I've written:

def res_info(arg,*args):
   for var in args:
    return var*arg

print(res_info(2,70,60,50))

Having:

140

Expected:

140
120
100

I don't understand why I'm not getting all the results. Thanks for taking a look into it.

SIM
  • 21,997
  • 5
  • 37
  • 109

2 Answers2

3

You are on the right path. The problem you had was due to your use of the return statement. Use yield instead.

>>> def res_info(arg,*args): 
        for var in args: 
            yield var*arg 

>>> list(res_info(2,70,60,50))
=> [140, 120, 100]

So, what was happening was, even though your logic was correct, since there was a return statement in the loop, your loop hence was never fully executed and your program scope would come out on the first iteration of the loop itself (ie, when var = 70).

Using yield, solved the problem as it returns a Generator object after all calculations, and hence does not exit the loop like return does.

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
2
def res_info(arg,*args):
    result = []
    for var in args:
        result.append(var*arg)
    return result

print(res_info(2,70,60,50))
Avijit Dasgupta
  • 2,055
  • 3
  • 22
  • 36