Python uses indentation to define control and loop constructs. This contributes to Python's readability, however, it requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration could result in code that behaves in unexpected ways.
Block Indentation[edit | edit source]
Python uses the colon symbol (
:) and indentation for showing where blocks of code begin and end (If you come from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in Python, such as functions, loops,
if clauses and other constructs, have no ending identifiers. All blocks start with a colon and then contain the indented lines below it.
def my_function(): # This is a function definition. Note the colon (:) a = 2 # This line belongs to the function because it's indented return a # This line also belongs to the same function print(my_function()) # This line is OUTSIDE the function block
if a > b: # If block starts here print(a) # This is part of the if block else: # else must be at the same level as if print(b) # This line is part of the else block
Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:
if a > b: print(a) else: print(b)
Attempting to do this with more than a single statement will not work:
if x > y: y = x print(y) #IndentationError: unexpected indent if x > y: while y != z: y -= 1 # SyntaxError: invalid syntax
An empty block causes an
pass (a command that does nothing) when you have a block with no content:
def will_be_implemented_later(): pass
Simple example[edit | edit source]
For Python, Guido van Rossum based the grouping of statements on indentation. The reasons for this are explained in the first section of the "Design and History Python FAQ". Colons,
:, are used to declare an indented code block, such as the following example:
class ExampleClass: #Every function belonging to a class must be indented equally def __init__(self): name = "example" def someFunction(self, a): #Notice everything belonging to a function must be indented if a > 5: return True else: return False #If a function is not indented to the same level it will not be considered as part of the parent class def separateFunction(b): for i in b: #Loops are also indented and nested conditions start a new indentation if i == 1: return True return False separateFunction([2,3,5,6,1])
Spaces or Tabs?[edit | edit source]
In short: always use 4 spaces for indentation.
Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.
Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated:
Inconsistent use of tabs and spaces in indentation and the program will not run.
Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs.
Citing PEP 8:
When invoking the Python 2 command line interpreter with the
-toption, it issues warnings about code that illegally mixes tabs and spaces. When using
-ttthese warnings become errors. These options are highly recommended!
Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the Tab key.
- The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to spaces.
- However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces, instead of inserting a tab character.
Python source code is written with a mix of tabs and spaces, or with a non-standard number of indentation, spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py)
The recommended indentation is 4 spaces but tabs or spaces can be used so long as they are consistent. Do not mix tabs and spaces in Python as this will cause an error in Python 3 and can causes errors in Python 2.
How Indentation is Parsed[edit | edit source]
Whitespace is handled by the lexical analyzer before being parsed.
The lexical analyzer uses a stack to store indentation levels. At the beginning, the stack contains just the value 0, which is the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack, and an "INDENT" token is inserted into the token stream which is passed to the parser. There can never be more than one "INDENT" token in a row (
When a line is encountered with a smaller indentation level, values are popped from the stack until a value is on top which is equal to the new indentation level (if none is found, a syntax error occurs). For each value popped, a "DEDENT" token is generated. Obviously, there can be multiple "DEDENT" tokens in a row.
The lexical analyzer skips empty lines (those containing only whitespace and possibly comments), and will never generate either "INDENT" or "DEDENT" tokens for them.
At the end of the source code, "DEDENT" tokens are generated for each indentation level left on the stack until just the 0 is left.
if foo: if bar: x = 42 else: print foo
is analyzed as:
<if> <foo> <:>  <INDENT> <if> <bar> <:> [0, 4] <INDENT> <x> <=> <42> [0, 4, 8] <DEDENT> <DEDENT> <else> <:>  <INDENT> <print> <foo> [0, 2] <DEDENT>
The parser than handles the "INDENT" and "DEDENT" tokens as block delimiters.
Indentation Errors[edit | edit source]
The spacing should be even and uniform throughout. Improper indentation can cause an
IndentationError or cause the program to do something unexpected. The following example raises an
a = 7 if a > 5: print "foo" else: print "bar" print "done"
Or if the line following a colon is not indented, an
IndentationError will also be raised:
if True: print "true"
If you add indentation where it doesn't belong, an
IndentationError will be raised:
if True: a = 6 b = 5
If you forget to un-indent functionality could be lost. In this example
None is returned instead of the expected
def isEven(a): if a%2 ==0: return True #this next line should be even with the if return False print isEven(7)