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 lessonThis 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:
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.
| Runs | Expected 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
- Add Comments and a DocstringBeginner
- Fix the Bad Variable NamesBeginner
- Rewrite Messy Code with PEP 8 StyleBeginner
All Python exercises · 50 practice problems · Python Fundamentals quiz