Python recursive function returning none after completion

后端 未结 3 2063
时光说笑
时光说笑 2021-01-23 19:15

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! <

3条回答
  •  日久生厌
    2021-01-23 19:40

    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()
    

提交回复
热议问题