Function returning None when it finishes

1

The function, when it undoes recursion, returns None , and I'm not sure why.

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


def superfat (n, x = 1):
   if n > 0:
      x*=fat(n)
      n-=1
      return superfat(n, x)

número = int(input("Digite um número para descobrir o seu superfatorial: "))
print("O fatorial de {} é {}.".format(número, superfat(número)))
    
asked by anonymous 11.12.2017 / 00:50

1 answer

0

See your code.

def superfat (n, x = 1):
    if n > 0:
        x*=fat(n)
        n-=1
        return superfat(n, x)

When n > 0 , the following excerpt will be executed:

x*=fat(n)
n-=1
return superfat(n, x)

But when n <= 0 , what will be executed?

Nothing!

You should write what should be returning when that if is false.

For example ...

def superfat (n, x = 1):
    if n > 0:
        x*=fat(n)
        n-=1
        return superfat(n, x)
    return 1

In this case, I would rewrite to:

def superfat (n, x = 1):
    if n <= 0:
        return 1

    x*=fat(n)
    n-=1
    return superfat(n, x)

Well, the moment the recursion is over is clearer (but this is a matter of preference).

    
11.12.2017 / 12:51