Editor

Refactor: Clean Up This Code

Beginner · Refactor · 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

This function works but it's messy. Refactor it to be clean and professional:

def d(p,r):
  a=p*r/100
  t=p-a
  return t
print(d(200,15))

Your refactored version must:

  • Give the function a meaningful name (it calculates a discounted price)
  • Use descriptive parameter names
  • Add a docstring explaining what the function does
  • Use proper PEP 8 spacing (4-space indent, spaces around operators)
  • Use two blank lines before the function call
  • The output must be:

    170.0
    # Refactor the messy code into clean, professional Python

    What Check runs

    Your code runs first, then each of these lines. The output must match exactly.

    RunsExpected output
    print(calculate_discounted_price(200, 15))170.0
    print(calculate_discounted_price(100, 25))75.0
    print(calculate_discounted_price.__doc__ is not None)True

    More Writing Clean Python exercises

    All Python exercises · 50 practice problems · Python Fundamentals quiz