How to keep a fixed value inside a recursive function?

0

I'd like to create a variable with the first value passed as a parameter in a function, but every time a recursive call is made the variable receives the value of the new passed parameter. For example:

def fatorial(n)
    print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

In the case above I would like to print only the value passed as parameter the first time. Can I store and print only the first last value? If so, how could I implement this?

    
asked by anonymous 28.05.2017 / 20:21

1 answer

2

It is not necessary to store the value passed the first time. Instead, use a control variable to decide whether or not to print the first value.

def fatorial(n, imprima=False):
    if imprima:
      print(n)
    if n <= 1:
        return 1
    else:
        return n * fatorial(n - 1)

print(fatorial(5, True))

Example online here .

    
28.05.2017 / 20:51