-4

I'm trying to run a For loop in a function but when I call the function only the first value is returned.

I've tried ending the loop with a print instead of a return, which gets the correct result (It prints every value in the loop) but means a none is added to the answer as there is now a double print.

PLEASE NOTE: In these examples one could one could just print "value" directly but I want to be able to run through a for loop, to add complexity later.

The function ending in return only prints out the first value of the `For loop``:

def thing():  
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
    return x

print(thing())
# 1 

This function uses print and gives the correct result except with a none added due to the double print.

def thing1():
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
     print(x)

print(thing1())

>>>  OutPut:
1
2
3
4
5
6
7
8
9
10
None

How exactly can I get the second result(the full printed loop of all values) whilst removing the "None"?

  • `return` exits from the function. If you want to return the full sequence, then just `return value` - there's no need for a loop. – Robin Zigmond May 12 '19 at 20:01
  • The `None` you see isn't printed by the `thing1()` function. Your `thing1()` prints exactly what you want. The `None` is probably from an other display something else after in the code. – Alexandre B. May 12 '19 at 20:06
  • @RobinZigmond this is true but I'd like it to run through the loop (ie to be able add more complexity like an if statement) – X-cessive Pupil May 12 '19 at 20:20
  • @AlexandreB. If it wasn't a function that would be the case. This can be explained here: https://stackoverflow.com/questions/7053652/function-returns-none-without-return-statement – X-cessive Pupil May 12 '19 at 21:27
  • @X-cessivePupil Thank you for the link ! – Alexandre B. May 12 '19 at 23:36

2 Answers2

0

After return is run, the function stops evaluating. If you'd like to return everything in a for loop, return a list of its outputs:

ret_vals = []
for x in value:
    ret_vals.append(x)

return(ret_vals)    

You can print them on new lines like you specified like so:

out = func()
for x in out:
    print(x)
Alec
  • 8,529
  • 8
  • 37
  • 63
0

You can use generators to return the sequence.

The generator follows the same syntax as a function but, instead of writing return, we write yield whenever it needs to return something.

def thing():  
   value = ( 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
   for x in value:
    yield x

res = thing()
for i in res:
  print(i, end=' ')

Output:

1 2 3 4 5 6 7 8 9 10 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Sneha R
  • 56
  • 2