Let’s continue our walk-through of the countdown function. We’ll skip a few steps for brevity…
Step 21: We call countdown(0).
Step 22: We print number (that is, 0) to the console.
Step 23: We call countdown(-1).
Step 24: We print number (that is, -1) to the console.
Uh-oh. As you can see, our solution isn’t perfect, as we’ll end up infinitely printing negative numbers.
To perfect our solution, we need a way to end our countdown at 0 and prevent the recursion from continuing on forever.
We can solve this problem by adding a conditional statement that ensures that if number is currently 0, we don’t call countdown() again:
| | def countdown(number): |
| | print(number) |
| | |
| | if number == 0: |
| | return |
| | else: |
| | countdown(number - 1) |
Now when number is 0, our code will not call the countdown() function again but instead just return, thereby preventing another call of countdown().
In recursion terminology, the case in which our function will not recurse is known as the base case. So 0 is the base case for our countdown() function. Again, every recursive function needs at least one base case to prevent it from calling itself indefinitely.