My code is supposed to countdown from n to 1. The code completes but returns None at the end. Any suggestions as to why this is happening and how to fix it? Thanks in advance! <
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.