Write a Python Function to Check Whether a Number is in a Given Range

Hi, Welcome to my blog. In this article you will learn about a python program to check if a number is within a range or not.

Lets use the special type of comparison supported only by python programming language, it is not supported by any other programming languages.

 

Write a Python Function to Check Whether a Number is in a Given Range

 

Write a Python Function to Check Whether a Number is in a Given Range

Define a function check_range() and pass the given number, starting range and ending range as input arguments to the python function.

Use the if statement to check if start is less than number less than ending range, as shown below. If the statement is true then return the boolean value as true else return false.

def check_range(number, start, end):
   if start <= number <= end:
       return True
   return False





In the main program take a three variable n, starting_range and  ending_range, ask the user to enter the numbers from the user using input() function call.

n = int(input("Enter a Number : "))
starting_range = int(input("Enter a Starting Range : "))
ending_range = int(input("Enter a End Range : "))





Take a flag variable to store the boolean value after calling the function check_range() and pass the three input arguments to it.

Use the if statement to check if flag is true then print the number is in range else print the number is not in range.

flag = check_range(n, starting_range, ending_range)
if flag:
   print("Number is in Range")
else:
   print("Number is not in Range")




Python Code
==========================

def check_range(number, start, end):
   if start <= number <= end:
       return True
   return False


n = int(input("Enter a Number : "))
starting_range = int(input("Enter a Starting Range : "))
ending_range = int(input("Enter a End Range : "))

flag = check_range(n, starting_range, ending_range)
if flag:
   print("Number is in Range")
else:
   print("Number is not in Range")


 


Output
================
>python main.py
Enter a Number : 23
Enter a Starting Range : 1
Enter a End Range : 100
Number is in Range




Output
=================
>python main.py
Enter a Number : -12
Enter a Starting Range : 1
Enter a End Range : 100
Number is not in Range





Output
==============
>python main.py
Enter a Number : 1000
Enter a Starting Range : 100
Enter a End Range : 500
Number is not in Range





Conclusion
===================
Python supports special type of comparison that none of the programming languages supports. I had used the same comparison in the above example.

Execute the above python program after understanding it completely by providing the random integers as input.

Comment it down below if you have any queries related to above python program.

Post a Comment

0 Comments