Skip to content
Exercise · Functions · lesson 8 of 8

Exercise: clamp

Write a function clamp(x, low=0, high=100) that limits x to the range from low to high inclusive. If x is less than low, it returns low; if greater than high, it returns high; otherwise, x itself.

  • clamp(150) → 100
  • clamp(5, 10) → 10
  • clamp(42, high=40) → 40

Constraints: x, low and high are integers from -1000 to 1000, and low is not greater than high. The low and high arguments may be passed by position or by name.

Do not add extra imports unless the task says so explicitly.

clamp.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way