Figure 4.2. The indentation of code blocks within a Python program using spaces.
In lines of Python code the different program blocks that relate to flow-control statements
like ‘if’, ‘for’ and ‘while’ etc. are indented relative to the start of the line using whitespace.
A flow-control statement in the main part of the program will have no indentation but will
define the start of a program block that is indented to the first level. Any statements that
are indented to this first level will be inside the block of the first statement. A further flow-
control statement at the first level will define a new block at the second indentation level.
Any lines of code that have less indentation than a preceding line are outside the previous
block and are part of the existing block with the same indentation or are outside all blocks
if there is no indentation.
One distinct and important difference between Python and many other computer
languages is how it deals with the issue of defining execution bocks (that are jumped into).
In many programming languages (such as Java, Perl, C, etc.), a block of code generally
has a left curly brace (‘{’) at the start and a right curly brace (‘}’) at the end. In Python the
extent of a block of code is completely determined by indentation, i.e. the addition of
blank spaces at the start of the line. The start of a Python code block must be indented by
some amount relative to whatever defines the block, such as a function declaration, a
conditional statement or loop statement. The content of the block must all have the same
indentation, except for when there are blocks inside the blocks, which are then indented
further. And finally, the block ends when the indentation ends.
For people moving to Python from other languages the block indentation can take some
getting used to. An advantage of the Python block syntax is that it removes clutter and
makes the code look cleaner; there is never a confusion of closing brackets. However,
there is one subtle issue: it is generally best to avoid using tab stops in Python code, unless
your editor is set up to automatically convert tabs to spaces while you are typing. The
reason for the potential problem is that in Python, tabs equate to giving space out to the
column that is the next multiple of 8 counting from the beginning of the line. Many editors
would show it instead out to the next multiple of 4 or 2, and so the code would look
different, and this is particularly problematic if the code mixes tabs and spaces for
indentation. The number of leading spaces used to indent each block is a matter of taste.
The Python community generally recommends 4 spaces, but in this book we consistently
use 2, allowing all our examples to fit within the width of the pages in a reasonable-size
font.
Do'stlaringiz bilan baham: |