Mathew K Analytics

Lesson 4 · Python for Data Science

4 - Writing Clean Code with PEP 8 in Python

In this lesson, we will learn why style matters in Python and how to write readable, clean code. PEP 8 is the official Python style guide that helps…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to Writing Clean Code with PEP 8 in Python!#

In this lesson, we will learn why style matters in Python and how to write readable, clean code.

PEP 8 is the official Python style guide that helps everyone write code the same way.

Clean code is easier to read, share, and update.

Let us get started!

What is PEP 8?#

PEP 8 is a set of recommendations for writing Python code.

It covers things like:

  • spaces and indentation
  • naming your variables
  • using blank lines
  • and more!

Why Should I Care?#

Clean code is easier for you and others to understand.

If everyone uses the same style, it makes teamwork smooth.

It also helps you find bugs faster!

# Let us start with indentation.
# Python uses spaces to show which code is inside what.
for i in range(3):
    print("Hello!")

# Bad example (do not copy):
# for i in range(3):
# print("Hello!")
Hello!
Hello!
Hello!
# PEP 8 recommends using 4 spaces for each indentation level.
if True:
    print("This line is indented with exactly 4 spaces.")
    
This line is indented with exactly 4 spaces.
# Let us talk about blank lines.
# Blank lines help separate sections of your code.
def greet():
    print("Hello!")

def bye():
    print("Goodbye!")
    
# Variable and function names should be descriptive.
# Use lower_case_with_underscores by PEP 8.
favorite_color = "blue"
def print_color(color):
    print("Favorite color:", color)

print_color(favorite_color)
Favorite color: blue
# Avoid single-letter names except for short loops.
x = 12   # Not clear
age_in_years = 12  # Better and clear
# Comments explain why, not just what.
height_cm = 170  # height in centimeters
# Calculate height in meters
height_m = height_cm / 100
print("Height in meters:", height_m)
Height in meters: 1.7
# Spaces make math easier to see.
# Always put spaces around operators.
a = 5+3*2    # Not clear
b = 5 + 3 * 2  # Better
print("a:", a)
print("b:", b)
a: 11
b: 11
 

Around equals in function arguments, leave no spaces.#

def add(x, y=3): return x + y

print(add(2))

# Let us use input to get your favorite snack.
snack = input("What is your favorite snack? ")
print("Yum!", snack, "sounds delicious.")
Yum! popcorn sounds delicious.
 
# Constants should be in ALL_CAPS.
PI = 3.14159
radius = 2
area = PI * radius ** 2
print("Circle area:", area)
Circle area: 12.56636
# Use good spacing in lists and dictionaries.
colors = ["red", "green", "blue"]
person = {"name": "Eva", "age": 29}
print("Colors:", colors)
print("Person:", person)
Colors: ['red', 'green', 'blue']
Person: {'name': 'Eva', 'age': 29}
# Use two blank lines before top-level functions and classes.

def multiply(x, y):
    return x * y

print(multiply(3, 4))
12
# Inline comments should be clear and at least two spaces from code.
width = 50  # width in centimeters
length = 100  # length in centimeters
area_cm = width * length  # Calculate area in cm squared
print("Total area in cm squared:", area_cm)
Total area in cm squared: 5000

Mini-Project: Simple Scorekeeper#

Let us put PEP 8 in action with a small project!

We will write a program to keep track of two players' game scores.

You will enter points, and the program will print who is winning.

# Step 1: Set up player names and starting scores.
player_one = input("Player 1 name: ")
player_two = input("Player 2 name: ")

score_one = 0
score_two = 0
 
# Step 2: Enter scores and print who is winning.
score_one = int(input("Points for " + player_one + ": "))
score_two = int(input("Points for " + player_two + ": "))
if score_one > score_two:
    print(player_one, "is winning!")
elif score_two > score_one:
    print(player_two, "is winning!")
else:
    print("It is a tie!")
    
Bob is winning!
 
# Troubleshooting tip: Watch out for indentation errors.
for n in range(2):
    print("Good indentation!")
# print("This will cause an error") # This line should be indented.
Good indentation!
Good indentation!
# Extra tip: Tools like black or autopep8 can help format your code.
# They rewrite your code to match PEP 8 automatically.
print("Try using code formatters for big projects!")
Try using code formatters for big projects!

Recap: Writing Clean Code with PEP 8#

  • Use 4 spaces for indentation
  • Pick clear, descriptive names
  • Add comments that explain why
  • Use blank lines to separate code
  • Mind your spaces!

Following PEP 8 makes your code readable and easier to work with.

Thanks for learning about clean Python code with PEP 8!

Like this video if you found it helpful, comment your questions or ideas, and subscribe for more beginner Python lessons.

Share this with a friend who wants to write better code!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.