Python for Developers

First edition

Chapter 2: Syntax


A program written in Python consists of lines, which may continue on the following lines, by using the backslash character (\) at the end of the line or parentheses, brackets or braces in expressions that use such characters.

The character # marks the beginning of a comment. Any text after the # will be ignored until the end of the line, with the exception of functional comments.

Functional comments are used to:

  • change the encoding of the source file of the program by adding a comment with the text # - * - coding: <encoding> - # - at the beginning of the file, in which <encoding> is the file encoding (usually latin1 or utf-8). Changing encoding is required to support characters that are not part of the English language, in the source code of the program.
  • define the interpreter that will be used to run the program on UNIX systems, through a comment starting with #! at the beginning of the file, which indicates the path to the interpreter (usually the comment line will be something like#! / usr / bin / env python ).

Example of functional comments:

In [3]:
#!/usr/bin/env python

# A code line that shows the result of 7 times 3
print 7 * 3
21

Examples of broken lines:

In [5]:
# A line broken by backslash
a = 7 * 3 + \
5 / 2

# A list (broken by comma)
b = ['a', 'b', 'c', 
'd', 'e']

# A function call (broken by comma)
c = range(1,
11)

# Prints everything
print a, b, c
23 ['a', 'b', 'c', 'd', 'e'] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The command print inserts spaces between expressions that are received as a parameter, and a newline character at the end, unless it receives a comma at the end of the parameter list.

Blocks

In Python, code blocks are defined by the use of indentation, which should be constant in the code block, but it is considered good practice to maintain consistency throughout the project and avoid mixing tabs and <span class = "note" title = "The official recommendation coding style (http://www.python.org/dev/peps/pep-0008/) is to use four spaces for indentation and this convention is widely accepted by developers.">spaces</span>.

The line before the block always ends with a colon (:) and is a control structure of the language or a statement of a new structure (a function, for example).

Program structure

Example:

In [1]:
# For i on the list 234, 654, 378, 798:
for i in [234, 654, 378, 798]:
    # If the remainder dividing by 3 is equal to zero:
    if i % 3 == 0:
        # Prints...
        print i, '/ 3 =', i / 3
234 / 3 = 78
654 / 3 = 218
378 / 3 = 126
798 / 3 = 266

The operator % computes the modulus (remainder of division).

In [1]:
 
Out[1]: