Titter
Titter

Reputation: 21

Returning a value of a function does not work over multiple iterations via for loop

I defined the following function:

def test():
    return 1

And once I type the following in the console:

test()

I get the expected value of 1 returned. But I want to 1 to be returned twice, so I type this in the console:

values = [1,2]
for i in values:
    test()

But instead I get no output now. Why does it not produce any output and how could I edit it so it would?

Upvotes: 0

Views: 114

Answers (5)

Samwise
Samwise

Reputation: 71454

As the other answers point out, doing a print inside the loop will print the value. The subtlety that nobody else has mentioned is that the reason the for loop doesn't work on its own is that a for doesn't return a value. The expressions inside of the loop are evaluated but their values are discarded.

If you want to do a loop that does return the value of the expressions inside it (so that you can see those values in the interpreter without having to print them, or do something else with those values in the next part of your program), a list comprehension is a good way:

>>> def test():
...     return 1
...
>>> values = [1,2]
>>> [test() for i in values]
[1, 1]

Upvotes: 0

Tanmay
Tanmay

Reputation: 111

just put a print on test() inside the for loop, like below

for i in values:
    print(test())

Now output would be:

   1
   1

Upvotes: 0

user14269391
user14269391

Reputation:

I don't know why it doesn't work for you, but when I run this code on my computer, everything is fine

def test():
    return 1

print("First case:")
print(test())

print("Second case:")
list = [1,2]
for i in list:
    print(test())  

OUTPUT:

First case:
1
Second case:
1
1

Upvotes: 0

Owen Valentinus
Owen Valentinus

Reputation: 394

First of all, you should fix your for loop. If you want to specify the number of times a for loop should run, you should use range() function.

for x in range(2):
    test()

and second, return value doesn't output the values unless you print it, i.e print(test())

Upvotes: 0

Moosa Saadat
Moosa Saadat

Reputation: 1167

Actually, you need to print the returned value to display it in console. Try this:

values = [1, 2]
for i in values:
    print(test())

You might ask why did it work in first case. I don't have the exact answer but I can give you a clue. Returned value of "last line of code" is automatically printed. This is not the right/good explanation. Maybe someone else can help with this.

Btw, here's a better way of writing the above piece of code:

for i in range(2):
    print(test())

Upvotes: 0

Related Questions