Generator in Python? What is Generator?

0

 Generator in Python?  What is Generator?

It is a special iterative statement that is used to create your own iterator statement similar to loop, it will work step by step using next(), which means it will display the first statements, after the next statement under any method block.

the generator will generate all internal content of function using next() and it uses yield() to call back the process.

While is a yield?

The yield will return the control from the method and not finish the complete execution but the return keyword will return the control from the method and terminate the execution.


Now I am defining one simple example to understand generator.

def fun():

    print(10)

    yield

    #return 1

    print(20)

    yield

#caling

x=fun()

next(x)

next(x)


here next() will call generator object and yield will return to control from method and again next() will call and regenerate value from function next block.

Now I am discussing another example of the generator?

It is also used to manage iterative statements or loop-based programs:-

def loop(x):

    for i in range(x):

        yield i


l=loop(5)

while True:

    try:

       print(next(l))

    except StopIteration:

        pass






Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)