Number helpers
- Python course
- Intermediate
- Lesson 15/116
- 6 min
Add number conversion and calculation methods.
The clamp method
We'll write a clamp method to keep a number within a range. clamp(n, lo, hi) returns lo if n is below lo; hi if above hi; otherwise n.
Example: clamp(15, 0, 10) → 10, because 15 is above 10. In Python we can write it in one line as max(lo, min(hi, n)). First min(hi, n) applies the upper bound, then max(lo, ...) applies the lower bound.
Bounding with max and min
min(a, b) returns the smaller, max(a, b) returns the larger. We build clamp from these: first min(hi, n) applies the upper bound, then max(lo, ...) applies the lower bound.
Example: clamp(15, 0, 10) = max(0, min(10, 15)) = max(0, 10) = 10. Read inside out. This form is shorter than if branches and still readable.
Practice Add clamp to Utility
Add a def clamp(self, n, lo, hi): method to the Utility class. In the body write return max(lo, min(hi, n)). Then create an instance with u = Utility() and call print(u.clamp(15, 0, 10)).
Starter code
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
u = Utility()
print(u.slugify("Hello World"))
# Add the clamp method and call it on an instanceSample solution
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
u = Utility()
print(u.clamp(15, 0, 10))Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the clamp parts
| Term | Meaning |
|---|---|
clamp |
Method name |
max(lo, min(hi, n)) |
Bounding |
15, 0, 10 |
Example input |
2 What does clamp(15, 0, 10) return?
- 5
- 15
- 10 Correct answer
- 0
Explanation: Since 15 is above 10, the upper bound 10 is returned.
3 Complete the clamp body
class Utility:
def clamp(self, n, lo, hi):
return max(lo, min(hi, ____))
class Utility:
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
Explanation: n is the original value; min applies the upper bound, max the lower.