a = 2.0
print(a)2.0
Marie-Hélène Burle
First, let’s cover some basics of the Python syntax.
Short commands are usually written one per line:
but you can write multiple commands on the same line with the semi-colon separator:
In a Python shell or when using Jupyter, you can omit the print function if you want to return a result directly (this is not true in functions definitions).
So the above could be run as:
and
Be careful though that if you are running a script (i.e. you write this code in a text file with a .py extension and execute it by running python <your-script>.py in the command line), nothing will get printed with this method and you have to explicitly use the print function.
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:
Cell In[5], line 3 print(i) ^ IndentationError: expected an indented block after 'for' statement on line 2
IDEs and good text editors indent code automatically.
Notice how the result can be of a different type.
Variables can be used in operations:
a = a + 10 can be replaced by the more elegant:
Pairs of single and double quotes are used to create strings.
PEP 8 does not recommend one style over the other. It does suggest however that once you have chosen a style, you stick to it to make scripts consistent.
Apostrophes and textual quotes interfere with Python quotes. In these cases, use the opposite style to avoid any problem:
Cell In[17], line 2 'This string isn't easy' ^ SyntaxError: unterminated string literal (detected at line 2)
Cell In[19], line 2 "He said: "this is a problem."" ^ SyntaxError: invalid syntax
Sometimes, neither option works and you have to escape some of the quotes with \:
Cell In[21], line 2 "He said: "this string isn't easy"" ^ SyntaxError: unterminated string literal (detected at line 2)
Cell In[22], line 2 'He said: "this string isn't easy"' ^ SyntaxError: unterminated string literal (detected at line 2)
'He said: "this string isn\'t easy"'
Comments
Comments (snippets of text for human consumption and ignored by the Python interpreter) are marked by the hashtag:
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.