Home > Software design >  I wrote this python code and got unexpected output. The output was number of zeros then it said rest
I wrote this python code and got unexpected output. The output was number of zeros then it said rest

Time:08-19

def countdown(n):
    for n in range(0,5):
        print(n)
        countdown(n-1)
countdown(2)

I tried it with 'if' and there was no problem but it is not working with 'for'.

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

CodePudding user response:

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 normally (no break).

countdown(5) gives

5
4
3
2
1
blast off

CodePudding user response:

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.

  • Related