Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.Use yield.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
def putNumbers(n): i = 0 while i<n: j=i i=i+1 if j%7==0: yield j for i in putNumbers(100): print i |
Explanation
The yield statement is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 |
Leave a Reply