The return statement causes a python function to exit and give back a value to its caller. The purpose of functions in general is to take in inputs and return something. A return statement, once executed, immediately terminates execution of a function, even if it is not the last statement in the function.
Functions that return values are sometimes called fruitful functions.
Given code gives the following output
def sum(a,b): return a+b sum(5,16)
Generators are iterators or iterables like lists and tuples, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly:
mygenerator = (x*x for x in range(4)) for i in mygenerator: print i,
0 1 4 9
We cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, 4 and end calculating 9, one by one.
yield is a keyword that is used like return, except the function will return a generator.
We use the following code to access the returns from a generator as follows
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: # print i, print(next(mygenerator)) print(next(mygenerator)) print(next(mygenerator)) print(next(mygenerator)) print(next(mygenerator))
<generator object createGenerator at 0xb71e27fc> 0 1 4 9 Traceback (most recent call last): File "yieldgen1.py", line 12, in <module> print(next(mygenerator)) StopIteration
The yield statement in above example created mygenerator. It can be used only once. We use the command next(mygenerator) to calculate; it can be used once: it first calculates 0, then forgets about it and then second time it calculates 1, third time 4 and fourth it calculates 9, then at fifth time it throws up an error of StopIteration as list elements have been exhausted.