BasicsChapter 3 of 114
Syntax
Indentation is the structure. Here is what that means in practice.
Indentation is not decoration
Most languages mark a block of code with braces and indent it so humans can read it. Python drops the braces and uses the indentation itself. What is indented under a line belongs to that line.
temperature = 31
if temperature > 30:
print("Hot")
print("Still inside the if")
print("Always runs")Output
Hot Still inside the if Always runs
Move that last print four spaces to the right and it becomes part of the if. Nothing else about the program changes. That is the whole idea.
The colon opens a block
A line that starts a block ends with a colon, and the next line is indented. You will see this with if, for, while, def, class, with and try:
def shout(word):
return word.upper() + "!"
print(shout("hey"))Output
HEY!
How much to indent
Four spaces per level. This is a convention rather than a rule — the language accepts any consistent amount — but it is the one nearly all Python code uses, and your editor will do it for you.
One statement per line
Python does not need semicolons. A newline ends a statement:
first = "Ada"
last = "Lovelace"
print(first, last)Output
Ada Lovelace
A long line can be broken inside brackets of any kind, and the indentation inside them is free:
names = [
"Ada",
"Grace",
"Katherine",
]
print(len(names))Output
3
That trailing comma after the last item is legal and normal. It keeps the diff small when you add another name later.
Case matters
name, Name and NAME are three different things. So are print and Print — and only the first exists:
value = 10
Value = 20
print(value, Value)Output
10 20
Empty blocks need pass
A block cannot be empty, but sometimes you want a placeholder. pass is a statement that does nothing, and exists exactly for this:
def not_written_yet():
pass
not_written_yet()
print("no error")Output
no error
Test yourself
3 questionsWhat decides which lines belong to an if statement?
Show the answer
How far they are indented — Indentation is the structure itself. Moving a line four spaces changes what it belongs to.
What happens if you mix tabs and spaces for indentation?
Show the answer
Python raises TabError and refuses to run the file — It is an error, not a preference. Set your editor to insert spaces and it never comes up again.
Why would you write pass?
Show the answer
A block cannot be empty, and pass is a placeholder that does nothing — Skipping to the next iteration is continue, and leaving a function is return. pass just occupies the block.
Comments
Notes to humans that the interpreter skips, and how to use them well.