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
def add(a,b):return a+b
Harder to read.
Better Style
def add(a, b):
return a + b
Common PEP 8 Rules
1. Use Spaces Around Operators
Good:
total = a + b
Bad:
total=a+b
2. Use snake_case for Variables and Functions
Good:
user_name = "Tom"
def get_total():
pass
Bad:
userName = "Tom"
def GetTotal():
pass
3. Use CapitalWords for Classes
class BankAccount:
pass
4. Keep Lines Readable
Do not make very long lines.
5. Use Blank Lines
Separate functions and sections clearly.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
6. Use Clear Names
Good:
price = 10
total_cost = 50
Bad:
x = 10
y = 50
Example Cleanup
Before:
def calc(x,y):
return x+y
After:
def calc(x, y):
return x + y
Helpful Tools
Common tools that check style:
flake8black
You can learn them later.
Code Along
Rewrite messy code using better spacing and names.
Mini Challenge
Improve this code:
class useraccount:
def GetBalance(self):
return 100
Expected improved version:
class UserAccount:
def get_balance(self):
return 100
Real World Use Case
Teams use style guides so everyone writes clean, consistent code.
Quiz
- What is PEP 8?
- Why does style matter?
- What naming style is used for functions?
- 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.