Python yield and return statements are common used in python function, both of them can control the execution process of python function, in this tutorial, we will discuss some differences between them.
Yield | Return |
Return a generator obj | Return a value or obj |
Suspend a functon execution and save its status, function can be executed again. | Suspend a functon execution, function can not be executed again. |
About Python yield, you can read tutorial.
Understand Python yield Statement for Beginners – Python Tutorial
Then we write an example similar to pyhton yield to express the usage of python return.
Create a return example
def returntest(): print ('return 1') return 1 print ('return 2') return 2 print ('return 3') return 3 print ('end') m = returntest()
Print type and value of m
print (type(m)) print (m)
The output is:
return 1 <class 'int'> 1
From the output, we will find:
1. m is an int, not a generator, because returntest() return 1
2. the value of m is 1
3. when returntest() call return 1, it is suspended and not executed contiously.