Python Indentation, Spacing and Line Length (PEP 8)
Python Indentation: 4 Spaces per Level
Indentation is the space at the start of a line. In Python it's not only style: it decides which lines belong to an if, a loop or a function (chapter 8). PEP 8 adds the style part: use 4 spaces for each level.
Think of it like the chapters, sections and paragraphs in a book. Each level is moved in by the same amount, so you can see at a glance what belongs where.
The rules
- Every level adds 4 spaces: 4 inside a function, 8 inside an
ifin that function, 12 one level deeper. - Use spaces, not tab characters. Set your editor so the Tab key types 4 spaces (most editors already do).
- Every line in one block lines up exactly.
def count_passes(marks):
passes = 0
for mark in marks:
if mark >= 40:
passes += 1
return passes
print(count_passes([35, 80, 52]))2
Follow the spaces: the for is inside the function (4), the if is inside the for (8), and passes += 1 is inside the if (12). return is back at 4, so it runs after the loop is done.
Indentation errors
A line that's moved in for no reason:
def greet(name):
print("Hello", name)
print("Welcome!")IndentationError: unexpected indent
A tab mixed with spaces. The third line below starts with one tab character, which looks the same on screen:
def greet(name):
print("Hello", name)
print("Welcome!")
greet("Sunny")TabError: inconsistent use of tabs and spaces in indentation
Every error is a clue! A TabError means "some lines use tabs, some use spaces". The fix is always the same: use 4 spaces everywhere.
Indent with 4 spaces per level, never tabs, and line up every block exactly.