The Python Language And Proper Indentation

Hello, and welcome back. I’m new to Python, so this post is not a tutorial; you can find a tutorial here. I need this language in its modules for a course I’m taking on “coursera.org“.

If you are a Linux user, you have probably heard about that language. So, what’s special about Python? One of its feature is that it forces you to use proper indentation. This is good because proper indentation makes your code more readable. In Python you don’t need symbols (usually curly braces)for the beginning and end of a command block.

Let’s look at some examples.

From your command line type ‘python’ and ….

1. Start a statement with an unnecessary space

>>>  print "Beginning with a space"
    print "Beginning with a space"
    ^
IndentationError: unexpected indent
>>>

2. Don’t indent a sub-block

>>> i=7
>>> if i<8:
... print "i<8"
File "<stdin>", line 2
print "i<8"
^
IndentationError: expected an indented block
>>>

3. An ‘if’ block with more than one statement

>>> if i<8:
...   print 'a'
...   print 'b'
...   print 'c'
... 
a
b
c
>>>

4. Nested loops

>>> for i in range(4):
...   for j in range(3):
...     print 'inner loop i=' + str(i)
...     print 'j=' + str(j)
...   print 'outer loop i=' + str(i)
... 
inner loop i=0
j=0
inner loop i=0
j=1
inner loop i=0
j=2
outer loop i=0
inner loop i=1
j=0
inner loop i=1
j=1
inner loop i=1
j=2
outer loop i=1
inner loop i=2
j=0
inner loop i=2
j=1
inner loop i=2
j=2
outer loop i=2
inner loop i=3
j=0
inner loop i=3
j=1
inner loop i=3
j=2
outer loop i=3
>>>

Summary

Proper indentation makes your code more readable. In other languages, such as C, PHP and Perl, readability won’t guarantee correctness, but in Python you are less likely to have bug if you follow rules of readability.

Advertisements