The instructions say:
Define a function factorial that takes an integer x as input.
Calculate and return the factorial of that number.
I have been reading the forums and I understand the solution (even though I am curious about the aim of this exercise since I don’t recall having learn the factorial function before in previous exercises), but I am very puzzled about something. The forums say that factorial is a recursive function, which I take to mean something like it will automatically repeat itself or something. But I don’t understand…why can’t we just take factorial(x) straightaway, where x is a number? if factorial is a function recognised by Python why can’t we just use it directly?
I understand what that means, and I also learnt in Math in school that 0! = 1. But I don’t understand why you can’t apply it directly since ultimately you are still having to use the factorial function directly (if you don’t do the iteration method)
yup I tried it and got an error message, which is why I am trying to find out more about why it doesn’t work by asking here on this forum.
I was essentially wondering since you are going to be using the factorial function eventually anyway when doing x * factorial(x - 1), why can’t I use it directly with factorial(x) ?
Sorry if this is an ultra beginner question, because that is precisely what I am
With the comment in the brackets I meant given that indentations are correct. I know it is wrong in my reply, but I forgot how to do it (I could do it once a few weeks back) and I can’t find how. I thought it was triple quotation marks with [python] but it didn’t work so yeah messy indentation sorry
so looks like you can just use a built in FACTORIAL function, without even telling it that factorial 1 is 1, the only thing is you first have to define your own function and inside this function first ask to store the result in a variable and then return the result of built-in FACTORIAL function, if that makes any sense…?
i just pasted only this code and its a fact, it doesnt work on its own, however when i had it written down below the first version of my factorial it did work:
def factorial(x):
if x == 1 or x == 0:
f = 1
return f
else:
f = x * factorial(x - 1)
return f
test examples
print factorial(3) # prints 6
print factorial(4) # prints 24
print factorial(0) # prints 1
def factorial_v2(x):
result = factorial(x)
return result
print factorial_v2(3)
print factorial_v2(0)
print factorial_v2(1)
so it must be that factorial_v2 is using the first factorial function which is useless…
yup and I was just wondering why. That was my original question
Anyway 2 days ago I realised I accidentally skipped some exercises and jumped to this so I am leaving this alone for now and doing what I haven’t done previously and hope that I will understand later on