A Motivating Question

Professor Fox: Loops are technically within recursion.

What does this statement even mean?

When a python program is run, it is compiled to "lower-level languages". These lower level languages (like x86 assembly or RISC-V) don't have the concept of iteration or while loops or for loops. They only have functions, and the ability to set arguments to a function and call it.

This may sound familiar. Lower-level languages implement iteration as recursion.

Implementation

Let's try to do this in Python!

Consider a while loop like the following:

""" Prints the numbers 0-9 """

i = 0 # Initialization
while(i < 10): # Condition
	print(i) # Body
	i += 1 # Updation

Simple enough! As commented above, any loop has four parts: the initialization of the variable we're looping over, the condition that terminates the loop, the body of the loop, and the updation, which brings the variable closer and closer to the termination condition.

Now, let's try to implement this using recursion.

def recur_number(i):
	if i == 10: # Condition (Base Case!)
		return 
	else:
		print(i) # Body
		recur_number(i+1) # Updation

recur_number(0) # Initialization

Notice how all the parts of this recursive function line up to our loop! We have the initialization, which here is the initial function call. Then we have the termination condition, which here is the base case.

<aside> 💡 Notice how the base case is just the inverse of the condition for the while loop. This is because the base case condition is "when should we stop" and the while loop condition is "when should we keep executing this block of code". They are meant to be complementary!

</aside>

Then of course, is the body — the thing that happens before the recursive call. The recursive call is starting the next iteration of our recursive function — equivalent to the next iteration of the while loop.


Conclusion