White Space in Python Code
Python does not use curly brackets or special begin and end statementsto structure code. Instead, the indentation level of a line determines to
which code block the line belongs. A code block is a group of statements
that belongs to an if clause, a for-loop, a function or a similar structure.
Indentation starts a code block and it ends when the indentation stops.
In the following example, the first two print statements form a code
block that belongs to the if clause. The last print statement does not
belong to the code block and it is executed regardless of the if condition.
if x > 5:
print "X is greater than 5"
print "Also this line belongs to the if-clause"
print "This line does not belong to the if-clause"
You can use spaces or tabs for indentation but you must be consistent.
In this book, we use four spaces for indentation. You can follow the
same style in your own code. Many text editors that support Python
programming, such as Emacs or PythonWin, automatically make sure
that the indentation is consistent. Using an editor like this is highly
recommended.
In some cases you must split a long expression over several lines. As
white space is significant only at the beginning of a statement, you can
split a long expression freely over several lines. However, in some cases
the Python interpreter cannot know whether the subsequent lines belong
to one statement or several statements. To make your intention clear, you
can put a backslash character ‘\’ at the end of a line to specify that the
next line continues the same statement.
No comments:
Post a Comment