Python Math: Clamps number within the inclusive range
87. Number Capper
Write a Python program to cap a number within the inclusive range specified by the given boundary values x and y.
- If num falls within the range (a, b), return num.
- Otherwise, return the nearest number in the range.
Sample Solution:
Python Code:
def clamp_number(num, a, b):
return max(min(num, max(a, b)), min(a, b))
print(clamp_number(2, 4, 7))
print(clamp_number(1, -1, -4))
print(clamp_number(22, -10, 10))
print(clamp_number(20, 1, 10))
print(clamp_number(5, 1, 20))
print(clamp_number(1, 10, 20))
Sample Output:
4 -1 10 10 5 10
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to cap a number within a given range by returning the lower bound if it is less than the minimum or the upper bound if it exceeds the maximum.
- Write a Python function that accepts a number and two boundary values and returns the number capped to that range, then test it with multiple examples.
- Write a Python script to process a list of numbers and apply capping based on given minimum and maximum values, then print the resulting list.
- Write a Python program to prompt the user for a number and boundaries, cap the number accordingly, and print the result using conditional expressions.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to calculate the Hamming distance between two given values.
Next: Write a Python program to check whether a given number is a Disarium number or unhappy number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.