I wrote this for
python code and got an unexpected output. The output was a number of zeros then it said “restarting kernel”. Why is the kernel restarting?
def countdown(n): for n in range(0,5): print(n) countdown(n-1) countdown(2)
On the other hand, I tried with if
and there was no problem:
def countdown(n): if n == 0: print("blast of") else: print(n) countdown(n-1) countdown(5)
So why is it not working with for
?
Advertisement
Answer
> def countdown(n): > for n in range(0,5): > print(n) > countdown(n-1) > countdown(2)
In your code above, each function call will call itself recursively 5 times. So the first call is 5, second call there will be 25 calls, third call 125 calls, and the recursive calls went exponentially high, causing the Kernel to restart.
If you use recursive function, there must be an exit condition. There are a few ways to achieve your goal:
(1) recursive with if-condition exit (this is your successful code)
def countdown(n): if n == 0: print("blast off!") else: print(n) countdown(n-1) countdown(5)
(2) recursive with while-condition exit
def countdown(n): while n != 0: print(n) countdown(n-1) return print("blast off!") countdown(5)
(3) for loop (no need recursive)
def countdown(n): for i in range(n, 0, -1): print(i) print("blast off!") countdown(5)
Output:
5 4 3 2 1 blast off!