Function returning None when finished

Asked

Viewed 530 times

1

The function, when undoes recursion, returns None, and I don’t know 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)))
  • In function superfat, will reach the point where n will be 0. What value should be returned in this case? As you did not put, it will be None.

1 answer

1

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 shall be implemented:

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

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

Nothingness!

You must write what must 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)

Because it becomes clearer when the recursion ends (but this is a matter of preference).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.