Python Code Indentation
Python uses whitespace (eg spaces and tabs) to group together lines of code that belong together. Any time a line ends with a colon, you are telling Python "hey, a block of code follows" and Python expects to see some indented code.
Example
if x = 1:
call_functionA()
call_functionB()
next_function()
The code call_functionA
and call_functionB
will be executed if x
equals 1, so they are grouped together with the same indenting. The code
next_function()
isn't part of the "if" block so it will be always be executed
next, regardless of whether or not x equals 1.
Example of bad indentation
In the following code, the second line is not a separate block of code.
print('Sane math.') print('foobar')
Therefore Python will tell you:
File "test.py", line 2 print('foobar') ^ IndentationError: unexpected indent
Notice how Python tells you the file and line where the indentation problem occurred. Python expects you to do
print('Sane math.') print('foobar')
Example error when a block not being indented
If you have this code, which defines a function:
def foo(): print('foo')
Python will tell you:
File "main.py", line 2 print('foo') ^ IndentationError: expected an indented block
Here, Python is expecting at least one line of real code (not just a comment line). For example
def foo(): print('foo')
Declaring a function without any code inside
If you need want to define a function but haven't got around to filling in the details:
def foo(): # ...the rest of your code...
This is not valid because Python expects an indented line of code under the def
.
If we tried to use a comment line to satisfy Python
def foo(): # This is a comment
Python will respond with
File "main.py", line 4 print("This is a non-indented line of code") ^ IndentationError: expected an indented block
If you truly don't have any code (yet) to add to the function you can use the pass keyword as a placeholder.
def foo(): pass
Notes
Four spaces for indentation is preferred.
Python's indentation is similar to functional programming language syntax but takes a while to get used to if you have used other programming languages that use curly braces { } to indicate a code block.
Python does not use the semi-colon ; character at the end of code line, unlike many other programming languages.
For readability, the end of a code block should be followed by a blank line, just like you use a blank line between paragraphs:
Example: Less readable
if 1 == 2: print('Wow, what kind of math are you using?') if 2 == 2: print('Sane math.')
Example: More readable
if 1 == 2: print('Wow, what kind of math are you using?') if 2 == 2: print('Sane math.')