Python looks different from most other programming languages. There are no curly braces wrapping blocks of code, and no end keywords closing statements. Instead, Python uses indentation to show which lines belong together. This is the first thing to understand before writing anything beyond a single line.
If you have already written your first program, you have seen that a simple print() line sits at the left margin. Now you need to understand what happens when you add structure.
Why Python uses indentation
In languages like JavaScript, Java, or C++, you wrap a block of code in curly braces:
if (x > 0) {
console.log("positive");
}Python drops the braces and uses the indentation itself to define the block:
if x > 0:
print("positive")The colon at the end of the first line says "a block is starting." The indented line underneath is inside that block. When you stop indenting, the block ends.
This approach was an intentional design choice by Python's creator, Guido van Rossum. The idea is that code should look like what it does. If a line is visually inside a block, it is inside that block. There is no way for indentation to lie about structure.
The basic syntax rules
Every Python statement sits on its own line. You do not need a semicolon at the end:
name = "Ada"
print(name)Statements run in order, top to bottom. A line that starts a block ends with a colon (:). The next line must be indented:
if temperature > 30:
print("It is hot outside.")
print("Drink water.")Both print calls are indented the same amount, so both are inside the if block. The block ends when a line returns to the previous indentation level:
if temperature > 30:
print("It is hot outside.")
print("Drink water.")
print("Weather report complete.") # outside the if blockThe last print runs regardless of the condition because it is not indented under the if.
How indentation defines blocks
Blocks can nest. Each level of nesting means one more level of indentation:
if score >= 50:
print("You passed.")
if score >= 90:
print("Outstanding performance!")
print("Check your email for results.")Here the first print and the inner if are at the same indentation level (one level deep). The second print is two levels deep, so it only runs when both conditions are true. The last print is back to one level deep, so it runs whenever score >= 50.
Python determines block boundaries by comparing indentation levels. When indentation increases, Python pushes an INDENT token. When it decreases, Python pushes DEDENT tokens. If you want to understand this process in more detail, read how Python runs your code.
Spaces versus tabs
Use spaces. Four spaces per indentation level. This is the recommendation in PEP 8, the official Python style guide, and it is the standard across every Python codebase you will encounter.
Most editors can be configured to insert spaces when you press Tab. In VS Code, this setting is called "Insert Spaces" and is on by default for Python files. In PyCharm, it is under Editor > Code Style > Python.
If you mix tabs and spaces in the same file, Python raises a TabError:
TabError: inconsistent use of tabs and spaces in indentationThis error exists to protect you. Mixing tabs and spaces makes code look different in different editors, which can hide bugs. If you see this error, pick spaces and reformat the file.
Indentation in practice
Here is a function that shows several levels of indentation:
def classify_number(n):
if n < 0:
return "negative"
elif n == 0:
return "zero"
else:
if n % 2 == 0:
return "positive even"
else:
return "positive odd"Notice the pattern. The body of def is indented once. Inside that, the bodies of if, elif, and else are indented again. The return inside each branch is indented one more level. Every line's position tells you exactly which block owns it.
This is also how loops work:
for item in shopping_list:
print(f"Checking: {item}")
if item == "eggs":
print(" Found eggs, stopping.")
breakThe for block contains everything indented underneath it. The if inside the loop adds another level. The break is inside the if, so it only fires when the condition is met.
Common indentation mistakes
Forgetting the colon. A block header like if, for, def, or class must end with :. Without it, Python does not expect a block:
if x > 0 # missing colon
print("positive") # IndentationErrorInconsistent indentation within a block. Every line in the same block must use the same number of spaces:
if x > 0:
print("one")
print("two") # IndentationError: unexpected indentUnindenting too far. When you unindent, you must return to a level that already exists on the indentation stack:
if x > 0:
print("one")
print("two") # IndentationError: unindent does not matchIndenting when there is no block. A line should only be indented if it belongs to a block introduced by a colon on the previous line:
print("hello")
print("world") # IndentationError: unexpected indentWhen you see an IndentationError, look at the line number in the error message. Check that the line is indented correctly relative to the lines above it. If you need more help with error messages, see reading Python error messages.
Line continuation
Sometimes a single statement is too long to fit on one line. Python gives you two ways to break it up.
Implicit continuation works inside parentheses, brackets, and braces:
total = (item_price + shipping_cost
+ tax - discount)As long as you are inside (), [], or {}, Python knows the statement continues on the next line. No special character is needed, and the indentation of the continuation line does not matter (though aligning it for readability is good practice).
Explicit continuation uses a backslash at the end of a line:
if score > 50 and time < 60 \
and not penalty:
print("Qualified")The backslash tells Python to ignore the newline. This is less common. Prefer implicit continuation with parentheses when possible because it is cleaner and allows comments on continuation lines.
Blank lines and vertical spacing
Blank lines are ignored by Python. Use them to separate logical sections within your code:
def calculate_total(items):
subtotal = sum(item.price for item in items)
if subtotal > 100:
subtotal *= 0.9 # 10% discount
return subtotalThe blank lines separate the calculation, the discount logic, and the return statement. This does not affect how the code runs, but it makes the code easier to read.
A blank line inside the interactive interpreter (REPL) ends a multi-line block. In a .py file, blank lines have no such effect.
Setting up your editor for indentation
The easiest way to avoid indentation problems is to configure your editor once:
- Set "Tab Size" to 4.
- Enable "Insert Spaces" so that pressing Tab inserts 4 spaces instead of a tab character.
- Enable "Render Whitespace" if you want to see dots for spaces, which helps spot inconsistencies.
If you have not set up a workspace yet, follow the Python workspace setup guide for step-by-step editor configuration.
After indentation, the next fundamental skill is adding notes to your code. Continue to writing comments in Python.
Rune AI
Key Insights
Python uses indentation to define code blocks, not braces or keywords; Use 4 spaces per indentation level; Never mix tabs and spaces; A consistent indentation style makes your code readable and error-free; Most editors can auto-indent and highlight indentation mistakes.
Frequently Asked Questions
How many spaces should I use for indentation in Python?
What happens if I mix tabs and spaces?
Can I use 2 spaces instead of 4?
Do I need to indent every line?
Why does Python enforce indentation when other languages do not?
Conclusion
Indentation is not a style preference in Python. It is how the language defines structure. Use 4 spaces per level, stay consistent, and let your editor handle the spacing. Once you internalize this rule, reading and writing Python becomes much smoother.
More in this topic
Python Keywords Explained
Learn what Python keywords are, which words are reserved, and why you cannot use them as variable or function names.
Getting User Input in Python
Learn how to use Python's input() function to collect information from the user and build interactive programs.
Printing Output in Python
Learn how to use Python's print() function to display messages, format output, and control how text appears on screen.