Python Resources

Updated on Feb 5 2022

Python Resources

Deborah R. Fowler



Recursion in Python

Posted on Oct 13  2019
Updated on Oct 13  2019

Recursion is defined as a function that calls itself. "To understand recursion, you must first understand recursion" Humor.

Seriously though, there are times to use recursion and many times not to. It is one way to solve a problem.

In order for this to work there must be some way of ending the recursion (just as a while loop needs a condition to end and if you forget you end up with an infinite loop, you want your recursive function to know when to quit). The structure of a recursive function involves a base case where the recursive call returns to where it was called. The computer "remembers" every previous state and returns, like every good function, to where it was called.

Advantages and disadvantages listed https://www.programiz.com/python-programming/recursion#what
If you scroll to the bottom of the page on the above article you will see a list of advantage and disadvantages.
Bottom line:

In Summary:

Here are some more basic visual examples to explain recursion:
MISSING IMAGE

Also Midpoint Squares:

MISSING IMAGE

Adding Random colors to the above code:

MISSING IMAGE

Have fun! Recursion is useful, but remember, it is meant for complex problems. You could make a square draw recursively but it is not recommended. That would not be a good use of recursion. Try some of your own, combine it with loops, explore! For example, how would you create these?

MISSING IMAGE MISSING IMAGE MISSING
      IMAGE