Table of Contents

**Problem Formulation**

You have been given a number. How will you check if the number lies between two numbers?

When you check if a number lies between two other numbers it returns a boolean that determines if the number is greater than or equal to the minimum number and also less than or equal to the maximum number. Here’s an example that demonstrates the problem:

Example 1: Is 25 between 15 and 35? Output: TrueExample 2:Is 0.5 between 1 and 5? Output: FalseExample 3:Is 10 between 10 and 20? Output: True |

That explains the given problem. We will have a look at few other conditions and examples. But before we discuss complex scenarios, let us dive into the solutions to the given question.

**Method 1: Use Comparison Operators**

Python comparison operators can compare numerical values such as integers and floats in Python. The operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).

Thus, you can use the <= and the >= operators to check if a number lies between the upper limit (maximum number) and lower limit(minimum number).

**Code:**

print(15 <= 25 < 35) # True print(1 <= 0.5 < 5) # False print(10 <= 10 < 20) # True

**Method 2: Using “and” Keyword with Comparison Operators**

The second way of checking whether a value lies between two other values is quite similar to the one used above. The only difference, in this case, is to use the *and *keyword in between the two comparison operators as shown in the solution below.

print(15 <= 25 and 25 <= 35) # True print(1 <= 0.5 and 0.5 <= 5) # False print(10 <= 10 and 10 <= 20) # True

Some of you might be thinking why use an extra keyword when the solution given before is more readable than this one! Well! That’s true. The first syntax is more readable but this solution runs faster. Let’s compare the two solutions using **timeit**.

~$ python3 -m timeit "10 <= 20 and 20 <= 30" 10000000 loops, best of 3: 0.0366 usec per loop ~$ python3 -m timeit "10 <= 20 <= 30" 10000000 loops, best of 3: 0.0396 usec per loop

**Method 3: Using “in” Keyword with range() Function**

You can use the `range()`

function to determine the upper and lower limits/numbers by feeding in the start and stop values within it. Now, to check if the number lies between the two numbers you can simply use the **in** keyword to check it. So, if the number lies in the specified range then the output will be “*True*” else “*False*“.

**Code: **

print(25 in range(15, 36)) # True print(0.5 in range(0, 2)) # False print(10 in range(10, 20)) # True

Note that the stop value within the `range()`

function should always be one greater than the given maximum number/upper limit since the range of values taken into account by the `range`

function always lies between start to stop-1. Read more about the `range()`

function here: **Python range() Function â A Helpful Illustrated Guide**

**TIDBIT:**

Pythonâs â`in`

â operator is a reservedÂ keywordÂ to test membership of the left operand in the collection defined as the right operand. For example, the expressionÂ `x in my_list checks`

Â if objectÂ `x`

Â exists in theÂ `my_list`

Â collection, so that at least one elementÂ `y`

Â exists inÂ `my_list`

Â for thatÂ `x == y`

Â holds. You can check membership using the â`in`

â operator in collections such asÂ lists,Â sets,Â strings, andÂ tuples.

**Exercises**

Before we wrap up our discussion, let’s discuss some other variations of the given problem to further stregthen our grip on the concept.

**Challenge 1:** How will you check if an alphabet lies between two other alphabets or not based on the alphabetical order of English language?

**Example: **When you check if the alphabet “Y” lies between “X” and “Z” or not, the output should be “True”.

**Solution: **

Python comparison operators can also compare strings in Python. The comparison ordering is given by theÂ `ord()`

Â function that returns the Unicode integer for a given characterÂ `c`

. The operators that can be used are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).

We will be using the < and > operators to solve the programming challenge.

print("X" < "Y" < "Z") # True # In case you want to ignore the case (make the letters case-insensitive) print("x".upper() < "Y".upper() < "z".upper()) # True

**Challenge 2: **Consider a real-time scenario where you have to allocate a specific grade to a student based on the marks obtained by him/her. Hereâs the grade allocation table that determines the range of marks that correspond to a certain grade:

Marks | Grade |

91-100 | A+ |

81-90 | A |

71-80 | B |

61-70 | C |

40-60 | D |

0-39 | Fail |

How will you use the above grading system and allocate the appropriate grade to a student based on the marks received? Letâs have a quick look at three examples that explain the desired goal of the given problem.Â

Input: marks = 90Output: âGrade AâInput: marks = 55Output: âGrade DâInput: marks = 10Output: âFailâ |

**Question: **Can you formulate a one-liner code snippet that solves the programming challenge?

**Solution:**

marks = 95 # One-liner grade = 'Grade: A+' if marks > 90 else 'Grade: A' if marks > 80 else 'Grade: B' if marks > 70 else 'Grade: C' if marks > 60 else 'Grade = D' if marks > 39 else 'Fail' # Result print(grade) # Grade: A+

This solution is a classic example of using a nested ternary operator. Letâs examine the one-liner to understand how it works.

If the value of marks is greater than 90, we print ‘Grade: A+’ on the shell. Otherwise, the remainder of the code gets executed, which represents a ternary operator by itself. The next condition gets evaluated and if the value of marks is greater than 80, we print ‘Grade: A’ on the shell. This is how each condition gets evaluated until a certain condition is **True. **Thus, if the value of marks is less than 80, then the next condition gets evaluated. Hence, if the value of marks is greater than 70, we print ‘Grade: B’ on the shell. Otherwise, the next condition is executed. If the value is greater than 60, we print ‘Grade: C’ on the shell. Otherwise, we move on to the next condition and if the value of marks is greater than 39, we print ‘Grade: D’ on the shell. Otherwise, the final else block is evaluated and we print ‘Grade: D’ on the shell.

**Challenge 3: **Examine the snippet given below and guess the output:

num1 = float('Inf') num2 = float('-Inf') print(num1 <= float('Inf') <= num2)

**Answer: **You cannot compare two Positive Infinite values with each other. Similarly, you cannot compare two Negative Infinite values with each other. Hence, the output will be **False**.

Read More: **Python Infinity **

**Conclusion**

I hope this article answers all your queries. Please **subscribe** and stay tuned for more interesting discussions. Meanwhile, you may want to have a look at this comprehensive guide to comparison operators in Python: **Python Comparison Operators [Blog + Videos]**.

Happy coding! đ