Reputation: 403
I am going through Learn Python the Hard Way, and am on Exercise 21 where the return statement is used. When going through the code, I understand what the return statement is doing, but I just don't get Zed Shaw's description entirely. I want to make sure I am not missing something. The exercise has this code
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
And Shaw describes the return statement like this:
- Our function is called with two arguments: a and b.
- We print out what our function is doing, in this case "ADDING."
- Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
- Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.
On number three, when he says "do something backward" and that it returns "a and b" (when he said 'them'), it seems like he is returning the expression, or just the two variables, rather than the numerical solution of the two. I am not exactly sure what it is saying.
Upvotes: 0
Views: 125
Reputation: 296049
The third step given in the book is inaccurate (words modified below are in italics):
- Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
This would be better written as:
- Then we tell Python to do something kind of backward: we return the result of adding a + b. You might say this as, "I add a and b then return the result."
Upvotes: 6
Reputation: 2930
Don't worry, it's not too complicated.
The return
statement tells the computer to take the next value, and to return that to where the function was called from.
For example, suppose you have a function:
def foo():
return 5
And then you say:
x = foo()
Then you will have x=5
. Because foo()
returns 5
. You can think about it as that in the main body of code, the foo()
expression gets replaced with whatever return
says.
Another example:
def foo(a):
return 5+a
x = foo(3)
Then you have x=8
.
Upvotes: 1