import sys def fibonacci(n): a, b, counter = 0, 1, 0 while True: if (counter >= n): return a, b = b, a+b yield a counter += 1 f = fibonacci(1) while True: try: print (next(f), end=" ") except StopIteration: sys.exit()
当yield 返回迭代器之后,后面再return 非迭代器的值的话, return返回的值使用迭代器(for a in f)不能找到,next会报类型错误。
原文:http://www.cnblogs.com/secoolar/p/5975371.html