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.
ADVERTISEMENT

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.