Skip to Content
Course content

8: Understanding PEP 8 and Code Style

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why should I care about a style guide if my code already runs?

I get this question a lot. When you're working alone on a small script, PEP 8 feels like a set of arbitrary rules designed to slow you down. But here's the reality: you spend ten times more time reading code than you do writing it. Whether that's reading your own code six months from now or collaborating with a teammate, consistent style reduces the "cognitive load."

Imagine you're reading a book where the author randomly switches between lowercase, UPPERCASE, and Bold for no reason. You'd get exhausted just trying to parse the sentences. Coding is the same. When you follow PEP 8, you stop thinking about how the code is written and start focusing on what it's actually doing.

What are the naming conventions I actually need to memorize?

You don't need to memorize the whole document, but there are a few naming patterns that are non-negotiable in the Python community. If you mix these up, experienced devs will notice immediately.

  • Functions and variables: Use snake_case. All lowercase, words separated by underscores.
  • Classes: Use PascalCase (also called CapWords). Capitalize every word, no underscores.
  • Constants: Use UPPER_SNAKE_CASE. These are variables that never change during the program's execution.
# This is the "Pythonic" way
MAX_RETRY_ATTEMPTS = 5  # Constant

class UserProfile:      # Class
    def __init__(self, username):
        self.username = username

def calculate_total_price(items):  # Function
    current_total = 0              # Variable
    for item in items:
        current_total += item.price
    return current_total

I've seen people use camelCase for functions because they come from a Java or JavaScript background. While it works, it'll make your Python code look like a translation rather than a native piece of software.

How do I handle long lines and whitespace without going crazy?

PEP 8 suggests a limit of 79 characters per line. Honestly? In the modern era of ultra-wide monitors, that feels a bit restrictive. Most professional teams now lean toward 88 or 100 characters. The core goal, however, is to avoid horizontal scrolling.

If you have a long list or a function call with ten arguments, don't just let it trail off the screen. Use "vertical hanging indents." Also, be mindful of your whitespace. Put two blank lines between top-level functions and classes, and one blank line between methods inside a class. It gives the code room to breathe.

# Hard to read:
my_list = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew"]

# Much better:
my_list = [
    "apple", "banana", "cherry", "date", 
    "elderberry", "fig", "grape", "honeydew",
]

Do I really have to do this all by hand?

Absolutely not. In fact, I'd tell you not to. Manually checking for two spaces instead of one is a waste of your engineering talent. We use "linters" and "formatters."

A linter (like Flake8 or Ruff) tells you when you've broken a rule. A formatter (like Black) just fixes it for you automatically. I personally use Black; it's known as "the uncompromising formatter." It doesn't give you options—it just reformats your code to a strict standard. It ends all arguments in code reviews about where a comma should go, which is a huge win for team sanity.




📋 Practical Task

Exercise: Refactoring the Messy Warehouse Manager

Below is a piece of code that functions perfectly but violates almost every PEP 8 convention. Your task is to refactor this code to be "Pythonic."

Requirements:

  • Fix the naming conventions for the class, the constant, and the functions.
  • Correct the whitespace (indentation and blank lines).
  • Fix the long list formatting.
# REFACTOR THIS CODE
tax_rate = 0.07
class warehouse_manager:
    def __init__(self, location):
        self.location=location
    def add_item(self,item_name,quantity,price):
        print(f"Adding {quantity} of {item_name} to {self.location}")
    def CalculateTax(self,amount):
        return amount * tax_rate

def run_app():
    my_warehouse = warehouse_manager("North Sector")
    inventory_list = ["Steel Beam", "Copper Wire", "Iron Plate", "Aluminum Sheet", "Zinc Bolt", "Brass Valve", "Nickel Pipe"]
    my_warehouse.add_item("Steel Beam", 10, 100)
    print(my_warehouse.CalculateTax(1000))

run_app()
Rating
0 0

There are no comments for now.

to be the first to leave a comment.