-6
def factorial(n):
    sum = 0;
    if (n==0 or n==1):
        return 1
    else:
        While(n!=0)
            sum = sum + factorial(n);
            n = n - 1;
            return sum

factorial(3);

python 3.6 i need to find this: 1! + 2! + ... + n!

  • 1
    Welcome to StackOverflow! Can you elaborate on how your code ["doesn't work"](http://idownvotedbecau.se/noexceptiondetails/)? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please [edit] these details in or we may not be able to help. – AChampion Oct 17 '18 at 16:32
  • Hi and welcome to StackOverflow! Please provide a description of the error, what version of Python you are using and what you are trying to achieve in general. This helps us help you :) – Oliver Baumann Oct 17 '18 at 16:32
  • 4
    While(n!=0) -> while(n!=0): – Askold Ilvento Oct 17 '18 at 16:32
  • 3
    no need for `;` – DiCaprio Oct 17 '18 at 16:33
  • 1
    Please note that factorial uses multiplication, not addition (see https://www.wikipedia.com/en/Factorial) – Edward Minnix Oct 17 '18 at 16:33
  • Or `()` around flow-control expressions. Note: this recursion never terminates because you are not change `n` before recursing. – AChampion Oct 17 '18 at 16:34
  • Integers are immutable. Take a look at https://stackoverflow.com/questions/37535694/why-are-integers-immutable-in-python and use a debugger (https://www.jetbrains.com/pycharm/) it will help learn faster – PilouPili Oct 17 '18 at 16:38

4 Answers4

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

This will return 6

You are attempting to use a recursive function, which is fine, but the argument needs to be changed, in this case factorial(n-1)

Suraj Kothari
  • 1,642
  • 13
  • 22
1

try

In [3]: def factorial(n):
   ...:     if n == 0:
   ...:         return 1
   ...:     return n * factorial(n-1)
   ...: factorial(3)
   ...:
Out[3]: 6
DiCaprio
  • 823
  • 1
  • 7
  • 24
1

It is easier to build up than descend given you want to efficiently calculate this factorial sum. E.g. f is the increasing factorial, t is the total of those factorials:

def fac_sum(n):
    t, f = 0, 1
    for x in range(1, n+1):
        f *= x
        t += f
    return t

In []:
fac_sum(3)

Out[]:
9

Note: you can use itertools.accumulate() to simplify:

import itertools as it
import operator as op

def fac_sum(n):
    return sum(it.accumulate(range(1, n+1), op.mul))
AChampion
  • 29,683
  • 4
  • 59
  • 75
1

The problem is that you are using recursive in a bad way. Recursive and while are not good friends.

If you omit the while and do

        sum = sum + factorial(n-1);

That should works

aepelman
  • 311
  • 2
  • 12