Functions that Return Values
You have seen that parameter passing provides a mechanism for initializing the variables in a function. In a way, parameters act as inputs to a function. We can call a function many times and get different results by changing the input parameters.
Sometimes we also want to get information back out of a function. This is accomplished by having functions return a value to the caller. You have already seen numerous examples of this type of function. For example, consider this call to the sqrt function from the math library.
Here the value of b*b  4*a*c is the actual parameter of math.sqrt. This function call occurs on the right side of an assignment statement; that means it is an expression. The math.sqrt function must somehow produce a value that is then assigned to the variable discRt. Technically, we say that sqrt returns the square root of its argument.
It's very easy to write functions that return values. Here's an example valuereturning function that does the opposite of sqrt; it returns the square of its argument.
def square(x):
The body of this function consists of a single return statement. When Python encounters return, it exits the function and returns control to the point where the function was called. In addition, the value(s) provided in the return statement are sent back to the caller as an expression result.
We can use our square function any place that an expression would be legal. Here are some interactive examples.
Let's use the square function to write another function that finds the distance between two points. Given two points (a!,yj) and (x2,yj>), the distance between them is calculated from the Pythagorean Theorem as — x^)2 + (j2 — yi)2. Here is a Python function to compute the distance between two Point objects.
def distance(p1, p2):
return dist
Using the distance function, we can augment the interactive triangle program from last chapter to calculate the perimeter of the triangle. Here's the complete program:
# Program: triangle2.py from graphics import *
def square(x):
return dist def main():
win = GraphWin("Draw a Triangle") win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 0.5), "Click on three points") message.draw(win)
# Get and draw three vertices of triangle p1 = win.getMouse()
p1.draw(win)
p2.draw(win)
p3.draw(win)
# Use Polygon object to draw the triangle triangle = Polygon(p1,p2,p3) triangle.setFill("peachpuff") triangle.setOutline("cyan") triangle.draw(win)
# Calculate the perimeter of the triangle perim = distance(p1,p2) + distance(p2,p3) + distance(p3,p1) message.setText("The perimeter is: %0.2f" % perim)
# Wait for another click to exit win.getMouse()
You can see how distance is called three times in one line to compute the perimeter of the triangle. Using a function here saves quite a bit of tedious coding.
Sometimes a function needs to return more than one value. This can be done by simply listing more than one expression in the return statement. As a silly example, here is a function that computes both the sum and the difference of two numbers.
def sumDiff(x,y): sum = x + y diff = x  y return sum, diff
As you can see, this return hands back two values. When calling this function, we would place it in a simultaneous assignment.
num1, num2 = input("Please enter two numbers (num1, num2) ") s, d = sumDiff(num1, num2)
print "The sum is", s, "and the difference is", d
As with parameters, when multiple values are returned from a function, they are assigned to variables by position. In this example, s will get the first value listed in the return (sum), and d will get the second value (diff).
That's just about all there is to know about functions in Python. There is one "gotcha" to warn you about. Technically, all functions in Python return a value, regardless of whether or not the function actually contains a return statement. Functions without a return always hand back a special object, denoted None. This object is often used as a sort of default value for variables that don't currently hold anything useful. A common mistake that new (and notsonew) programmers make is writing what should be a valuereturning function but forgetting to include a return statement at the end.
Suppose we forget to include the return statement at the end of the distance function.
def distance(p1, p2):
Running the revised triangle program with this version ofdistance generates this Python error message.
Traceback (innermost last): File "<stdin>", line 1, in ? File "triangle2err.py", line 44, in ? main()
File "triangle2err.py", line 37, in main perim = distance(p1,p2) + distance(p2,p3) + distance(p3,p1) TypeError: bad operand type(s) for +
The problem here is that this version ofdistance does not return a number, but always hands back the value None. Addition is not defined for None, and so Python complains. If your valuereturning functions are producing strange error messages, check to make sure you remembered to include the return.
Responses

franco8 years ago
 Reply

Alfie2 months ago
 Reply