Python Practice › Function Programs › Program 8
Is a number in a range?
Write a Python function to check whether a number is within a range (inclusive).
Input
7 in 2 to 20; 25 in 2 to 20
Output
7 is in the range 25 is outside the range
Approach
- A chained comparison.
Solution
def in_range(n, low, high): return low <= n <= high for n in [7, 25]: print(n, "is in the range" if in_range(n, 2, 20) else "is outside the range")Output
7 is in the range 25 is outside the range
Learn the concept
New to this topic? Read the lesson, then come back.