41
Base case and recursive case
You
can write it recursively, like so:
def countdown(i):
print i
countdown(i-1)
Write out this code and run it. You’ll notice a problem: this function
will run forever!
> 3...2...1...0...-1...-2...
(Press Ctrl-C to kill your script.)
When you write a recursive function, you have
to tell it when to stop
recursing. That’s why
every recursive function has two parts: the base
case, and the recursive case.
The recursive case is when the function calls
itself. The base case is when the function doesn’t call itself again … so it
doesn’t go into an infinite loop.
Let’s add a base case to the countdown function:
Dostları ilə paylaş: