Lesson 8 of 10
Writing functions
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
def, return and parameters
Explanation
A function is a set of steps you give a name because you need them more than once: you define it once with def, then call it wherever you like. A function takes its inputs through parameters and hands back its result with return, and return ends the function immediately.
You can give a parameter a default value. If you define def clamp(value, low=0, high=100), you can call it as just clamp(150) and the other parameters take their defaults. To change one particular parameter, name it: clamp(150, high=120), without writing low and without memorizing the parameter order.
The most common function mistake is printing the result instead of returning it. It looks right on the screen, but x = clamp(150) makes x equal None, because every function without a return returns None. Remember: print shows the result to you, and return hands it to the code that called the function.
Your task
Write the function clamp(value, low=0, high=100) so it returns value kept between the two bounds, the way a volume level or a progress percentage is held between a minimum and a maximum: anything below low becomes low, anything above high becomes high, and anything in between comes back unchanged.
Checks
5 checks- Returns the value unchanged when it's between the bounds
- Anything below the lower bound becomes 0
- Anything above the upper bound becomes 100
- high can be passed by name
- low can be passed by name