Imagine you take on user input like so:
"""Bounding input.""" n = input("Please enter some number: ") m = int(n) print("Here is the output:", m)
Here we have to cast
n into an integer because it’s considered a string when using
Let’s say you have this hypothetical problem where you need to bound the user input of a number between two values, say 10 and 0.
You could use branches of
else statements, but I want to introduce how you can do it in one line.
Here we can use the builtin
min() functions to enforce the value between two bound.
"""Bounding input.""" n = input("Please enter some number: ") UPPER = 10 LOWER = 0 m = max(min(int(n), UPPER), LOWER) print("Here is the output:", m)
Here, if the user enters a value above the highest bound, then the
min() function will enforce the value provided by
11 will be ignored for
10, which is what
UPPER is assigned too)
If the user enters a value below the lowest bound, then the
max() function will enforce the value provided by
A Practical Application
<label> Is it better with 1, 2 or 3: <select name="num"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </label>
let num = parseInt("4"); // Bad actor! const UPPER = 3; const LOWER = 1; num = Math.max(Math.min(num, UPPER), LOWER);