Yield (вместо return):
def fr(n): for i in range(n): return i def fy(n): for i in range(n): yield i numr = fr(5) numy = fy(5) print(numr) print(numr) print('-------') print(next(numy)) print(next(numy)) print(next(numy)) print(next(numy)) print(next(numy)) |
0 0 ------- 0 1 2 3 4 |
Yield (генератор):
def subgenerator(): yield 'My' yield 'World' def generator(): yield 'Hello' yield from subgenerator() #Запрашиваем значение из субгенератора yield '!' for i in generator(): print(i, end = ' ') |
Hello My World ! |
Yield (генератор формулы):
def f(n): for i in [x ** 2 for x in range(2, n + 1)]: yield i num = f(5) print(next(num)) print(next(num)) print(next(num)) print(next(num)) |
4 9 16 25 |