Function generator in Python

Normally when we use for loop and range() method in Python it stops at just before the range we mentioned.

It looks like :

for i in range(10):
print(i)

And it reads from 0 to 9 and stops.
Basically through the range() method of Python, we pass three variables – start, stop and step. In between these three variables, by default the values of ‘start’ and ‘stop’ are pre-set. ‘start’ is 0 and ‘stop’ is 1. So it starts from 0 and each step it iterates 1 step and stops at 9. In it the ‘stop’ value remains inconclusive.
But we can make the ‘stop’ value conclusive by the following method:



#!/usr/bin/python3

def main():
    GetARangeOfNumber()


def GetARangeOfNumber():
    for index in IteratingStepByStep(0,10, 1):
        print(index, end=' ')

def IteratingStepByStep(start, stop, step):
    number = start
    while number <= stop:
        # print(number)
        yield number
        number += step

if __name__ == "__main__":
    main()

It will loop through each number and finally stops at 10.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s