Today is my 23 day of #100DaysOfCode and #python. Like yesterday today I also revised python for everybody from coursera and learned more about basic of python.
I had tried to write some code in mathematical problem regarding to python. Today I have start to learn about python generator. Try to write some simple code on python generator. I found python generator are similar to python function but there are some dissimilarity of them.
Simple Code On Python Generator
Simply speaking a generator is a function that return an object(iterator) which we can iterate over one value at a time. It is fairly simple to create a generator in python .It is as easy as defining a normal functions, but with a yield statement instead of return statement .
def my_gen():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
for item in my_gen():
print(item)
If a function contains at least one yield statement (it may contain other yield or return statements) it become a generator function. Both yield and return will return some value from a function.
The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive call.
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
for char in rev_str("hello"):
print(char)
Once the function yields, the function is paused and the control is transferred to the caller. Local variable and their states are remembered between successive calls. Finally , when the function terminates, stopIteration is raised automatically on further calls.
a = my_gen()
next(a) ,next(a), next(a)
When this code is run it gives following output.
This is printed second
This is printed at last
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-57-b3ab980ac96b> in <module>
----> 1 next(a) ,next(a), next(a)
StopIteration:
Day 23 of #100DaysOfCode and #Python
— Durga Pokharel (@mathdurga) January 16, 2021
* Revised Python Basic
* Did some code in mathematical problem regarding to python
* Learned about python Generator
* Some simple code in python Generator pic.twitter.com/1UsiOFdsWG
Top comments (0)