-1

Why does it return None and not the value?

def countdown(n):
    if n == 0:
        return("Blastoff!")
    else:
        print(n)
        countdown(n-1)

print(countdown(20))

1 Answers1

1

This is a simple mistake when first starting with recurssions. When you first call the function with:

print(countdown(20))

It runs the function and reaches the else condition, causing the countdown function to run. But this does not actually return anything for the first function, instead you can think of it like it duplicated your print statement like this:

print(countdown(20))
print(countdown(19))
print(countdown(18))

And so on. Rather what you want to do is answer the first call of the function, by returning instead of printing. That way the first call returns the second call and the second returns the third call etc...

Here is a simple modification:

def countdown(n):
    if n == 0:
        return("Blastoff!")
    else:
        print(n)
        return(countdown(n-1))

print(countdown(20))
Rob Kurt
  • 28
  • 5
  • 3
    Don't wrap your return value expressions in useless parentheses. It's just clutter, and decidedly un-pythonic. – Tom Karzes Apr 18 '23 at 00:59