Returns nothing because you called the function main
within itself; but as the function is never called from without, it will not be performed. Apparently it was an error in the indentation of the code only, so just go back on a level to the call of main
:
def fatorial(n):
fat = 1
if n == 0 or n ==1:
return 1
else:
for i in range(1,n+1):
fat=i*fat
return fat
def main():
n = int(input("Digite um numero que quer ver o fatorial: "))
print(str(n) + "! = ", fatorial(n))
# Executanto a função main():
main()
# ^----- Aqui, main voltou um nível de indentação
If you call range(1, n+1)
for n = 0
, repeat loop will not be executed as the interval is [1, 1[
and the value you set for fat
would be 1, which is the result; similar happens to when n = 1
, because the break will be [1, 2[
, running to i = 1
, getting fat = 1 * fat
, which will still be 1, which is also the result. That is, you do not need this condition if n
is worth 0 or 1:
def fatorial(n):
fat = 1
for i in range(1, n+1):
fat=i*fat
return fat
And make fat = i * fat
is the same as fat *= i
, then you can simplify that too:
def fatorial(n):
fat = 1
for i in range(1, n+1):
fat *= i
return fat
Why is it calling itself ? Then the code does not run!
– NoobSaibot
@Andersoncarloswoss blz, it is me I anticipated thinking that the answer was an edition, I will try to question before.
– NoobSaibot