How to Clamp an Integer in Python?

Estimated read time 1 min read

To clamp an integer in Python, you can use the min() and max() functions to limit the value within a specified range. Here’s an example of how to clamp an integer:

def clamp(number, min_value, max_value):
    return max(min(number, max_value), min_value)

# Example usage:
clamped_number = clamp(10, 0, 5)
print(clamped_number)  # Output: 5

clamped_number = clamp(-5, 0, 10)
print(clamped_number)  # Output: 0

clamped_number = clamp(7, 0, 10)
print(clamped_number)  # Output: 7

In the clamp() function, the max() function is used to ensure that the number does not exceed the maximum value. The min() function is used to ensure that the number is not less than the minimum value. By nesting these functions, you can restrict the number within the specified range.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply