[Tutor] Computing factorial...
kinuthia muchane
muchanek at gmail.com
Mon Apr 21 16:30:30 CEST 2008
Hi,
I wanted to calculate the factorial of a given number without using
recursion. I came up with the following code, although it is not very
elegant it works.
def factorial(*args):
product = args[0]
for item in args[1:]:
product *= item
return product
number = int(raw_input('Enter value of number to compute factorial '))
seq = range(1,number + 1)
if number <= 0:
print -1
else:
print factorial(*seq)
When I change that code a bit to (In fact, this is what I started with,
it almost drove me crazy trying to figure out what was wrong!) :
def factorial(*args):
temp = args[0]
for item in args[1:]:
product = temp * item
return product
number = int(raw_input('Enter value of number to compute factorial '))
seq = range(1,number + 1)
if number <= 0:
print -1
else:
print factorial(*seq)
... it just echoes back the number you were prompted to enter.
My confusion is, aren't the variables 'temp' and 'product' storing the
same value ie "args[0]". So why would they return different values, the
one with "temp" giving a wrong answer?
Thanks!
Kinuthia...
More information about the Tutor
mailing list