livepython.net
CHAPTER 16Styling Your Code (PEP 8)
16.3  SPACING

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 if in 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.
PYTHONedit me
def count_passes(marks):
    passes = 0
    for mark in marks:
        if mark >= 40:
            passes += 1
    return passes


print(count_passes([35, 80, 52]))
OUTPUT
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:

PYTHONedit me
def greet(name):
    print("Hello", name)
        print("Welcome!")
OUTPUT
IndentationError: unexpected indent

A tab mixed with spaces. The third line below starts with one tab character, which looks the same on screen:

PYTHONedit me
def greet(name):
    print("Hello", name)
	print("Welcome!")


greet("Sunny")
OUTPUT
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.

your turnFix the code

Fix the indentation so the code prints: Total: 30

It should print: Total: 30

def show_total(prices):
    total = sum(prices)
  print("Total:", total)


show_total([10, 20])
This code does not work yet. Fix it, then press Run.
your turnPredict the output

What will this print?

for n in [1, 2]: print("Hi") print("Bye")
Your turn! What will this code show on the screen?

Spaces Around Operators and After Commas

Whitespace means the spaces in your code. PEP 8 has a simple goal for them: put spaces where they help the eye split the line into parts, and nowhere else.

Think of it like the spaces between words in a sentence. Withoutspacesitishardtoread. With too many, it falls apart.

The rules

Write thisNot thisRule
total = price * qtytotal=price*qtyone space on each side of =, +, *, ==, >=, +=
print(name, age)print(name,age)one space after a comma
print(name, age)print(name , age)no space before a comma
print(total)print( total )no space just inside brackets
print(total)print (total)no space before the ( of a call
scores[0]scores [0]no space before the [ of an index
print(a, b, sep="-")print(a, b, sep = "-")no spaces around = in a keyword argument

The last rule is the surprising one. = gets spaces when it stores a value in a variable. Inside the brackets of a call, like sep="-", or in a default value, like def greet(name="friend"):, it gets none.

PYTHONedit me
def greet(name="friend"):
    return "Hi " + name


first = greet()
second = greet(name="Sunny")
print(first, second, sep=" | ")
OUTPUT
Hi friend | Hi Sunny

Don't line things up

PYTHONedit me
x     = 1
long_name = 2
print(x + long_name)
OUTPUT
3

It looks neat, but when you add a longer name, you have to change the spaces on every line. PEP 8 says: one space before =, always.

Common beginner doubt: "Does print (total) with a space break the code?" No, Python runs it. That's what makes style hard: nothing warns you. You have to see it yourself.

One space around operators and after commas; no spaces inside brackets or around keyword =.

your turnPick the right idea

Which line follows PEP 8?

Think about it, then pick one.
your turnPredict the output

Remember sep from chapter 2?

print("Sunny", "Rocky", sep="-")
Your turn! What will this code show on the screen?

Blank Lines Between Functions

Blank lines split your program into parts, the way paragraphs split a story. PEP 8 has one clear rule for them: put two blank lines before and after every function that starts at the left edge.

Think of it like the space between two letters in a stack of mail. Each letter is one piece; the gap shows where the next one starts.

The rules

  • Two blank lines before and after each function defined at the left edge (a top-level function).
  • Inside a function, use one blank line now and then, to separate steps. Not after every line.
  • No long runs of blank lines anywhere else.
PYTHONedit me
TAX_RATE = 0.18


def add_tax(price):
    return price + price * TAX_RATE


def print_bill(item, price):
    print(item, "costs", add_tax(price))


print_bill("Pen", 100)
OUTPUT
Pen costs 118.0

Look at the shape: the constant, a gap, the first function, a gap, the second function, a gap, the main program. Your eye finds each function in a second.

One blank line inside a function

PYTHONedit me
def report(marks):
    total = sum(marks)
    average = total / len(marks)

    print("Total:", total)
    print("Average:", average)


report([60, 80])
OUTPUT
Total: 140
Average: 70.0

The blank line separates "work it out" from "show it". That's a good reason for one blank line.

Common beginner doubt

"Does Python need these blank lines?" No. Blank lines never change what a program does. Delete them all and it prints the same thing. They're only for the reader, like everything else in PEP 8.

Two blank lines around every top-level function; one, sometimes, inside.

your turnPick the right idea

How many blank lines go between two top-level functions?

Think about it, then pick one.
your turnPredict the output

What will this print?

print("A") print("B")
Your turn! What will this code show on the screen?

Line Length: About 79 Characters

PEP 8 says a line of code should be at most 79 characters long, and a comment line at most 72. Some teams agree on a little more, up to 99, but 79 is the standard.

Think of it like a newspaper. It prints text in narrow columns, because your eye loses its place on a very long line. Short lines also fit two files side by side on one screen, or a phone screen, with no scrolling sideways.

Break long lines inside brackets

Inside round ( ), square [ ] or curly brackets, Python lets a line continue on the next line. It waits for the closing bracket:

PYTHONedit me
players = [
    "Sunny",
    "Rocky",
    "Lucky",
]
print(len(players))
OUTPUT
3

A long calculation has no brackets of its own, so add a pair around it:

PYTHONedit me
rent = 12000
food = 6000
travel = 1500
internet = 800
monthly_total = (
    rent
    + food
    + travel
    + internet
)
print(monthly_total)
OUTPUT
20300

The rules

  • Break the line inside brackets, after an opening bracket or after a comma.
  • Indent the extra lines by 4 more spaces, so they don't look like a new statement.
  • In a long calculation, start each new line with the operator, like + food. PEP 8 suggests this, because you can read down the operators like a sum on paper.
  • Put the closing bracket on its own line, or at the end of the last line. Pick one way.

Avoid breaking without brackets

PYTHONedit me
total = 1 + 2
    + 3
OUTPUT
IndentationError: unexpected indent

Without brackets, a statement ends at the end of the line. Python thinks + 3 is a new line that's moved in for no reason.

Common beginner doubt: "What about a backslash \ at the end of a line?" It also works, but one invisible space after it breaks the code. PEP 8 prefers brackets.

Keep lines under 79 characters; to break one, use brackets and indent the rest.

your turnFill the gap

Pick the bracket that lets the line continue

total = ?10 + 20 + 30) print(total)

It should print: 60

Which piece makes this code work?
your turnPredict the output

Remember default values from the Functions chapter?

def greet(name="friend"): return "Hi " + name print(greet())
Your turn! What will this code show on the screen?

Practice: Spacing

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 145.Fix the Indentation in a Python FunctionEasySolve
  2. 146.Python Program to Break a Long Line of Code (PEP 8)MediumSolve