Indentation and Semicolon Rules
Python has chosen a different way to structured the code. Instead of following the path other programming languages chose via curly braces {} or keywords to define code blocks, Python uses indentation (whitespace at the beginning of lines) to determine the structure of code. This might seem unusual at first, but it actually makes Python code more readable and consistent.
What is Indentation?
Indentation refers to the spaces or tabs at the beginning of a line of code. In Python, indentation is not just for readability, it’s part of the syntax. The amount of indentation tells Python which code belongs to which block.
if x > 5: print("x is greater than 5") print("This is also inside the if block")print("This is outside the if block")In this example, the first two print() statements are indented (they have spaces at the beginning), so they belong to the if block. The third print() statement is not indented, so it’s outside the if block.
How Indentation Works
Python uses indentation to group statements together. When a block is started (like after an if statement, while loop, or for loop), the code that belongs to that block must be indented. When the block ends, the next line is outdented.
Basic Rules
- Consistent indentation - All statements in the same block must have the same level of indentation.
- Increase indentation - After a colon
:, the next line must be indented. - Decrease indentation - To end a block, return to the previous indentation level.
Most Python devs usually indent the code by having either 1-tab, 2 spaces or 4 spaces. But in fact we can have as much as we want so long that we are consistent. We can start a block and indent each line by 3 spaces, then inside of it we can start another block and indent the code by 2 spaces.
x = 1y = 2if x > 0: # 3 spaces if y > x: # 2 spaces print("Hi!")Tip
The standard indentation is 4 spaces per level. Tabs are strongly discouraged.
Common Indentation Errors
Error 1: Forgetting to Indent
This will cause an IndentationError.
if x > 5:print("x is greater than 5") # ERROR: This line must be indentedError 2: Inconsistent Indentation
Both statements must have the same indentation.
if x > 5: print("First statement") print("Second statement") # ERROR: Different indentation levelError 3: Mixing Spaces and Tabs
Python can get confused if the code uses a mix of spaces and tabs. Stick to one method.
if x > 5: print("Spaces") # Uses spaces print("Tabs") # Uses tabs - ERROR!Semicolons in Python
In Python, a semicolon denotes the separation of statements rather than the termination. It allows us to write multiple statements on one line. Python will throw an error if you use a semicolon to separate a normal expression from a block statement i.e loop.
x = 1; y = 2 #Two statementsz = 1;print(x); print(y)
if x == z: print(x); print(z);else: print(y); print(z)
print("Hello"); for i in range(10): print(i) #Throws an errorprint("Hello"); for i in range(10): print(i) #Throws an errorNote
Generally, this goes against Python’s philosophy of readability.
Simple statement and Compound statement
A simple statement is comprised within a single logical line. It does not contain other statements inside it and it executes as one unit.
passbreakcontinuereturnraiseimport mathx = 5Note
Something like this
x = 5; y = 10; print(x + y)is just three simple statements separated with a semicolon.
A compound statement consists of one or more clauses. A clause consists of a header and a suite. The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon (if, while, for, …). A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Thus a compound statement contain other statements, and controls a suite (a block).
if condition: statementwhile condition: statementfor item in iterable: statementdef func(): statementclass MyClass: statementtry: statementexcept: statementEach clause (like the if part, the else part, or the except part) can have a suite, and that suite can be either:
- Indented block on new lines.
- A list of semicolon-separated simple statements on the same line.
if x == y: print(x)else: print(y)
for i in range(5): print(i)
i = 0while i < 10: i += 1; print(i)
if 1 == 12: print(1); print(2);else: print(3)Writing Statements on the Same Line
Simple statements can be written on the same line as control structures in Python, though there are certain limitations.
A single simple statement can be written on the same line as an if, for, or while:
if x == 2: print("x is 2")This is equivalent to:
if x == 2: print("x is 2")In combination with semicolon:
if x == 2 and y == 2: print("x is 2"); print("y is 2");Only simple statements can be used on the same line. Complex statements (like nested if statements or loops) cannot be written this way:
# This worksif x > 5: print("Yes")
# This does NOT workif x > 5: if y > 5: print("Both") # ERROR: Syntax errorExercises
Below are some exercises to test your understanding of indentation and semicolon rules in Python.
Exercise 1: Indentation requirement
Is the following statement true or false?
In Python, indentation is optional and only used for readability purposes.
False. In Python, indentation is not optional, it’s part of the syntax. Python uses indentation to determine the structure of code blocks, unlike languages that use curly braces {} or keywords.
Exercise 2: Identifying indentation error
What is wrong with this code?
if x > 5: print("x is greater than 5") print("This is also inside the if block")The code has inconsistent indentation. The second print() statement has a different indentation level (2 spaces) compared to the first one (4 spaces). All statements in the same block must have the same level of indentation. This will cause an IndentationError.
The correct code is:
if x > 5: print("x is greater than 5") print("This is also inside the if block")Exercise 3: Semicolon usage
Is the following statement true or false?
Semicolons in Python are used to terminate statements, similar to how they work in languages like JavaScript or C++.
False. In Python, semicolons are used to separate statements on the same line, not to terminate them. Python doesn’t require statement terminators. While semicolons can be used to write multiple statements on one line (e.g., x = 1; y = 2), this is generally discouraged as it goes against Python’s philosophy of readability.
Exercise 4: Missing indentation error
What error will this code produce?
if x > 5:print("x is greater than 5")This code will produce an IndentationError. After a colon : in Python (which starts a block), the next line must be indented. The print() statement is not indented, so Python doesn’t know that it belongs to the if block.
The correct code should be:
if x > 5: print("x is greater than 5")Exercise 5: Semicolon with loops
What is wrong with this code?
print("Hello"); for i in range(10): print(i)This code will throw a SyntaxError. You cannot use a semicolon to separate a simple statement from a compound statement (like a for loop). The semicolon can only separate simple statements from other simple statements.
The correct way to write this would be:
print("Hello")for i in range(10): print(i)Exercise 6: Code block identification
Which lines belong to the if block in this code?
if x > 5: print("First statement") print("Second statement")print("Third statement")if y > 10: print("Fourth statement")- Lines 2 and 3 belong to the first
if x > 5:block (they are indented) - Line 4 (
print("Third statement")) is not part of anyifblock (it’s not indented) - Line 6 belongs to the second
if y > 10:block (it’s indented)
The indentation level determines which code belongs to which block.
Exercise 7: Simple statement on same line
Is this code valid?
if x == 2: print("x is 2"); print("y is also 2")Yes, this code is valid. Simple statements can be written on the same line as a control structure (like if), and multiple simple statements can be separated with semicolons. However, this style is generally discouraged as it reduces readability.
Exercise 8: Nested compound statements
What is wrong with this code?
if x > 5: if y > 5: print("Both")This code will produce a SyntaxError. Nested compound statements (like nested if statements) cannot be written on the same line. Only simple statements can be written on the same line as a control structure.
The correct way to write this would be:
if x > 5: if y > 5: print("Both")Exercise 9: Semicolon placement
Which of these is valid Python code?
A: x = 1; y = 2; z = 3
B: x = 1; if y > 2: print(y)
C: if x > 5: print(x); else: print(0)
A and C are valid, but B is invalid.
- A: Valid. Multiple simple statements separated by semicolons.
- B: Invalid. Cannot separate a simple statement from a compound statement with a semicolon.
- C: Valid. Both the
ifandelseclauses can have simple statements on the same line, separated by semicolons.
Exercise 10: Fix multiple indentation and syntax errors
This code has multiple problems. Identify and fix all the errors to make it run correctly:
x = 5y = 10if x > 3:print("x is greater than 3") print("Checking y now")if y > x: print("y is greater than x") print("Both conditions met")else:print("y is not greater than x")print("Done"); for i in range(3): print(i)The code has 5 errors that need to be fixed:
- Missing indentation on line 4:
print("x is greater than 3")must be indented after theifstatement - Inconsistent indentation on line 5:
print("Checking y now")has 2 spaces but should have 4 spaces to match the block - Inconsistent indentation on line 8:
print("Both conditions met")has 2 spaces but should have 4 spaces to match theif y > x:block - Missing indentation on line 10:
print("y is not greater than x")must be indented after theelse:statement - Syntax error on line 11: Cannot use a semicolon to separate a simple statement from a compound statement (
forloop)
The corrected code is:
x = 5y = 10if x > 3: print("x is greater than 3") print("Checking y now")if y > x: print("y is greater than x") print("Both conditions met")else: print("y is not greater than x")print("Done")for i in range(3): print(i)