I thought I had a decent understanding of how functions work and how they can be assigned to variables. However, I was just looking over some Learn Python the Hard Way exercises I read a few months ago (most notably exercise 21) and noticed some interesting things about the interpreter’s output.
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
Outputs:
>>> add(30, 5)
ADDING 30 + 5
35
Why does this show 35? Shouldn’t you have to write “print add(30, 5)” for the return value to show up?
>>> age = add(30, 5)
ADDING 30 + 5
>>> age
35
The variable assignment looks like it calls the function and outputs the print statement and not the return value… but the variable itself shows the value 35, why doesn’t the variable assignment do the same?
I hope these questions make sense. I’m just trying to get a better idea of what’s going on behind the scenes. If anyone has any outside reading, let me know!
This is because the interactive interpreter displays the return value of any expression you type.
The function you posted has two lines. In the first line, it
print()s the value to the standard output. The secondreturns the same value out of the function. As I stated above, this also gets written to the standard output in the interactive interpreter.If you were to run your script via the command line (i.e. not in the interactive interpreter:
You would notice that this return value is no longer printed to the standard output.