Statements and blocks
In part 1 you wrote programs without worrying much about what their parts are called. Programmers use a handful of words for those parts all the time, and knowing them makes error messages, documentation and the rest of this course easier to follow. This module goes through the most important ones.
Statements
A statement is one complete instruction in a program, something Python carries out. Every line of your programs in part 1 was a statement: name = input("Your name: ") asks a question and keeps the answer in a variable, and print(f"Hi, {name}!") greets the user by that name. Python carries out the statements one at a time, from the top down. Most statements fit on one line.
A statement can also contain other statements. An if statement is a single statement made of its first line, with the condition, and the lines that belong to it:
temperature = 28
if temperature > 25:
print("It's a warm day.")
print("Remember to drink water.")
print("See you later!")
It's a warm day.
Remember to drink water.
See you later!This program has three statements at the top level: an assignment, an if statement and a print. The if statement has two more statements inside it.
Blocks
You have used blocks since the if statement in part 1. A block is a run of statements that Python handles as one unit, and in Python you mark it with indentation: all the lines of a block are indented by the same amount. Above, the two indented print lines make up the block of the if. When the condition is true Python runs the whole block, and when it's false Python skips the whole block. Where the indentation stops, the block stops too, which is why the last print runs every time. Which block a statement belongs to is decided by its indentation alone, so moving a line four spaces to the left or right can change what the program does.
Everything that isn't indented belongs to the program's main block, the outermost one. Its lines have no indentation at all, so even one space before a line of the main block is an error:
print("Line one")
print("Line two")
File "main.py", line 2
print("Line two")
IndentationError: unexpected indentAn IndentationError is a kind of syntax error, so Python runs nothing at all, not even line 1. The same goes for a block that is missing: after a line that ends with a colon, Python expects at least one indented line, and stops with IndentationError: expected an indented block if there isn't one.