python print inside vs outside function?
This question already has an answer here:
In your code fibon
is a generator function. And when you call it returns generator object. You could remove yield
from function
def fibon(n):
a = b = 1
for i in range(n):
a, b = b, a + b
print(a) # move here inside function but doesnt print?
fibon(20)
or construct list from generator object
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
print(a) # move here inside function but doesnt print?
list(fibon(20))
The yield
statement makes the function returns a generator object
, not just a function.
In short, python generators are iterators. PEP 255 that describes simple generators. Generators are used either by calling the next method on the generator object or using the generator object in a for loop.
To execute the generator, you need to iterate over it. So, for x in fibon(20)
does the iteration, while fibon(20)
returns a generator object.
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
fibon(5)
<generator object fibon at 0x00000000034A6A20>
for i in fibon(5):
print i
# list() can be used too, because it accepts generator as a param
fibos = list(fibon(5))
If you just change the yield
statement to print
, you get regular function. But I wouldn't recommend that with fibonacci, the yield option is the way to go.
>>> fibon
<function fibon at 0x0000000002D31C88>
如果目标只是打印数字,只要用print
替换yield
就足够了。
上一篇: 了解Python中的yield
下一篇: python打印内部vs外部功能?