1

I am writing this code to get the 10! ,however, I believe I have an infinite loop in there since it keeps repeating the same error code. I am trying to find the issue but can not seem to.

def calculatingfactor(num2cal): """this fuction will be calculating a mathematical factorial""" if num2cal == 1: returnvalue = 1 elif num2cal <= 0: returnvalue = 0 else: print("Calculating the facterial of {}".format(num2cal)) variable2 = calculatingfactor(num2cal - 1) returnvalue = calculatingfactor(num2cal*variable2) return #main code first_fact=calculatingfactor(10) print (first_fact) 
1
  • I see that you have a good understanding of the factorial, however: why are you calling the recursive function twice? That second call will never end making you get a "StackOverflowException". You should update the 10th line of code for -> returnvalue *= variable2. Also note that the condition "elif num2cal <= 0" will make your result 0. Consider reviewing it. Commented Oct 30, 2018 at 2:58

1 Answer 1

1

The recursive case of your code looks incorrect to me. You should be calling the same function with num2cal decremented by one, then returning the current value multiplied by whatever that recursive call returned.

def calculatingfactor(num2cal): if num2cal == 1: return 1 elif num2cal <= 0: return 0 else: print("Calculating the facterial of {}".format(num2cal)) variable2 = calculatingfactor(num2cal - 1) return num2cal*variable2 # main code first_fact=calculatingfactor(10) print (first_fact) 
Sign up to request clarification or add additional context in comments.

3 Comments

I did try that Tim, I still unfortunately get the same error TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' and the error prints out about 20 times
@JoanthanMaldonado The above code is working in this demo. You must have some other problem in your code.
You were correct with your edit and it was just an error on my end. Thank you !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.