What is Python Whitespace and how does it work?
Solution 1:
Whitespace is used to denote blocks. In other languages curly brackets ({
and }
) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.
im_a_parent:
im_a_child:
im_a_grandchild
im_another_child:
im_another_grand_child
Off the top of my head, def
, if
, elif
, else
, try
, except
, finally
, with
, for
, while
, and class
all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child
and im_another_child
are siblings.
Solution 2:
Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation
I'm not sure exactly how to use it.
Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).
You need to create a new indent level after each colon:
for x in range(0, 50):
print x
print 2*x
print x
In this code, the first two print
statements are "inside" the body of the for
statement because they are indented more than the line containing the for
. The third print
is outside because it is indented less than the previous (nonblank) line.
If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.
Finally, certain statements, like lambda
feature a colon, but cannot have a multiline block as the body.
Solution 3:
It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.
Example 1:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
We are in main function
print 2nd line
Example 2:
def main():
print "we are in main function"
print "print 2nd line"
main()
Result:
print 2nd line
We are in main function
Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.