Python Syntax
Syntax is the set of rules that decides how a program must be written so the interpreter can understand it. Python's syntax is deliberately small. The two rules that surprise newcomers most are: a new line ends a statement, and indentation defines blocks.
Statements and lines
Each line normally holds one statement. You don't end it with a semicolon:
city = "Hanoi"
population = 8_500_000
print(city, population)Hanoi 8500000
Tip: Underscores inside numbers (
8_500_000) are ignored by Python. They only make big numbers easier to read.
You can put several statements on one line with ;, but it is considered poor style:
a = 1; b = 2; print(a + b) # works, but avoid itIndentation
Many languages use { and } to group statements. Python uses indentation — the whitespace at the beginning of a line. A line ending with a colon : opens a block, and every line of that block must be indented by the same amount.
temperature = 31
if temperature > 30:
print("It is hot today.")
print("Drink plenty of water.")
print("This line always runs.")It is hot today.
Drink plenty of water.
This line always runs.
The two indented print calls belong to the if. The last line is back at the left margin, so it is outside the block.
The standard is 4 spaces per level. Python will reject code whose indentation is inconsistent:
if temperature > 30:
print("hot")
print("very hot") # IndentationError: unexpected indentForgetting to indent is an error too:
if temperature > 30:
print("hot") # IndentationError: expected an indented blockBlocks inside blocks
Blocks can be nested. Each extra level adds another 4 spaces:
for n in [3, 8, 12]:
if n > 5:
print(n, "is bigger than 5")
else:
print(n, "is small")3 is small
8 is bigger than 5
12 is bigger than 5
Case sensitivity
Python is case-sensitive. score, Score and SCORE are three different names, and the built-in function is print, not Print.
score = 10
Score = 99
print(score)
print(Score)10
99
Long lines
If a statement is too long, you can continue it on the next line inside any pair of brackets (), [] or {}. Python knows the statement isn't finished until the bracket closes:
total = (
100
+ 250
+ 75
)
colors = [
"red",
"green",
"blue",
]
print(total, colors)425 ['red', 'green', 'blue']
Syntax at a glance
| Rule | Example |
|---|---|
| One statement per line | x = 5 |
| Colon opens a block | if x > 0: |
| Block body is indented (4 spaces) | print(x) |
Comments start with # |
# a note |
| Names are case-sensitive | age ≠ Age |
| Brackets allow line continuation | (1 +\n 2) |
Note: A
SyntaxErrororIndentationErroris reported before any of your code runs, because Python reads the whole file first.
Test yourself
What character ends a line that opens a block, such as an if statement?
- ;
- {
- :
- ->
How many spaces per indentation level does the Python style guide recommend?
- 1
- 2
- 4
- 8
Are Total and total the same variable?
- Yes
- No, Python is case-sensitive
- Only inside functions
- Only in Python 2