[Tutor] Computing factorial...

bob gailer bgailer at gmail.com
Mon Apr 21 17:24:06 CEST 2008


kinuthia muchane wrote:
> 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?
>
>   
The program never changes temp. So temp will always be 1.

Is that not obvious? Or are you expecting that product and temp both 
refer to the same object? Which would be true if the object were a 
mutable such as a list or a dict or a class instance. But is NOT the 
case for immutables such as numbers and strings.


-- 
Bob Gailer
919-636-4239 Chapel Hill, NC



More information about the Tutor mailing list