2

Hi: I am testing the recursive function like this:

def countdown(n):
    if n == 1:
        print 1
    elif n > 1:
        print countdown(n - 1), '\n', n
    else:
        pass

The function is to count down from $n$ to $1$. but why I get 'None' in the output?

In [2]: countdown(4)
1
None  
2
None 
3
None 
4

Thank you.

pinseng
  • 301
  • 2
  • 6
  • 11
  • In order to solve this riddle, add some output before the place you suspect to generate the unexpected output and after. With that, circle in on the actual piece of code that causes the unexpected output. Using that technique, it should have been trivial to find that the second `print` outputs two lines, the first of which is `repr(None)`. Since the only thing in the first line is `countdown(n - 1)`, it would be obvious that printing the output of that function prints "None". – Ulrich Eckhardt Aug 03 '15 at 19:24

3 Answers3

4

When the function completes without returning anything, it implicitly returns None. Your function has no return statement, so print countdown(n-1) will print None.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • 1
    The `None`s are coming from the `print` statement in the function, not the interpreter. At least the ones shown in the question. – Scott Hunter Aug 03 '15 at 19:21
3

You are printing what countdown returns, but it doesn't return anything.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
2

Your recursive function has no return statement. Because functions always must return something, the default is to return None.

Remove the print statement from the recursive function call, and put it on a separate line:

elif n > 1:
    countdown(n - 1)
    print n

Note that the else: pass block is entirely redundant. You can omit that part, you don't have to have an else statement.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343