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

Question:

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?

Asked By: Nidhi Kushwaha

||

Answers:

Your if recursive version is the correct form for recursion.

With a for loop you don’t need a recursive function, just iterate from n to 0, and when you’re done, print your blast off.

def countdown(n):
    for in range(n,0,-1):
        print(n)
    else:
        print("blast off")

NB. I am using the for/else construct here, it means the else block with be executed when the for loop completes fully without break.

countdown(5) gives

5
4
3
2
1
blast off
Answered By: ljmc

Code you posted:

def countdown(n):
    if n == 0:
        print("blast of")
    else:
        print(n)
        countdown(n-1)
countdown(5)

This is a recursive function because it has a base case (if n == 0:).

This code has a loop built in due to the recursion: countdown(n-1)

If you want a for loop, then really you don’t need recursion.

Answered By: quamrana
>    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!
Answered By: perpetualstudent