Syntax

Author

Marie-Hélène Burle

First, let’s cover some basics of the Python syntax.

Commands

Short commands are usually written one per line:

a = 2.0
print(a)
2.0

but you can write multiple commands on the same line with the semi-colon separator:

a = 2.0; print(a)
2.0

Some commands (e.g. function definitions, for loops, if else statements) span over multiple lines. The first line starts normally, but subsequent lines are indented to mark that they are part of the same command.

This indentation—one tab or a series of spaces (often 4 spaces, but the number can be customized in many IDEs)—has a syntactic meaning in Python and is not just for human readability:

# Incorrect code
for i in [1, 2]:
print(i)
  Cell In[3], line 3
    print(i)
    ^
IndentationError: expected an indented block after 'for' statement on line 2
# Correct code
for i in [1, 2]:
    print(i)
1
2

IDEs and good text editors indent code automatically.

Comments

Comments (snippets of text for human consumption and ignored by the Python interpreter) are marked by the hashtag:

# This is a full-line comment

print(a)         # This is an inline comment
2.0

PEP 8—the style guide for Python code—suggests a maximum of 72 characters per line for comments. Try to keep comments to the point and spread them over multiple lines if they are too long.

Basic operations

3 + 2
5
3.0 - 2.0
1.0
10 / 2
5.0

Notice how the result can be of a different type.

Variables can be used in operations:

a = 3
a + 2
5

a = a + 10 can be replaced by the more elegant:

a += 10
a
13