What is the difference between return and yield in a function? | Sololearn: Learn to code for FREE!
+ 1

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

15th Jan 2017, 6:18 AM
Austin Joyal
Austin Joyal - avatar
3 Antworten
+ 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