1
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1     
    return 'done'

print(next(fib(6)))
print(next(fib(6)))
print(next(fib(6)))

the result is 1,1,1. However, if I change the content in print() as below:

f = fib(6)
print(next(f))
print(next(f))
print(next(f))

the result will be 1, 1, 2. Why does this happen?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Eva Red
  • 569
  • 1
  • 5
  • 11

1 Answers1

4

The call print(next(fib(6))) always creates a new instance of the fib generator and yields one value from it, you then discard it.

On the other hand:

f = fib(6)
print(next(f))
print(next(f))
print(next(f))

creates an instance f of the generator fib and yields three values from it.

Also, using max as the parameter name is frowned about since, in the local scope at least, you're masking a built-in function that has the same name.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253