Yield statement is used with the function when we want to return series of values over time instead of returning single value at the end of the function.
If we use yield statement with function then the function become generator function, the yield statement suspend the function and send back value to the caller of the function and resume where it is left off.
How Yield statement works with function?
- With Yield statement function pause the execution and return the value to the caller.
- You can resume the state of the function.
- Execute the function from previous state and generate next result instead of starting from the first..
- We can call yield statement multiple times.
Example:
# Python 3 Code
# Yield statement with function
def myfunction(a, b):
add = a + b
yield add
sub = a - b
yield sub
mul = a * b
yield mul
div = a % b
yield div
# Run Generator with for loop to get all values
for value in myfunction(35,54):
print(value)
Output:
89
-19
1890
35
Example with Return statement:
# Python 3 Code
# Return statement with function
def myfunction(a, b):
add = a + b
sub = a - b
mul = a * b
div = a % b
return(add, sub, mul, div)
# Get Return value in variable and print the result
output = myfunction(35,54)
print("Addition: ", output[0])
print("Subtraction: ", output[0])
print("Multiplication: ", output[0])
print("Division: ", output[0])
Output:
Addition: 89
Subtraction: 89
Multiplication: 89
Division: 89
Difference between Yield and Return Statement in Python
Return Statement |
Yield Statement |
Returns the value to the caller |
Yield returns the value to the caller and preserve the current state |
Return statement runs only one time |
Yield statement can run multiple times |
Code written after return statement wont execute |
Code written after yield statement execute in next function call |
Every function calls run the function from the start. |
Yield statement function is executed from the last state from where the function get paused. |