Use the function in an expression or in an assignment statement

The name on the left side of the equals sign in the assignment statement now stores the value that the function returned, as shown:

>>> my value = my function(3) >>> print my value 45 "

If a function has no return statement, or if the return statement doesn't specify what to return, the function returns None (a built-in name). Here's a function without a return statement.

>>> def no return function(b): ... print b

>>> my value = no return function(3) 3 " " "

So why would you ever want a function without a return statement? Some functions manipulate an item in place instead of returning a new item. Some functions perform an action that doesn't need to return a result (for example, saving a message to a log). Such a function might not need a return statement.

Tip The return statement not only passes a value out of the function, it also stops

Python from running the rest of the code in the function. So return either should be the last statement in the function or should be used in conditional code, such as an if block, to jump out of the function when a certain condition is met.

Was this article helpful?

0 0

Post a comment