Skip to content
Advertisement

My code caused the kernel to restart. Why is the kernel restarting?

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?

JavaScript

On the other hand, I tried with if and there was no problem:

JavaScript

So why is it not working with for?

Advertisement

Answer

JavaScript

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)

JavaScript

(2) recursive with while-condition exit

JavaScript

(3) for loop (no need recursive)

JavaScript

Output:

JavaScript
Advertisement