Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Basic] Indentation
#1
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. 

   
http://i.imgur.com/1Zvi6gk.png
This image illustrates this code:
 
x = 1
if x:
    y = 2
    if y:
        print('block2')
        x = 3
    print('block1')
print('block0')
You need to make sure all if/elif/else lines up correctly such as

if condition:
    do_something
else:
    do_something_else
Here are some examples of incorrect indentation:
Quote:
if x:
    y = 2
        if y:
Line 3 needs to be dedented back 4 spaces to be aligned with y = 2 line
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. 

if condition:
    do_something
    else:
        do_something_else
both lines 3 and 4 need to be dedented back to the same levels as the first two lines.    

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. Take the first example in this tutorial. It would like like in C as 

int x = 1;
if (x != NULL){
    int y = 2;
    if (y != NULL){
        printf("block2");
        int x = 3;
    }
    printf("block1");
}
printf("block0")
but in python it looks like
x = 1
if x:
    y = 2
    if y:
        print('block2')
        x = 3
    print('block1')
print('block0')
c-like:
if (x > y){
    x = 1;
    y = 2;
}
python:
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:
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:
while x > y:
    ----
    ----
    ----
In python the indentation of a block is required. This prevents things like the previous example.

Seeing white space in IDE's/Editors:
Most IDE's and editors will allow options such as convert to spaces, show indentation guides, whitespace, or line endings, etc.
       


There are a few exceptions to these rules:

multiple statments on a line:
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
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:
x = (a + b +
    c + d)
Block rule special case
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:
 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:
IndentationError: unindent does not match any outer indentation level
If you copy code from the internet over here and there, you might find that you have mixed spaces and must convert them to one or the other. The general rule is to use 4 spaces. Most IDE's have the option of showing the whitespace to help you find what lines are using spaces and what lines are using tabs. And almost all IDE's have the option to covert the entire file to one or the other. This is what you need to do to fix this issue.
Recommended Tutorials:
#2
What's with the quote?

Also something notable about indentation - I've heard braces in C/C++/Java compared to indentation in Python, but there is a vital difference. In the aforementioned languages, you can simply add braces to denote a new scope. This is rarely used, but Python is different in an important way - as mentioned above, you can't just indent without good reason, but also, scope is not denoted by indentation. A variable created within an indented block will "leak" into the enclosing space, as in a for loop. Functions, classes and modules are the ways to create new scopes, and even though two of those use indentation, indentation itself does not generally create scope.
#3
Quote:What's with the quote?
not a year later or anything Shifty

I used the quote to group together incorrect indentation
Recommended Tutorials:


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020