In Python, the yield keyword is used to create a generator function. When a function includes a yield statement, it becomes a generator function, which returns an iterator object that can be iterated over with a loop.
The yield statement suspends the function's execution and sends a value back to the caller, but unlike return, the function state is saved, and the function can be resumed later from where it left off.
Here's an example to demonstrate the use of yield:
def countdown(num):
while num > 0:
yield num
num -= 1
This generator function countdown() will return an iterator that will produce a sequence of numbers from num down to 1. We can use a for loop to iterate over the sequence:
for i in countdown(5):
print(i)
5
4
3
2
1
Each time the yield statement is reached, the function's state is saved, and the value of num is sent back to the caller. The next time the generator is called, execution continues from where it left off, and num is decremented until it reaches zero.
0 Comments:
Post a Comment