+ 1

What is the difference between return and yield in a function?

15th Jan 2017, 6:18 AM
Austin Joyal
Austin Joyal - avatar
3 Answers
+ 5
once a function reaches the point where it has to 'return', it will return a value and exit the function def x(): a=5 return(a) b=3 #will not be executed return (b) #will not be executed print(x()) yield means adding the value of 'variable' to the function you created, without exiting the function def x(): a=5 yield(a) b=6 yield(b) #since x now is storing more then one value, it should be a list. print(list(x())) -> this will print [5,6]
15th Jan 2017, 8:57 AM
Badmephisto
Badmephisto - avatar
+ 4
With 'return' the execution of function is stopped, and its context ( local scope of variables ) is deleted, when 'yield' don't and just suspends execution to resume later... and keeping the context. 'Yield' cannot replace 'return' as you want. 'Yield' is designed for the particular use of 'generators' and 'iterables' objects ;)
15th Jan 2017, 6:30 AM
visph
visph - avatar
+ 2
def fab(max): n, a, b = 0, 0, 1 while n < max: yield b # print b a, b = b, a + b n = n + 1 …… #I tried to translate it in my poor English~~~~~~:P 简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。 The yield can turn a function to a generator. The function with the yield is no longer an ordinary function, Python interpreter will viewed it as a generator. Fab function will not be performed, it will returns an iterable object! When the for loop is executed, the loop will execute Fab code inside the function each time, when performe to yield b, Fab function returns an iteration value. When the iteration execute next time, code continues to execute from the next statement of yield b, whereas the local variables of the function is exactly the same as before interrupts execution, so the function continues to perform until meeting yield again.
17th Mar 2017, 2:44 PM
Troy Liu
Troy Liu - avatar