Python Recursive Function Returning None After Completion
Solution 1:
print(countdown(n))
prints the value returned by countdown(n)
. If n > 0
, the returned value is None, since Python functions return None by default if there is no return
statement executed.
Since you are printing values inside countdown
, the easiest way to fix the code is to simply remove the print
call in main()
:
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
countdown(n-1)
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
countdown(n)
if __name__ == '__main__':
main()
Edit: Removed the else-clause
since the docstring says the last value printed is 1, not 0.
Solution 2:
Remove the print(countdown(n))
and replace it with just countdown(n)
.
What happens is your countdown function returns nothing when n is greater than 0, so that print statement is printing None
. You can also remove your else statement in countdown(n)
- since you never care about the return value of countdown, it serves no purpose.
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
countdown(n-1)
# No need to return a value from here ever - unused in the recursion and
# you don't mention wanting to have zero printed.
#else:
# return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
# Don't print the result of countdown - just call it
#print(countdown(n))
countdown(n)
if __name__ == '__main__':
main()
Solution 3:
You want to return the recursive call to the next invocation of countdown
:
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
return countdown(n-1)
else:
return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
print(countdown(n))
if __name__ == '__main__':
main()
In this way, when the base case is reached, the return value of 0 should propagate back up the stack and be returned.
Unfortunately, however, since your base case returns 0, this results in the printing of 0. But, if you want to return something (think about whether or not you actually need to in this case) this would be how you do it.
If you don't need to return anything, then you don't need to print the result. Further modify
print(countdown(n))
to
countdown(n)
Post a Comment for "Python Recursive Function Returning None After Completion"