Factorial problem


#1

I used the code:

def factorial(x):
  end = x
  while x>1:
    end = end*(x-1)
	  x = x-1
  print(end)

to find the factorial of x however an “indentation error” keeps coming up. I tried the code on a python interpreter and it worked.


#2

Hello @emilylaw,

Your code is not indented properly. Codecademy uses two spaces indentation.
I don’t know how it worked on a python interpreter because all of them need your code to be intended (as far as I know). Your code must be indented like this-

def factorial(x):
  end = x
  while x>1:
    end = end*(x-1)
    x = x-1
  print(end)



#3

#4

When I copied the code to the forum it changed the format. I did have two spaces indentation. The code only worked after I rewrote everything making sure to only use ‘Enter’ instead of the spacebar.


#5

Then there must be bug.
You can report it to codecademy.
I was also confused how it worked on the interpreter
:slight_smile:


#6

Compare your formatted code to @ammarbinfaisal’s. See the indentation yours has on the x= ... line? That’s the error. A statement does not start a new block, so no indentation added to next line.

For best results in the Python track, use the standard four spaces for each block level indent.

Also, your code should be returning the factorial, not printing it. Here is your code with a little shorthand simplification…

def factorial(x):
    end = x
    while x > 1:
        end *= (x - 1)
        x -= 1
  return end

See the section on “Python Assignment Operators” on the following page:

Python Operators - w3resource


#7

#8

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