Saturday, September 12, 2009

IndentationError: expected an indented block

IndentationError: expected an indented block

Indentation is a big part of writing Python code, and it is a good thing in my opinion because it makes you write better and cleaner code. indentation is used to place code more to the right. so instead of writing your code like below;


#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"


you have to write your code using indentations to make it work in python. Meaning a functioning code will look like this;


#!/usr/bin/python
n = 1
i = 1
print "start code"
while n<=10:
i = 1
print "start the table of", n
while i<=10:
print i,"x 8 =", i*8
i=i+1
n=n+1
print "end code"


As you can see it will make your code more readable because you can see what is inside a while look and what not. This is directly the reason why it is used in Python coding, not to make your code look nice, it has a functional part to it. In some languages you indicate the begin and end of a codeblock like a while loop with brackets, a { to start and a } to end the while block. In python you use indentations. If you do not make sure your indentation is correct you will most likely end with a " IndentationError: expected an indented block" error. Lucky for you a line number will be given so you can debug your code quickly.

Personaly I think that the use of indentation for codeblocks is great. It will learn you to write your code in a way that it is more readable for other developers. That is at least on this part. I remember re-writing code from other developers and first making sure all the indentation is correct so it becomes more readable, in in python that is no longer needed because if you have your indentation not set correct in your code you will not be able to run it in the first place. Meaning that, if your process is correct, no developer can commit code into production if the indentation is incorrect. That is to say, for the parts where it is needed.

Final word, indentation in Python code,….. a good thing.

Post a Comment