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
  • 132,665
  • 89
  • 401
  • 465
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95

5 Answers5

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
  • 19,069
  • 5
  • 54
  • 72
  • 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,389
  • 23
  • 39
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
  • 41,580
  • 88
  • 260
  • 469
0
def factorial(n):
    total = 1
    for num in range(2,n+1):
        total *= num
    return total
Kate Kiatsiri
  • 63
  • 2
  • 7
0

input:

n = 10
print(str(n) + "! = ", end = '')
def factorial(n):
    '''
    print factorial number in human way
    '''
    if n < 0:
        return 'factorial() not defined for negative values'
    if n == 0:
        return 1
    if n == 1:
        print('', n, ' =', end = ' ')
        return 1
    else:
        print('', n, '*', end = '')
        return n * factorial(n - 1)

print(factorial(n))

output:

10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800

Arthur
  • 21
  • 4