Factorial


#1
def factorial(x):
  total = 1
  for d in range(1, x+1):
    total = total * d
    return total

Hi guys - I am on this factorial problem and I am unsure why the code is not working.

The error says ‘factorial(2) returned 1 instead of 2’.

The x+1 in the range function, I believe it includes x but not including x+1?

Thanks in advance.


#2

by default, a function returns None at the end

if we want to return something different at the end of our function, we can use the return keyword

so, return is the last action done by the function, which currently means your function ends in the first iteration of the loop

but to get the correct total, the loop need to make all its iterations


#3

Oh ok - I have just decreased the indent so that the ‘return’ is in line with the ‘for’. The code seems to work now!

This means that now it will iterate over all the numbers?
Then as part of the factorial function as a whole it will return the final total after all the iterations are done?

Please let me know if my thinking here is correct.
Many thanks.

def factorial(x):
  total = 1
  for d in range(1, x+1):
    total = total * d
  return total

#4

yep, seems you understand perfectly now :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.