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

What Is PEP 8? The Python Style Guide Explained

What Is PEP 8?

PEP 8 is the official style guide for Python: a list of habits for how your code should look. Where to put spaces, how to name things, how long a line may be. It doesn't change what your program does. It changes how easy it is to read.

PEP stands for "Python Enhancement Proposal", a document that suggests something for Python. PEP 8 was written in 2001 by Guido van Rossum, the creator of Python, together with two other Python developers. Almost every Python programmer in the world follows it.

Think of it like handwriting rules at school: write on the lines, leave a space between words, start a sentence with a capital letter. Your teacher can still read messy handwriting, but neat handwriting is read faster, and with fewer mistakes.

Same program, two looks

PYTHONedit me
price=250;qty=3
total=price*qty
print("Total:",total)
OUTPUT
Total: 750
PYTHONedit me
price = 250
qty = 3
total = price * qty
print("Total:", total)
OUTPUT
Total: 750

Both print the same thing. Python doesn't care which one you write. People do: the second one reads like a sentence.

What PEP 8 covers

AreaAn example ruleYou'll learn it in
Namesvariables in snake_caseNaming
Indentation4 spaces per levelSpacing
Spacesone space on each side of =Spacing
Line lengthabout 79 characters at mostSpacing
Layoutone statement per lineClean code
Commentsstart with # and explain whyClean code

Good news: you already follow some of these. You met snake_case in chapter 4, the 4-space indentation in chapter 8, and good comments in chapter 6. This chapter puts them all in one place, and adds the rest.

PEP 8 is Python's style guide: it changes how your code looks, not what it does.

your turnPick the right idea

What does following PEP 8 change about your program?

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

What will this print?

a=5;b=2 print(a*b)
Your turn! What will this code show on the screen?

Why Code Style Matters

Readability means how easy your code is for a person to read. PEP 8 is built on one idea from Guido van Rossum: "Code is read much more often than it is written."

You write a line once. Then you read it again and again: when you fix a bug, when you add a feature, when a teammate learns from it. So the reader matters more than the writer.

Think of it like recipe cards in a shared kitchen. If every cook writes cards the same way, ingredients first and steps after, anyone can pick up any card and start cooking.

Who reads your code?

  • You, next month. You will forget why you wrote it that way.
  • Your teammates. In a team, everyone writes in the same style, so the code looks like one person wrote it.
  • Whoever checks your work: a teacher, a reviewer, or an interviewer.

Can you tell what this does?

PYTHONedit me
x=1200
y=0.18
z=x+x*y
print(z)
OUTPUT
1416.0

It works, but what is x? What is y? You have to guess. Now the same program, written for the reader:

PYTHONedit me
price = 1200
tax_rate = 0.18
price_with_tax = price + price * tax_rate
print(price_with_tax)
OUTPUT
1416.0

Now the code explains itself: a price, plus 18% tax. If the tax rate changes, you know exactly which line to edit.

Clean code hides fewer bugs

When code is tidy, a mistake stands out, like a crooked picture on a straight wall. In messy code, every line looks a little wrong, so the real bug blends in.

Common beginner doubt: "My program works. Why should I care about style?" Because working is only the first job of code. The second job is to be easy to read and change. Messy code that works today is hard to fix tomorrow.

You write code once but read it many times, so write it for the reader.

your turnFill the gap

Use the clear name to finish the line

price = 1200 tax_rate = 0.18 price_with_tax = price + price * ? print(price_with_tax)

It should print: 1416.0

Which piece makes this code work?
your turnPick the right idea

Why does PEP 8 care so much about readability?

Think about it, then pick one.

Style Rules vs Python Rules

Some rules are enforced by Python: break one, and your program stops with an error. Most PEP 8 rules are style rules: Python runs your code anyway, but people find it harder to read.

Think of it like a football match. A foul makes the referee stop the game. Passing badly is allowed, and the game goes on, but your team plays worse.

RuleWho checks itIf you break it
Indent the block under if, for, defPythonIndentationError
Line up every line in a blockPythonIndentationError
A name can't start with a numberPythonSyntaxError
Use 4 spaces, not 2PEP 8runs fine
One space on each side of =PEP 8runs fine
snake_case namesPEP 8runs fine

Two spaces work, but aren't the style

PYTHONedit me
if 5 > 3:
  print("Two spaces work")
  print("but PEP 8 says 4")
OUTPUT
Two spaces work
but PEP 8 says 4

Python only needs the lines of a block to line up. It doesn't count how many spaces you use.

Mixing is the real danger

PYTHONedit me
if 5 > 3:
    print("Four spaces")
  print("Two spaces")
OUTPUT
IndentationError: unindent does not match any outer indentation level

Don't be scared of this error! It's saying: "this line is moved left, but not to a place where any block starts". Unindent means moving a line back to the left. When you use 4 spaces every time, you never mix, and this error never happens.

So who checks the style?

You do. Python won't warn you about a missing space or a bad name. In this chapter's practice questions, the tests check your output only, so the style is your own job: read your code once more before you submit it.

Python enforces only a few rules. PEP 8 style is your job, so check it yourself.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPick the right idea

Which one makes Python stop with an error?

Think about it, then pick one.

Be Consistent: Pick One Way

The most important style rule is consistency: once you pick a way to write something, write it that way everywhere. PEP 8 itself says that consistency inside one project matters more than any single rule.

Think of it like the signs in a train station. It matters less which colour the exit signs are. It matters a lot that every exit sign has the same colour.

Quotes are a good example

Python accepts single and double quotes, and PEP 8 doesn't choose one for you:

PYTHONedit me
first_name = "Sunny"
last_name = 'Rocky'
print(first_name, last_name)
OUTPUT
Sunny Rocky

It runs, but a reader wonders: "Is there a reason these are different?" There isn't. Pick one kind and stick to it:

PYTHONedit me
first_name = "Sunny"
last_name = "Rocky"
print(first_name, last_name)
OUTPUT
Sunny Rocky

The one exception: when the text itself has a quote inside, use the other kind, so you don't need a backslash (chapter 2):

PYTHONedit me
print("It's Lucky's turn")
print('She said "hi"')
OUTPUT
It's Lucky's turn
She said "hi"

The rules

  • Pick one style for quotes, names and spacing, and use it in the whole program.
  • In a team, follow the team's style, even if you'd choose differently.
  • When you change someone else's code, match the style that's already there.
  • PEP 8 also says: if a rule makes one piece of code harder to read, it's fine to break it there. Readability is the goal, the rules are the tools.

Common beginner doubt: "Single or double quotes: which one is right?" Both are right. This course uses double quotes, so you'll see them everywhere here. What's wrong is switching between them for no reason.

Pick one way of writing each thing and use it everywhere.

your turnPick the right idea

Your team always uses single quotes. What should you write?

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

Remember sorted() from the Lists chapter?

scores = [72, 95, 88] print(sorted(scores)) print(scores)
Your turn! What will this code show on the screen?

Practice: PEP 8

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

  1. 140.Python Program to Rewrite Squashed Code in PEP 8 StyleEasySolve
  2. 141.Fix a Messy Python Program That Won't RunMediumSolve