Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Check if a number lies within a given range - Python Program

Example 1 :

n = int(input("Enter a number: ")) if 10 <= n <= 100: print("Within range") else: print("Out of range")

Output

 
OUTPUT  :
Enter a number: 12
Within range

Example 2 :

def check_number_in_range(number, lower_bound, upper_bound): """ Checks if a given number lies within a specified inclusive range. Args: number: The number to check. lower_bound: The lower limit of the range (inclusive). upper_bound: The upper limit of the range (inclusive). Returns: True if the number is within the range, False otherwise. """ if lower_bound <= number <= upper_bound: return True else: return False # Example usage with output num_to_check = 7 range_start = 5 range_end = 10 if check_number_in_range(num_to_check, range_start, range_end): print(f"The number {num_to_check} is within the range [{range_start}, {range_end}].") else: print(f"The number {num_to_check} is outside the range [{range_start}, {range_end}].") num_to_check_2 = 3 if check_number_in_range(num_to_check_2, range_start, range_end): print(f"The number {num_to_check_2} is within the range [{range_start}, {range_end}].") else: print(f"The number {num_to_check_2} is outside the range [{range_start}, {range_end}].")

Output

 
OUTPUT  :
The number 7 is within the range [5, 10].
The number 3 is outside the range [5, 10]. 

Explanation

check_number_in_range(number, lower_bound, upper_bound) Function:

  • This function takes three arguments: number(the value to verify), lower_bound (the inclusive starting point of the range), and upper_bound (the inclusive ending point of the range).
  • It uses a chained comparison lower_bound <= number <= upper_boundto efficiently determine if the number is greater than or equal to the lower_bound AND less than or equal to the upper_bound.
  • It returns Trueif the condition is met (the number is within the range), and False

 

Example Usage:

  • Variables num_to_check, range_start, and range_endare defined to demonstrate the function's use.
  • The check_number_in_rangefunction is called with these variables.
  • An if-elsestatement prints a message indicating whether the num_to_check falls within the specified range based on the function's return value.
  • A second example with num_to_check_2further illustrates the functionality.