A journal entry for fundamental lessons that advance programming fluency:
- What a return statement does:
When a function ‘returns’ a value, it doesn’t go anywhere in particular. What is special about a value that is returned is that it is now available to be called by other methods and functions.
For example, here’s a function utilizing both
print()
andreturn
:def foo(): print("hello from inside of foo") return 1
Now you can run code that calls foo, like so:
if __name__ == '__main__': print("going to call foo") x = foo() print("called foo") print("foo returned " + str(x))
If you run this as a script (e.g. a
.py
file) as opposed to in the Python interpreter, you will get the following output:going to call foo hello from inside foo called foo foo returned 1
Logical example supplied by Nathan Hughes.
- How recursion works:
If you define a small script with a nested return statement, the untrained logic will present a computational fallacy. Note the example:def f(n):
… if n<2:
… return 1
… return f(n-1) + f(n-2)
x = f(3)Print x
How will this code work? The tough spot is that this algorithm is especially designed to fool you. If you calculate the computation algebraically, you get the same answer as you would have if you understood where recursion was supposed to take place — in this case using the integer ‘3’. Take a moment to run the numbers in your head.
Now, If you were to shove in the number 2, different devils come out of the details. Try coding this up in a Python interpreter and see what you come out with.
3 gets you 3. 4 gets you 5. But 2 gets you 2, not 1. Why do you think that is? Understanding recursion means that when you get to the second return line, you understand that each f(someValue) must be looped back up through the first if statement again and be subject to satisfying the first return statement again.