Factorial


#1

def factorial(x):
factorial(x)
return factorial(x)

when i click on save&submit. it shows me as follows.

Oops, try again. factorial(1) resulted in an error: maximum recursion depth exceeded


#2

It looks like to me, you're doing double recursion without any base case (aka a condition where the recursion should stop). This error is like an equivalent to an infinite loop error.


#3

def factorial(x):
return factorial(x)

when i click on save and submit.

Oops, try again. factorial(1) resulted in an error: maximum recursion depth exceeded


#4

Haha, it's not that simple buddy (unfortunately).

You can use loops to do this. But if you want to do it the recursive way, start with a condition of if x==0 or x==1, return 1. This condition is a base case (and the condition for the recursion to stop). Then you can go from there.

If you want to read more on recursion and how it works, Google is your friend.

EDIT: I also don't recommend using recursion for Python. It's the reason why it's not taught here at Codecademy. It's pretty uncommon to be using recursion. Loops are preferred (and you learned how to do them already). Use what you learned.


#5

can u help me how to write this code.


#6

Factorial works like this: 4!=4*3*2*1 right? Make a function that can replicate the process.

You can assign a variable and equate it to the value 1. That is because 0! And 1!=1 and is the base case to consider.
You can make a for loop from range 2 to whatever your x is +1 because you need to include the last number.
Later on, just increment your variable you assigned by doing randomvariable *= indexofloop.
Return the variable.

This is one way of doing it. There are many other way to replicate the factorial process.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.