Search code examples
pythonrecursion

Python function recursion used with try/except error


def main():

    def numSys(x):
        if x == 1:
            print ("BASELINE (1) REACHED!")
            return 1
        else:
            return x * numSys(x-1)

    def userSystem():
        a = input("Initial Number: ")
        try:
            a = int(a)
        except:
            print ("ERROR! Please type a valid number!")
            userSystem()
        
        factorialSum = numSys(a)
        print (factorialSum)
    
    #INITIATE FUNCTIONS
    userSystem()

main()

When inputting a number on the first prompt, it would be successful, but when I test the try/except function by putting a letter first, then putting a number, it would be successful but with a error in the end.

Console log:

Console Log


Solution

  • The problem is (as "Sayse" mentioned) that you're missing a return after you handle the exception.

    def numSys(x):
        if x == 1:
            print ("BASELINE (1) REACHED!")
            return 1
        else:
            return x * numSys(x-1)
    
    def userSystem():
        a = input("Initial Number: ")
        try:
            a = int(a)
        except:
            print ("ERROR! Please type a valid number!")
            # add return to exit the current call of the function - to try again
            # otherwise after finishing the second call of the function, the program will
            # still attempt to call numSys on the bad input - and fail
            return userSystem() 
        
        factorialSum = numSys(a)
        print (factorialSum)
    
    def main():
        #INITIATE FUNCTIONS
        userSystem()
    
    main()