Block Indentation

suggest change

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.

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.

For example:

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

or

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 IndentationError. Use pass (a command that does nothing) when you have a block with no content:

def will_be_implemented_later():
    pass

Spaces vs. Tabs

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 tabs and spaces for indentation. In that case the program fails to compile with TabError: inconsistent use of tabs and spaces in indentation.

Citing PEP 8:

Many editors have “tabs to spaces” configuration. When configuring the editor, one should differentiate between the tab character (‘\t’) and the Tab key.

Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents