Fruitful Function

Functions that perform an action and return a value are called fruitful functions.

Example:

def area(radius):
a = math.pi * radius**2
return a
area(2)

Sometimes it is useful to have multiple return statements, one in each branch of a conditional

def absolute_value(x):
if x < 0:
return -x
else:
return x
  • As soon as a return statement runs, the function terminates without executing any subse- quent statements. Code that appears after a return statement, or any other place the flow of execution can never reach, is called dead code.
  • In a fruitful function, it is a good idea to ensure that every possible path through the program hits a return statement.
# incorrect function
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x

This function is incorrect because if x happens to be 0, neither condition is true, and the function ends without hitting a return statement.

References

  • Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
  • Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
  • John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
  • Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
  • Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
  • Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
  • Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.