Home »
Python
Python yield Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
The yield is a keyword (case-sensitive) in python, it is used to suspend the execution of a function and returns the value, if next time function calls, it resumes the function execution from the next statement where last execution was suspended.
Note: return keyword and yield keywords returns the value to the called function, but the return statement terminates the execution of the function, while yield statement just suspends the execution of the programs.
Syntax
Syntax of yield keyword:
def function_name():
statement(s):
yield value
statement(s)
Sample Input/Output
def sampleGenerate():
yield 100
yield 500
yield 800
Example 1
Demonstrate the example with yield keywords by returning values multiple times on function calls.
# python code to demonstrate example of
# yield keyword
def sampleGenerate():
yield 100
yield 500
yield 800
# main code
for value in sampleGenerate():
print(value)
Output
100
500
800
Example 2
Find the squares of the numbers till a given maximum value of the square from main function.
# python code to demonstrate example of
# yield keyword
def generateSquare():
count = 1
while True:
yield count*count
count += 1 # next function execution
# resumes from here
# main code
for i in generateSquare():
print(i)
if i>=100:
break
Output
1
4
9
16
25
36
49
64
81
100