It does not return anything because you called the main
function within itself; but since the function is never called from outside, it will not be executed. Apparently it was error in the indentation of the code only, so it is enough to go back on a level 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)
to n = 0
, the loop will not execute because the loop is [1, 1[
and the value you set to fat
would be 1, which is the result; similar happens when n = 1
, because the interval will be [1, 2[
, executing for 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 0 or 1:
def fatorial(n):
fat = 1
for i in range(1, n+1):
fat=i*fat
return fat
And making fat = i * fat
is the same as fat *= i
, then you can simplify this too:
def fatorial(n):
fat = 1
for i in range(1, n+1):
fat *= i
return fat