+ 2
Why this code is showing error can you explain?
11 Answers
+ 4
Payal Sharma , you didn't declare the base case in the recursion, so the function is called infinitely. Look at the correct code.
https://code.sololearn.com/cg17G7G9yY1F/?ref=app
+ 2
You need stop condition in recursive method
Like
if x==1:
return 1
+ 1
You have written the code in such a way that the recursion keeps going deeper until it runs out of depth, (processing power, time, etc)
You could do this to get a result
def factorial(x):
return x * (x-1)
print(factorial(5))
But I don't think this was your objective.
The main problem was there was no way to stop the recursive loop
+ 1
Justus , in fact it's needed, because 0! = 1. If you call the function with 0 as argument, again it will run infinitely and will not calculate this specific case.
0
TheWh¡teCat 🇧🇬 the first condition was ok (if x==1) to exit the loop. x==0 isn't required
0
TheWh¡teCat 🇧🇬 oh. I didn't check that
0
def factorial(x):
if x == 1:
return x
else:
return x*factorial(x-1)
print(factorial(5))
0
you just missed one condition
0
you are missing the base condition of the recursive method
if x==1:
return 1
- 1
Just type like this :
def factorial(x):
return x*x-1
print(factorial(5))