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.
Program to print random number form 1 to 3.
# Driver code to check above generator function
for value in simpleGen():
Program to print random number from 1 to 40.
# 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
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 firstname.lastname@example.org.
Please write your suggestion in comment section below if you find anything incorrect in this blog post.