panicTrading
panicTrading

Reputation: 5

Why is the result value of a generator function using the yield keyword different?

I am curious as to why the result values of the two conditions are different with the generator function using the yield below.

def test():
    print("function has been called.")
    yield 1
    print("The function was called a second time.")
    yield 2

print("A passing")

t = test()

a = next(t)
print(a)

b = next(t)
print(b)
def test():
    print("function has been called.")
    yield 1
    print("The function was called a second time.")
    yield 2

print("A Passing")

t = test()

a = next(t)
b = next(t)

print(a)
print(b)

Upvotes: 0

Views: 40

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54877

Here's an annotated version of your source that shows what prints when:

def test():
    print("function has been called.")
    yield 1
    print("The function was called a second time.")
    yield 2

print("A passing")

t = test()

a = next(t)     # prints "Function has been called"
print(a)        # prints 1

b = next(t)     # prints "The function was called a second time"
print(b)        # prints 2

print("A Passing")

t = test()

a = next(t)     # prints "Function has been called"
b = next(t)     # prints "The function was called a second time"

print(a)        # prints 1
print(b)        # prints 2

Upvotes: 1

Related Questions