I CSDN blog column: HTTPS: //blog.csdn.net/yty_7
Github Address: https: //github.com/yot777/Python-Primary-Learning
7.4 function returns a value --return and yield
return : return a call to a function or set of values
yield : each encounter yield when the function will pause and save all of the current operating information, returns the current value of the variable, and when a function is executed the next method continues to run from the current position.
yield , for example :
def func(n):
for i in range(2,n):
print("i=",i)
print("i*i=",i*i)
yield i*i*i
for s in func(5):
print("s=",s)
Explanation: When func (n-) function is passed the parameter n = 5 , the call will go to func function inside the for loop
for I in Range (2,5) the cycle from 2 starts traverse to 4
First i value of 2 :
Performing Print ( " I =", I ) the output I = 2 , the implementation of Print ( " I * I =", I * I ) output I * I =. 4 , and finally I * I * I
As a whole FUNC (n-) function return value to S , execute print ( "s =", s ) output s = 8
Then i value of 3 :
Performing Print ( " I =", I ) the output I =. 3 , performing Print ( " I * I =", I * I ) output I * I =. 9 , and finally I * I * I
As a whole FUNC (n-) function return value to S , execute print ( "s =", s ) output s = 27
Finally i value of 4 :
Performing Print ( " I =", I ) the output I =. 4 , the implementation of Print ( " I * I =", I * I ) output I * I = 16 , and finally I * I * I
As a whole FUNC (n-) function return value to S , execute print ( "s =", s ) output s = 64
Please 6.6 combined cycle structure - content generator, think carefully about the above example.
If you do not use the yield and the use of return , I want to return multiple values function can only be called multiple times.
return example :
def func(i):
print("i=",i)
print("i*i=",i*i)
return i*i*i
s=func(2)
print("s=",s)
s=func(3)
print("s=",s)
s=func(4)
print("s=",s)
运行结果:
i= 2
i*i= 4
s= 8
i= 3
i*i= 9
s= 27
i= 4
i*i= 16
s= 64
Reference Tutorial:
Liao Xuefeng of Python tutorials
https://www.liaoxuefeng.com/wiki/1016959663602400
Liao Xuefeng's Java Tutorial
https://www.liaoxuefeng.com/wiki/1252599548343744
Python3 Tutorial | Tutorial rookie
https://www.runoob.com/python3/
If you feel Benpian chapter has helped you, welcome attention, comments, thumbs up! Github welcome you Follow, Star!