+ 1

What is yield and return

To this day i still dont know what they mean but i see them a lot. Can i please have some help

20th May 2019, 5:56 AM
Dubby
Dubby - avatar
3 Answers
+ 1
Yield and return are used in functions. Return stops the function, and returns a value: def func(): return 6 When you refer to it like x = func(), it will be 6. It can also be used by itself to break the function: def loop(): if (x == 3): return this will break the function if the x value equals 0. Yield means the same as return, except it is used in recursive functions or infinite loops: def inf(): print(7) yield This will cause an infinite loop
20th May 2019, 6:10 AM
Airree
Airree - avatar
0
return: Is a keyword used to return a single object within function call. When return is used, function call is terminated. yield: Is a keyword used to return a generator object. A sequence of objects, similar to lists. The squence can be used in for loops or can be converted to lists to be used. yield will not terminate the function call.
20th May 2019, 7:40 AM
Seb TheS
Seb TheS - avatar
0
Let's go simple. Suppose you method is like doing a calculus. At the end of it, you obtain a result. The return keywords is used to communicate this result to the rest of the program. Some methods don't need to return values, so the return statement is not required in a method. The yield keyword is similar to the return, except that you're not declaring a function but a generator. The difference is that generator keep tracks of their previous calls unlike methods and so can change their behavior over time. See it like this : Suppose you want to represent a cookie jar. Using method to take a cookie and a variable that exists outside the method and counts the amount of cookie remaining in the jar, you can tell if the person can or can't take a cookie (if the jar is empty) Now, using the generator, the amount of cookie remaining can be stored within the generator, meaning that each time you call it, you get a cookie, but once it's empty you get nothing Hope I'm clear. If I'm not, don't hesitate to ask
20th May 2019, 9:15 AM
ThewyShift
ThewyShift - avatar