Refactoring
Python · Unit 19: Clean code
- Full plan
- Python
- 10 exercises
Refactoring means changing how the code is written without changing what it does.
Instead of two nearly equal print lines, a loop. The proof that it went well is that it prints exactly what it printed before.
names = ["amy", "leo"]
for n in names:
print("Hello", n)Prints
Hello amy Hello leo
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Find the bug
Both prices carry the same tax, so it should print 116 and 232. Which line got left behind?
3. Put the lines in order
Put the program in order. The tax math must be written once and only once.
4. Complete the code
totalused to add the prices with a loop. Now it fits in one line: pick the one that gives exactly the same.5. Predict the output
What does this code print?
6. Multiple choice
What has to stay true after refactoring?
7. Find the bug
Somebody shortened
meanand changed the result. With [3, 4] it should print 3.5. Which line has the error?8. Complete the code
This ladder of
ifwas swapped for a dictionary. Complete it so an unknown size still costs 0.9. Predict the output
What does this code print?
10. Write the code
totaladds three prices by hand and crashes with lists of any other size. Rewrite it so it adds up every price it gets. You can change what's inside; the name and what it gives back stay the same.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.