Clamping Numbers Within Range

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In programming, it is often necessary to limit a number to a certain range. This is where the concept of clamping comes in. Clamping a number means restricting it to a certain range of values. In this challenge, you will be tasked with creating a function that clamps a number within a specified range.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13602{{"`Clamping Numbers Within Range`"}} python/tuples -.-> lab-13602{{"`Clamping Numbers Within Range`"}} python/function_definition -.-> lab-13602{{"`Clamping Numbers Within Range`"}} python/build_in_functions -.-> lab-13602{{"`Clamping Numbers Within Range`"}} end

Clamp Number

Write a function clamp_number(num, a, b) that takes in three parameters:

  • num (integer or float): the number to be clamped
  • a (integer or float): the lower boundary of the range
  • b (integer or float): the upper boundary of the range

The function should clamp num within the inclusive range specified by the boundary values. If num falls within the range (a, b), return num. Otherwise, return the nearest number in the range.

def clamp_number(num, a, b):
  return max(min(num, max(a, b)), min(a, b))
clamp_number(2, 3, 5) ## 3
clamp_number(1, -1, -5) ## -1

Summary

In this challenge, you have learned how to clamp a number within a specified range. This is a useful technique in programming, especially when dealing with user input or data that needs to be restricted to a certain range. Keep practicing and honing your skills to become a better programmer!

Other Python Tutorials you may like