In Python, you can easily check if a number is between two numbers with an if statement, and the and logical operator.
def between_two_numbers(num,a,b):
if a < num and num < b:
return True
else:
return False
You can also use the Python range() function to check if a number is in a range between two numbers.
def between_two_numbers(num,a,b):
if b < a:
a, b = b, a
if num in range(a,b):
return True
else:
return False
When working with numbers in Python, the ability to easily check for certain conditions is very valuable.
One such situation is if you want to check if a number is in a range of numbers or is between two numbers.
In Python, you can easily check if a number is between two numbers with an if statement, and the and logical operator.
All you need to do is check if a number is greater than the lower bound of the range and less than the upper bound of the range. Then, you can use and to create a multiple condition if statement.
Below is a simple function which will check if a number is between two numbers using Python.
def between_two_numbers(num,a,b):
if a < num and num < b:
return True
else:
return False
print(between_two_numbers(10,5,15))
print(between_two_numbers(20,5,15))
#Output:
True
False
Using range() to Check if a Number is Between Two Numbers in Python
Another way to check if a number is between two numbers in Python is to use the Python range() function and check if the number is included in a created range.
To create a range, you can pass two numbers to range(). Then you can use the in logical operator to check if a number is in the created range.
Below is a simple function which will check if a number is in a range of numbers and between two numbers using Python.
def between_two_numbers(num,a,b):
if b < a:
a, b = b, a
if num in range(a,b):
return True
else:
return False
print(between_two_numbers(10,5,15))
print(between_two_numbers(20,5,15))
#Output:
True
False
Hopefully this article has been useful for you to learn how to