Indentation

A place where you can post Python-related tutorials you made yourself, or links to tutorials made by others.

Indentation

Postby metulburr » Fri Feb 15, 2013 11:03 pm

Python detects block boundaries automatically, by line indentation. (the empty space to the left of your code). All statements indented the same distance to the right belong to the same block of code. The block ends when the end of the file or a lesser-indented line is encountered, and more deeply nested blocks are simply indented further to the right than the statements in the enclosing block.

scaled_indent.png
scaled_indent.png (9.53 KiB) Viewed 41 times

http://i.imgur.com/1Zvi6gk.png
This image illustrates this code:
Code: Select all
x = 1
if x:
    y = 2
    if y:
        print('block2')
        x = 3
    print('block1')
print('block0')


Here are some examples of incorrect indentation:
Code: Select all
if x:
    y = 2
        if y:

Line 3 needs to be dedented back 4 spaces to be aligned with y = 2 line

Code: Select all
x = 1
if x:
    y = 2
    if y:
        print('block2')
x = 3
    print('block1')
print('block0')

line 6 needs to be indented 8 spaces (two indentation levels) to be aligned with print('block2') line. Having it this way x =3 line terminates block 1 prematurely, causeing an error due to print('block1') line being indented for no reason.



Comparing C-Like and Python

If you come from C, if statements will look like they are missing quite of few things. However they are not.
c-like:
Code: Select all
if (x > y){
    x = 1;
    y = 2;
}

python:
Code: Select all
if x > y:
    x = 1
    y = 2


Python adds the : to complete the compound statement, and removes the parenthesis. Parenthesis are optiional, but not pythonic. Python also removes the semi-colon to terminate statements. The end of the line terminates the statement. Semi-colons on statements are also optional, but also not pythonic. Lastely python removes {} to indicate blocks of code. You do not need to add anything explicit to mark the beginning or end of a nested block of code. It is simply the consistant indentation that does this in python.

c-like:
Code: Select all
while (x > y){
    ----;
        ----;
----;
}

Though this is not favored in c-like languages, it is still legit code. It happens more often than you think, especially if each code ----; is actually a section of code written by 3 different programmers. One who liked to indent 4 spaces, one who liked to indent 8 spaces , and one who didn't like to indent at all. Regardless of the indentation though this all one block of code. I feel bad for the 4th person having to add code to this. It may be you!

In python the same code would be:
Code: Select all
while x > y:
    ----
    ----
    ----

In python the indentation of a block is required. This prevents things like the previous example.

There are a few exceptions to these rules:

multiple statments on a line:
Code: Select all
a = 1; b = 2; print(a + b)

The semi-colons are required for when you have multiple statements on per line. You cannot though, have compund statements within one of these statements.

one statement spanning multiple lines
Code: Select all
mylist = [123,
    456,
    789]

To make this work, you enclose part of your statement in a bracketed pair, (), {}, []. Any code within these, can span multiple lines. Your statement does not end until python reaches the line containing the closing part of the pair. The indentation of the coninuation lines does not matter.

Because any expression can be wrapped in parenthesis, you can add the left parenthesis, and drop down to the next line and continue your statement:
Code: Select all
x = (a + b +
    c + d)


Block rule special case
Code: Select all
if x > y: print(x)

This is an exception to blocks being indented on the next line. This will only work if the body of the compound statement itself does not contain any other compound statements. Larger statements must appear on another line indented.

tab and space mixing
You cannot mix tabs and spaces together. Choose one or the other.IF you are piecing code together from here and there you might find your final result mixed with tabs and spaces. A good IDE will have the option to display such indentation type.
For example this is the IDE Geany showing indentation. the dots indicate spaces, while the arrows indicate tabs.
tabs and spaces mixed (tracebacks will not be exact as the image has changed)
If you look closesly, you can see the class' first two lines are indented by spaces while the rest are indented in tabs. This is going to cause:
Code: Select all
  File "test3.py", line 19
    self.surf = pygame.Surface((5,10)).convert()
                                               ^
TabError: inconsistent use of tabs and spaces in indentation

or if the tabs and spaces are in reverse order it will cause:
Code: Select all
IndentationError: unindent does not match any outer indentation level

However you cannot see it unless your IDE has that. Which in Geany you just convert the whole file to use spaces as indentation in which fixes the problem
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Return to Tutorials

Who is online

Users browsing this forum: No registered users and 3 guests