(Full disclosure, I am going through the Python tutorial at CodeAcademy, and am using their web-based IDE.)
def factorial(x):
bang = 1
for num in x:
bang = bang * num
return bang
In java, this works to generate a factorial from a number smaller than 2,147,483,647. I think it should work in python, but it doesn't. Instead I get the error:
"Traceback (most recent call last): File "python", line 3, in factorial TypeError: 'int' object is not iterable"
Perhaps there's something I'm not understanding here, or perhaps my syntax is wrong. I tested further and created a separate function called factorial that iterates:
def factorial(x):
if x > 2:
return x
else:
return x(factorial(x-1))
This also doesn't work, giving me the error:
"Traceback (most recent call last): File "python", line 11, in factorial TypeError: 'int' object is not callable"
I am a python noob, but it seems that both of these should work. Please advise on the best way to learn Python syntax...
You can't do for num in x
if x
is an integer. An integer isn't "iterable" as the error says. You want something like this:
def factorial(x):
bang = 1
for num in xrange(1, x+1):
bang = bang * num
return bang
The xrange
(or range
) will generate the necessary range of numbers for the in
to operate upon.