As we have observed in instructional content, technical literature, and official Python documentation, a
return statement, when executed, terminates execution of the function that contains it, and delivers a value to the statement that called the function. Literature on Python also offers much information on handling exceptions.
Python: Simple statements
– Within the above, note: 7.6. The return statement
Python: Errors and Exceptions
– Within the above, note: 8.3. Handling Exceptions
For practice, but at the risk of sowing confusion, let’s take a look at the following code:
# A return statement terminates execution of a function, # and delivers a value to the calling statement. # Which return statements will execute here, # and what will be the output? def fun(num, den): # How many of the return statements in this function will execute? print("fun!") try: return divide(num, den) except: return eggs() finally: return spam() def divide(num, den): print("divide!") return num / den def eggs(): print("eggs!") return "eggs function return value" def spam(): print("spam!") return "spam function return value" print(fun(42, 0))
fun! divide! eggs! spam! spam function return value
For practice, copy it, execute it, modify it, and experiment with it, using Python 3. Can you explain what happens? In particular, which
return statements executed, and why?
Feel free to post explanations, questions, and your modifications of the code.