0

EDIT: I know I can import factorials but I'm doing this as an exercise

Trying to get the factor of a given number with a function in Python.

For example: factorial(4) = 4 * 3 * 2 * 1 = 24

def factorial(x):
    n = x
    while n >= 0:
        x = n * (n - 1)
        n -= 1
    return x
Colonel Panic
  • 126,394
  • 80
  • 383
  • 450
Mr.Smithyyy
  • 2,013
  • 9
  • 43
  • 85

4 Answers4

4

try like this: to make your code work

def factorial(x):
    n = 1   # this will store the factorial value
    while x > 0:
        n = n*x
        x -= 1
    return n

you got many advice on comments follow it

Hackaholic
  • 17,534
  • 3
  • 51
  • 68
  • Thank you for using my existing code to make this, makes it much easier to understand. I appreciate everyone else in the comments that put in their answer, very helpful in seeing other ways of doing it. – Mr.Smithyyy Feb 21 '15 at 00:16
  • 1
    nice to see u @JoranBeasley – Hackaholic Feb 21 '15 at 00:17
1

A good way of approaching this would be using recursion where a function calls itself. See Function for Factorial in Python

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

But in your case your return statement actually breaks out of the while loop. So if you pass in 5 you get 20 back which is obviously not 5! (5 factorial).

Instead, try this:

def factorial(x):
   n = 1
   while x > 1:
       n *= x
       x -= 1
   return n

print (factorial(5))

But do have a go at the recursive approach.

If you really want to cheat try:

import math
math.factorial(n)
Community
  • 1
  • 1
Gordonium
  • 3,318
  • 22
  • 37
0

I present an even shorter code for recursive factorial calculation. Not sure if it is faster or slower than other approaches:

def fac(n):
    return 1 if n==1 else n*fac(n-1)

fac(10)
3628800
Alex
  • 38,938
  • 74
  • 207
  • 406
0
def factorial(n):
    total = 1
    for num in range(2,n+1):
        total *= num
    return total