简体   繁体   中英

unexpected output using yield statement

I now read about the difference between return and yield statements and understand everything, when I applied some tests as the tutorial I follow said that there is 3 option I can use it to get out the result by yield one of them is the next method and as you know to use the next method you should create it manually by adding it more than one time, the test I did is:

first case:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(i)

the expected result here is:

0
1
4
9
16
25
36
49
64
81

and it works fine as expected

second case:

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print(next(sq))

so, instead of print the next(sq) multiple times I put it into a loop and used it one time so, it should printout same result as the first function but instead, it printout that result:

1
9
25
49
81

I ran debug but I couldn't understand what happens exactly

You are yielding in the for loop, then immediately yielding again with next()

def test(n):
    yield n*n

def getSquare(n):
    for i in range(n):
        for x in test(i):
            yield x

sq = getSquare(10)
for i in sq:
    print("Before next: ", i)
    print("After next:  ", next(sq))

Output:

Before next:  0
After next:   1
Before next:  4
After next:   9
Before next:  16
After next:   25
Before next:  36
After next:   49
Before next:  64
After next:   81

The code for i in sq: iterates on each value of the iterator consecutively, but at each iteration, you explicitly call next to get the next, you forget the value in i and move on, so you print one value over 2

sq = getSquare(10)
for i in sq:
    print("current ", i)
    print("next:   ", next(sq))


current  0
next:    1
current  4
next:    9
current  16
next:    25
current  36
next:    49
current  64
next:    81

To use only next to move on the iterator, use like this and wrap ith a try to handle the StopIteration error

sq = getSquare(10)
try:
    while True:
        i = next(sq)
        print("current ", i)
except StopIteration:
    print("End")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM