How on Factorial

Ulrich Eckhardt eckhardt at satorlaser.com
Wed Oct 27 02:55:09 EDT 2010


Geobird wrote:
> I  am a beginner in Python and would ask for a help.
> 
> 
> I  was searching for  smaller  version  of  code  to calculate
> factorial . Found  this one
> def fact(x):
>     return x > 1 and x * fact(x - 1) or 1

I'd say this is about as small as it gets.

> But I don't  really get how (  ....x > 1 and x * fact(x - 1)....)
> works .

In that case, I'd suggest not trying to make things smaller, but more easy
to read:

  def fact(x):
      if x > 1:
          return x * fact(x - 1)
      else:
          return 1

This is equivalent to the above code and I hope it illustrates how that code
works.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list