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.
This code gives the following output
def sum (a, b): return a + b sum (5,16)
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:
mygenerator = (x * x for x in range (4)) for i in mygenerator: print i,
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 &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
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))
& 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
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.
Topics on Big Data are growing rapidly. From the first 3 V’s that originally characterized Big Data, the industry now has identified 42 V’s associated with Big Data. The list of how we characteriz...
ig Data applications are growing very rapidly around the globe. This new approach to decision making takes into account data gathered from multiple sources. Here my goal is to show how these diverse s...
Pandas for Everyone: Python Data Analysis (Addison-Wesley Data & Analytics Series), 1st Edition. Pandas for Everyone brings together the practical knowledge and insights you need to solve real-worl...
For many decades, some powerful trends have been in place. Computer hardware has rap- idly been getting faster, cheaper and smaller. Internet bandwidth (that is, its information carrying capacity) has...