0
I would like to create a variable with the first value passed as parameter in a function, but every time a recursive call is made the variable receives the value of the new parameter passed. For example:
def fatorial(n)
print(n)
if n <= 1:
return 1
else:
return n * fatorial(n - 1)
In the above case I would like to print only the value passed as parameter the first time. Is there any way I can store and print only the first value passed? If so, how could I implement this?
It worked, but there’s some other way to store in a variable?
– Rafael Lima
@Rafaellima you could store the value of the parameter within the condition
if imprima
.– mercador
Since you only want the first printed value, I don’t see why this should be done within the function.
– mercador
While trying to store and use the variable later is still giving error, but the impression of the value already solves my problem.
– Rafael Lima
In fact, the most common - and what I like - is to leave the default value of the optional value set to whoever calls the function "from outside" - the recursive function "knows more about itself" - (that is, Voce is thinking about her code when she writes the calls to herself)And it’s best that those internal calls go over the extra optional parameters. In short, change the cabbage to
def fatorial(n, imprima=True):
and the internal call tofatorial(n - 1, imprima=False)
so who calls from outside need not worry about the "print".– jsbueno
Having said all this - it is a bad idea that a function of these 0- which is purely numerical, prints something - the best practice is even the recursive function only return a value - whoever makes the outside call that prints.
– jsbueno
If it is a real code (in contrast to this example that is only didactic) where what will be done with the final value returned is more complicated than a simple
print
- still worth keeping the recursive function without a "special case` for when it is called from outside -and instead create another small function, which only takes care of calling the recursive function, and print or save its results.– jsbueno