top of page

Python Generators | Why We Use Python Generators




Generators are simple functions which return an iterable set of items, one at a time, in a special way.

If the body of a def contains yield, the function automatically becomes a generator function.

Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.


Example 1:


Program to print random number form 1 to 3.


def simpleGen():

yield 1

yield 2

yield 3

# Driver code to check above generator function

for value in simpleGen():

print(value)


Output:

1

2

3


Example 2:


Program to print random number from 1 to 40.


import random

def lottery():

# returns 6 numbers between 1 and 40

for i in range(6):

yield random.randint(1, 40)


# returns a 7th number between 1 and 15

yield random.randint(1,15)


for random_number in lottery():

print("And the next number is... %d!" %(random_number))




If you like Codersarts blog and looking for Assignment help,Project help, Programming tutors help and suggestion  you can send mail at contact@codersarts.com.

Please write your suggestion in comment section below if you find anything incorrect in this blog post.



6 views0 comments
bottom of page