A program written in Python consists of lines, which may continue in 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.
# 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 for:
# - * - coding: <encoding> - # -at the beginning of the file, in which
<encoding>is the file encoding (usually latin1 or utf-8). Change encoding is required to support characters that are not part of the English language, in the source code of the program.
#!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:
#!/usr/bin/env python # A code line that shows the result of 7 times 3 print 7 * 3
Examples of broken lines:
# 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]
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 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).
# 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
% computes the modulus (remainder of division).