** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
l = ['Good morning', 'Good afternoon', 'Good night']
for i in l:
print(i)
result
Good morning
Good afternoon
Good night
def greeting():
yield 'Good morning'
yield 'Good afternoon'
yield 'Good night'
g = greeting()
print(next(g))
print(next(g))
print(next(g))
result
Good morning
Good afternoon
Good night
In Python, if there is a yield
inside the def
, that function will be recognized as a generator.
You can process elements one by one by using next ()
.
This may not be of much benefit, but let's take a look at the following code.
def greeting():
yield 'Good morning'
yield 'Good afternoon'
yield 'Good night'
g = greeting()
print(next(g))
print('run!')
print(next(g))
print('run!')
print(next(g))
result
Good morning
run!
Good afternoon
run!
Good night
If you write using a for loop, the process will run from the beginning to the end at once. With the generator, you can stop the process at any time and run another process.
Recommended Posts