How do Python functions return and give objects?

Python Methods and Functions

The return statement causes the python function to exit and returns a value to the caller. The purpose of functions in general is to accept input and return something. The return statement after execution immediately terminates the function execution, even if it is not the last statement in the function.

Functions that return values ​​are sometimes called fruitful functions.




Example

This code gives the following output


 def sum (a, b): return a + b sum (5,16) 



Output

 21 



Generators

Generators are iterators or iterators, such as lists and tuples, but you can only iterate over them once. This is because they do not store all values ​​in memory, they generate values ​​on the fly:






Example

 mygenerator = (x * x for x in range (4)) for i in mygenerator: print i, 



Output

 0 1 4 9 

We cannot execute a second time for i in mygenerator, because generators can only be used once times: they calculate 0, then forget about it and calculate 1, 4 and finish calculating 9, one by one.




Yield

yield &this is the keyword that is used like return, except that the function will return a generator.

We use the following code to access the generator as follows




Example

 def createGenerator (): for i in range (4): yield i * i # this code creates a generator mygenerator = createGenerator () print (mygenerator) # mygenerator is an object! # for i in mygenerator: # p rint i, print (next (mygenerator)) print (next (mygenerator)) print (next (mygenerator)) print (next (mygenerator)) print (next (mygenerator)) 



Output

 & lt; generator object createGenerator at 0xb71e27fc & gt; 0 1 4 9 Traceback (most recent call last): File "yieldgen1.py", line 12, in & lt; module & gt; print (next (mygenerator)) StopIteration 



Explanation

The yield statement in the above example was created by mygenerator. Can only be used once. We use the next (mygenerator) command to compute; it can be used once: first it evaluates 0, then forgets about it, and then it evaluates 1 a second time, the third time &4 and fourth &9 and then throws a StopIteration error for the fifth time because the list items were exhausted.







Get Solution for free from DataCamp guru