CodingNic

Testing and Best Practices

Code Style (PEP 8)

Testing and Best Practices 32 min read

Code Style (PEP 8)

Code Style (PEP 8)

Good code should not only work.

It should also be easy to read.

Python has a style guide called PEP 8 that helps developers write clean and consistent code.

What Is PEP 8?

PEP 8 is the official Python style guide.

It gives recommendations for formatting Python code.

Why Style Matters

Good style helps you:

  • read code faster
  • reduce mistakes
  • work with teams
  • maintain projects
  • look professional

Example: Poor Style

python
def add(a,b):return a+b

Harder to read.

Better Style

python
def add(a, b):
    return a + b

Common PEP 8 Rules

1. Use Spaces Around Operators

Good:

python
total = a + b

Bad:

python
total=a+b

2. Use snake_case for Variables and Functions

Good:

python
user_name = "Tom"

def get_total():
    pass

Bad:

python
userName = "Tom"
def GetTotal():
    pass

3. Use CapitalWords for Classes

python
class BankAccount:
    pass

4. Keep Lines Readable

Do not make very long lines.

5. Use Blank Lines

Separate functions and sections clearly.

python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b

6. Use Clear Names

Good:

python
price = 10
total_cost = 50

Bad:

python
x = 10
y = 50

Example Cleanup

Before:

python
def calc(x,y):
 return x+y

After:

python
def calc(x, y):
    return x + y

Helpful Tools

Common tools that check style:

  • flake8
  • black

You can learn them later.

Code Along

Rewrite messy code using better spacing and names.

Mini Challenge

Improve this code:

python
class useraccount:
 def GetBalance(self):
  return 100

Expected improved version:

python
class UserAccount:
    def get_balance(self):
        return 100

Real World Use Case

Teams use style guides so everyone writes clean, consistent code.

Quiz

  1. What is PEP 8?
  2. Why does style matter?
  3. What naming style is used for functions?
  4. What naming style is used for classes?

Assignment

Take one old program and rewrite it using better names and spacing.

Summary

You learned basic PEP 8 style rules that make Python code cleaner and easier to read.