Editor

Rewrite Messy Code with PEP 8 Style

Beginner · Write the code · from Writing Clean Python: Comments, Docstrings, and PEP 8

From the lesson: Writing Clean Python: Comments, Docstrings, and PEP 8

Imagine opening a cookbook where every recipe is scribbled in messy handwriting, with no labels, no ingredient lists, and no spacing between steps. You could figure it out eventually, but it would be painful. Code works the same way.

Read the lesson

The code below is messy. Rewrite it following PEP 8 rules:

def calcArea(W,H):
  result=W*H
  return result
def calcPerimeter(W,H):
  result=2*(W+H)
  return result
w=8
h=5
print(f"Area: {calcArea(w,h)}")
print(f"Perimeter: {calcPerimeter(w,h)}")

Fix these issues:

  • Function names should be snake_case
  • Use 4 spaces for indentation
  • Add spaces around operators and after commas
  • Add two blank lines between function definitions
  • Use meaningful variable names
  • The output must be:

    Area: 40
    Perimeter: 26
    # Rewrite the messy code below following PEP 8 rules

    More Writing Clean Python exercises

    All Python exercises · 50 practice problems · Python Fundamentals quiz