Check number in range python


Range PythonRange type PythonFor in rangeRange reverse python

While 10 <= number <= 20 works in Python, I find this notation using range() more readable:

if number in range(10, 21):
    print("number is between 10 (inclusive) and 21 (exclusive)")
else:
    print("outside of range!")

Keep in mind that the 2nd, upper bound parameter is not included in the range set as can be verified with:

>>> list(range(10, 21))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

However prefer the range() approach only if it's not running on some performance critical path. A single call is still fast enough for most requirements, but if run 10,000,000 times, we clearly notice nearly 3 times slower performance compared to a <= x < b:

> { time python3 -c "for i in range(10000000): x = 50 in range(1, 100)"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
1.848

> { time python3 -c "for i in range(10000000): x = 1 <= 50 < 100"; } 2>&1 | sed -n 's/^.*cpu \(.*\) total$/\1/p'
0.630

Python IF Number in Range

You can check if a number is present or not present in a Python range() object.

To check if given number is in a range, use Python if statement with in keyword as shown below.

if number in range(start, stop[, step]):
    statement(s)

number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

You can also check the other way around using not to the existing syntax.

if number not in range(start, stop[, step]):
    statement(s)

Now the expression: number not in range() returns True if the number is not present in the range, and False if number is present in the range.

Example 1 – If Number in range()

In this example, we will create a range object that represents some sequence of numbers, and check if a given number is present in the range or not.

Python Program

range_1 = range(2, 20, 3)
number = int(input('Enter a number : '))

if number in range_1 :
    print(number, 'is present in the range.')
else :
    print(number, 'is not present in the range.')

Output

D:\workspace\python> python example.py
Enter a number : 4
4 is not present in the range.
D:\workspace\python> python example.py
Enter a number : 5
5 is present in the range.
D:\workspace\python> python example.py
Enter a number : 11
11 is present in the range.
D:\workspace\python> python example.py
Enter a number : 12
12 is not present in the range.

Example 2 – If Number not in range()

You can also check if the number is not in range.

In this example, we will create a range object that represents some sequence of numbers, and check if a given number is not present in the range.

Python Program

range_1 = range(2, 20, 3)
number = int(input('Enter a number : '))

if number not in range_1 :
    print(number, 'is not present in the range.')
else :
    print(number, 'is present in the range.')

Output

D:\workspace\python> python example.py
Enter a number : 4
4 is not present in the range.
D:\workspace\python> python example.py
Enter a number : 5
5 is present in the range.
D:\workspace\python> python example.py
Enter a number : 11
11 is present in the range.
D:\workspace\python> python example.py
Enter a number : 12
12 is not present in the range.

Conclusion

Concluding this Python Tutorial, we learned how to check if a given number is present in the range() or not using if in range and if not in range expressions.

Last update on August 19 2022 21:51:39 (UTC/GMT +8 hours)

Python Functions: Exercise-6 with Solution

Write a Python function to check whether a number falls in a given range.

Sample Solution-1:

Python Code:

def test_range(n):
    if n in range(3,9):
        print( " %s is in the range"%str(n))
    else :
        print("The number is outside the given range.")
test_range(5)

Sample Output:

 5 is in the range
 

Pictorial presentation:

Flowchart:

Check number in range python

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Sample Solution-2:

  • Use arithmetic comparison to check if the given number is in the specified range.
  • If the second parameter, end, is not specified, the range is considered to be from 0 to start.

Python Code:

def test_range(n, start_num, end_num = 0):
  return start_num <= n <= end_num if end_num >= start_num else end_num <= n <= start_num
print(test_range(5, 2, 7))
print(test_range(5, 7))
print(test_range(1, 3, 6))
print(test_range(6, 5))

Sample Output:

True
True
False
False
 

Flowchart:

Check number in range python

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
Next: Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.

Python: Tips of the Day

Unzipping:

name = 'abcdef'
suffix = [1,2,3,4,5,6]
result = zip(name, suffix)
--> returns (a,1),(b,2),(c,3),(d,4),(e,5),(f,6)
unzipped = zip(*result)

How do you check if a number is in a range of numbers in Python?

You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

How do you check if a number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check if a number is between two values in Python?

Use the comparison operators to check if a number is between two numbers. Use the syntax minimum <= number <= maximum such that maximum is greater than minimum to return a boolean indicating whether number falls between minimum and maximum on a number line.

How do you find the range of a value in Python?

Steps to use range() function.
Pass start and stop values to range() For example, range(0, 6) . Here, start=0 and stop = 6 . ... .
Pass the step value to range() The step Specify the increment. ... .
Use for loop to access each number. Use for loop to iterate and access a sequence of numbers returned by a range() ..