Block Indentation
suggest changePython 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.
- 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 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)