How to Check If a Value Is Within a Range in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a value is within a specific numeric range in Python. This involves understanding and utilizing comparison operators such as <, >, <=, and >= to define numerical boundaries.

The lab guides you through creating a Python script, numeric_range.py, where you'll explore two methods: first, using comparison operators to check if a number falls within a range, and second, employing the range() function in conjunction with the in operator to achieve the same result. You'll execute the script and observe the output to confirm the functionality of both approaches.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} python/numeric_types -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} python/booleans -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} python/conditional_statements -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} python/for_loops -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} python/data_collections -.-> lab-559597{{"How to Check If a Value Is Within a Range in Python"}} end

Define a Numeric Range

In this step, you will learn how to define numeric ranges in Python. Understanding numeric ranges is crucial for various programming tasks, such as iterating through a sequence of numbers or creating conditional statements based on numerical boundaries. We'll explore two primary methods: using comparison operators and the range() function.

First, let's create a Python script named numeric_range.py in your ~/project directory using the VS Code editor.

## ~/project/numeric_range.py
number = 50

if number > 0 and number < 100:
    print("The number is within the range of 0 to 100")

In this script, we've defined a variable number and used comparison operators (>, <) to check if it falls within the range of 0 to 100.

Now, let's run the script using the following command in the terminal:

python ~/project/numeric_range.py

You should see the following output:

The number is within the range of 0 to 100

Next, let's modify the script to use the range() function. The range() function generates a sequence of numbers, which can be useful for defining a numeric range.

Modify the numeric_range.py script as follows:

## ~/project/numeric_range.py
number = 50

if number in range(0, 101):
    print("The number is within the range of 0 to 100")

In this modified script, we use the in operator along with the range() function to check if the number is within the range of 0 to 100 (inclusive). Note that range(0, 101) generates numbers from 0 up to (but not including) 101, effectively covering the range 0 to 100.

Run the script again:

python ~/project/numeric_range.py

You should see the same output as before:

The number is within the range of 0 to 100

This demonstrates how to define and check numeric ranges using both comparison operators and the range() function in Python.

Use Comparison Operators (<, >, <=, >=)

In this step, you will learn how to use comparison operators in Python. Comparison operators are essential for making decisions in your code based on the relationship between two values. We'll cover the following operators:

  • < (less than)
  • > (greater than)
  • <= (less than or equal to)
  • >= (greater than or equal to)

Let's create a new Python script named comparison_operators.py in your ~/project directory using the VS Code editor.

## ~/project/comparison_operators.py
age = 25

if age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

In this script, we've defined a variable age and used comparison operators to determine the person's age group.

Now, let's run the script using the following command in the terminal:

python ~/project/comparison_operators.py

You should see the following output:

You are an adult.

Let's modify the script to explore other comparison operators. Change the value of age to 70 and run the script again:

## ~/project/comparison_operators.py
age = 70

if age < 18:
    print("You are a minor.")
elif age >= 18 and age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")
python ~/project/comparison_operators.py

You should now see the following output:

You are a senior citizen.

Now, let's explore the <= and >= operators. Modify the script as follows:

## ~/project/comparison_operators.py
score = 85

if score >= 90:
    print("Excellent!")
elif score >= 80 and score < 90:
    print("Good job!")
else:
    print("Keep practicing.")
python ~/project/comparison_operators.py

You should see the following output:

Good job!

By experimenting with different values and operators, you can gain a solid understanding of how to use comparison operators to control the flow of your Python programs.

Utilize the range() Function

In this step, you will learn how to utilize the range() function in Python. The range() function is a powerful tool for generating sequences of numbers, which are commonly used in loops and other programming constructs.

The range() function can be used in several ways:

  • range(stop): Generates a sequence of numbers from 0 up to (but not including) stop.
  • range(start, stop): Generates a sequence of numbers from start up to (but not including) stop.
  • range(start, stop, step): Generates a sequence of numbers from start up to (but not including) stop, incrementing by step.

Let's create a new Python script named range_function.py in your ~/project directory using the VS Code editor.

## ~/project/range_function.py
for i in range(5):
    print(i)

In this script, we use the range(5) function to generate a sequence of numbers from 0 to 4. The for loop iterates through this sequence, printing each number.

Now, let's run the script using the following command in the terminal:

python ~/project/range_function.py

You should see the following output:

0
1
2
3
4

Next, let's modify the script to use the range(start, stop) form:

## ~/project/range_function.py
for i in range(2, 7):
    print(i)

In this modified script, we use range(2, 7) to generate a sequence of numbers from 2 to 6.

Run the script again:

python ~/project/range_function.py

You should see the following output:

2
3
4
5
6

Finally, let's explore the range(start, stop, step) form:

## ~/project/range_function.py
for i in range(0, 10, 2):
    print(i)

In this script, we use range(0, 10, 2) to generate a sequence of even numbers from 0 to 8.

Run the script:

python ~/project/range_function.py

You should see the following output:

0
2
4
6
8

By experimenting with different parameters, you can effectively use the range() function to generate various sequences of numbers for your Python programs.

Summary

In this lab, you learned how to check if a value is within a numeric range in Python. The lab covered defining a numeric range using comparison operators (>, <) and the range() function. You created a Python script to check if a number falls within a specified range (0 to 100) using both methods.

The lab demonstrated how to use comparison operators with and to define a range and how to use the in operator with the range() function to achieve the same result. The range() function generates a sequence of numbers, and the in operator checks if a value exists within that sequence.