Small functions
Python · Unit 19: Clean code
- Full plan
- Python
- 10 exercises
A function does one thing. If it also prints while it calculates, it already does two, and whoever calls it is left without the result.
The one that calculates gives back a value, and that value is what lets you keep working.
def total(prices):
return sum(prices)
print(total([10, 20]))
print(total([5]) * 2)Prints
30 10
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
doubleshould be usable to keep calculating. Which line has the error?3. Complete the code
Complete it to keep only the passing grades.
4. Predict the output
What does this code print?
5. Put the lines in order
Put the program in order. It charges 0 under 5 years old, 50 under 18 and 100 for everyone else.
6. Complete the code
averagemust give back 0 when the list comes in empty. Complete the guard.7. Predict the output
What does this code print?
8. Find the bug
Shipping is free when the order goes past 500. It should print 0 99. Which line has the error?
9. Find the case that fails
first_word(t)should give back the first word of the text, and an empty text when there is none. Which call breaks it?10. Multiple choice
Both functions do the same thing. Which one reads better, and why?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.