The first thing that tends to catch your eye when it comes to Python syntax is that indentation matters:
It determines which code is inside the block
When a block of code starts and ends
Example of Python code:
a = 10 b = 5 if a > b: print("A greater than B") print(a - b) else: print("B is greater than or equal to A") print(b - a) print("End") def open_file(filename): print("Reading File", filename) with open(filename) as f: return f.read() print("Ready")
This code is shown for syntax demonstration. Although if/else statement has not yet been covered, it is likely that the meaning of code will be clear in general.
Python understands which lines refer to “if” on indentation basis.
Execution of a block
if a > b ends when another string with the same indent
if a > b appears. Similarly to block
The second feature of Python is that some expressions must be followed by colon
(for example, after
if a > b and after
Several rules and recommendations on indentation:
Tabs or spaces can be used as indents (it is better to use spaces or more precisely to configure editor so that Tab is 4 spaces - then when using Tab key, 4 spaces will be placed instead of 1 tab sign).
Number of spaces must be the same in one block (it is better to have the same number of spaces in whole code - popular option is to use 2-4 spaces, for example, this book uses 4 spaces).
Another feature of code above is empty lines. It makes reading code easier. Other syntax features will be shown during process of familiarization with data structures in Python.
Python has a special document that describes how best to write Python code PEP 8 - Style Guide for Python Code.