About Clamping/Clipping Values within Range

Using the max(min()) pattern you can ensure that a value is within a provided range:

def save_image(image, quality):
    # Valid JPEG quality range
    quality = max(1, min(100, quality))
    image.save(output, quality=quality)

Whichever quality value is provided to the function, the quality for the image will be no lower than 1 and no higher than 100.

Tips and Tricks Programming Python 3