By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

i want to be able to make factorial while counting down

P: 1
Expand|Select|Wrap|Line Numbers
  1. x = 5
  2. y = 5
  3.  
  4. while x > 0:
  5.     print (x, x * y)
  6.     x -= 1

how can i make this do factorial of 5?
Jan 23 '15 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
There are several way to calculate a factorial of a number. This uses the built-in function reduce:
Expand|Select|Wrap|Line Numbers
  1. >>> import operator
  2. >>> reduce(operator.mul, range(5, 0, -1))
  3. 120
This uses recursion:
Expand|Select|Wrap|Line Numbers
  1. >>> def factorial(n):
  2. ...     if n == 0:
  3. ...         return 1
  4. ...     return n*factorial(n-1)
  5. ... 
  6. >>> factorial(5)
  7. 120
  8. >>> 
A simple for loop:
Expand|Select|Wrap|Line Numbers
  1. >>> x = 5
  2. >>> v = 1
  3. >>> for i in range(5, 0, -1):
  4. ...     v *= i
  5. ...     
  6. >>> v
  7. 120
  8. >>>
Choose what is best for your application.
Jan 23 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.