Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndentationError: unindent does not match any outer indentation level

When I compile the Python code below, I get

IndentationError: unindent does not match any outer indentation level


import sys  def Factorial(n): # Return factorial     result = 1     for i in range (1,n):         result = result * i     print "factorial is ",result     return result 

Why?

like image 796
cbrulak Avatar asked Jan 29 '09 16:01

cbrulak


People also ask

How do I fix this error IndentationError Unindent does not match any outer indentation level?

The Python "IndentationError: unindent does not match any outer indentation level" occurs when we mix tabs and spaces in the same code block. To solve the error, remove the spacing and only use tabs or spaces, but don't mix the two in the same code block.

How do I fix a unexpected Unindent in Python?

Conclusion. “IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.

What is outer indentation in Python?

Indentation in Python is important, and it makes your code well structured and clean. Python uses indentation to define code blocks. You can use either tabs or spaces to indent the code. However, using a combination of space and tab will result in indentationerror: unindent does not match any outer indentation level.


2 Answers

IMPORTANT: Spaces are the preferred method - see PEP 8 Indentation and Tabs or Spaces?. (Thanks to @Siha for this.)

For Sublime Text users:

Set Sublime Text to use tabs for indentation: View --> Indentation --> Convert Indentation to Tabs

Uncheck the Indent Using Spaces option as well in the same sub-menu above. This will immediately resolve this issue.

like image 20
activatedgeek Avatar answered Oct 10 '22 21:10

activatedgeek


Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys  def Factorial(n): # return factorial     result = 1     for i in range (1,n):         result = result * i     print "factorial is ",result     return result  print Factorial(10) 
like image 133
Kevin Tighe Avatar answered Oct 10 '22 21:10

Kevin Tighe