How to Check If a Number Is Divisible by Another in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number is divisible by another number using Python. The lab focuses on understanding the concept of divisibility and applying the modulo operator (%) to determine if a number can be divided evenly by another, leaving no remainder.

You will create a Python script named divisibility.py that demonstrates how to use the modulo operator to check divisibility by 2, 3, and 5. By running the script, you will observe the output indicating whether the number 10 is divisible by each of these numbers. This hands-on experience will solidify your understanding of divisibility and the modulo operator in Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") subgraph Lab Skills python/numeric_types -.-> lab-559547{{"How to Check If a Number Is Divisible by Another in Python"}} python/conditional_statements -.-> lab-559547{{"How to Check If a Number Is Divisible by Another in Python"}} python/for_loops -.-> lab-559547{{"How to Check If a Number Is Divisible by Another in Python"}} python/catching_exceptions -.-> lab-559547{{"How to Check If a Number Is Divisible by Another in Python"}} end

Learn About Divisibility

In this step, you will learn about divisibility in mathematics and how it relates to programming. Divisibility is a fundamental concept that helps us understand if a number can be divided evenly by another number, leaving no remainder. This concept is crucial in various programming tasks, such as data validation, algorithm optimization, and more.

Let's start with a simple example. Consider the number 10. It is divisible by 2 because 10 divided by 2 equals 5, with no remainder. Similarly, 10 is divisible by 5 because 10 divided by 5 equals 2, with no remainder. However, 10 is not divisible by 3 because 10 divided by 3 equals 3 with a remainder of 1.

In Python, we can check for divisibility using the modulo operator (%). The modulo operator returns the remainder of a division. If the remainder is 0, it means the number is divisible.

To demonstrate this, let's create a Python script called divisibility.py in your ~/project directory using the VS Code editor.

## Create a script named divisibility.py
## Open VS Code editor and create a new file named divisibility.py in ~/project directory
## Add the following content to the file

number = 10

## Check if the number is divisible by 2
if number % 2 == 0:
    print(f"{number} is divisible by 2")
else:
    print(f"{number} is not divisible by 2")

## Check if the number is divisible by 3
if number % 3 == 0:
    print(f"{number} is divisible by 3")
else:
    print(f"{number} is not divisible by 3")

## Check if the number is divisible by 5
if number % 5 == 0:
    print(f"{number} is divisible by 5")
else:
    print(f"{number} is not divisible by 5")

Now, let's run the script using the Python interpreter. Open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the script:

python divisibility.py

You should see the following output:

10 is divisible by 2
10 is not divisible by 3
10 is divisible by 5

This output confirms that 10 is divisible by 2 and 5, but not by 3, as we discussed earlier.

Understanding divisibility and using the modulo operator are essential skills for any Python programmer. In the next steps, we will explore more advanced applications of these concepts.

Use Modulo Operator

In this step, we will dive deeper into the modulo operator (%) and explore its various applications in Python. As you learned in the previous step, the modulo operator returns the remainder of a division. This seemingly simple operation is incredibly versatile and can be used to solve a wide range of programming problems.

One common use case for the modulo operator is to determine if a number is even or odd. An even number is divisible by 2, while an odd number is not. We can easily check this using the modulo operator:

## Create a script named even_odd.py
## Open VS Code editor and create a new file named even_odd.py in ~/project directory
## Add the following content to the file

number = 17

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")

Save this code as even_odd.py in your ~/project directory. Now, let's run the script:

cd ~/project
python even_odd.py

You should see the following output:

17 is odd

Another useful application of the modulo operator is to cycle through a sequence of numbers. For example, suppose you want to assign different colors to a series of items, and you only have a limited number of colors. You can use the modulo operator to cycle through the colors:

## Create a script named colors.py
## Open VS Code editor and create a new file named colors.py in ~/project directory
## Add the following content to the file

items = ["apple", "banana", "cherry", "date", "elderberry"]
colors = ["red", "yellow", "purple"]

for i, item in enumerate(items):
    color_index = i % len(colors)
    color = colors[color_index]
    print(f"{item} is {color}")

Save this code as colors.py in your ~/project directory. Now, let's run the script:

cd ~/project
python colors.py

You should see the following output:

apple is red
banana is yellow
cherry is purple
date is red
elderberry is yellow

In this example, the modulo operator ensures that the color_index stays within the bounds of the colors list, allowing us to cycle through the colors repeatedly.

The modulo operator is also useful for tasks like validating input data, generating patterns, and implementing cryptographic algorithms. As you continue your Python journey, you will find many more creative ways to use this powerful operator.

Handle Division by Zero

In this step, you will learn how to handle division by zero errors in Python. Division by zero is a common error that occurs when you try to divide a number by zero. In mathematics, division by zero is undefined, and in programming, it typically results in an error that can crash your program.

Let's see what happens when we try to divide by zero in Python:

## Create a script named division_error.py
## Open VS Code editor and create a new file named division_error.py in ~/project directory
## Add the following content to the file

numerator = 10
denominator = 0

result = numerator / denominator

print(result)

Save this code as division_error.py in your ~/project directory. Now, let's run the script:

cd ~/project
python division_error.py

You should see an error message like this:

Traceback (most recent call last):
  File "/home/labex/project/division_error.py", line 4, in <module>
    result = numerator / denominator
ZeroDivisionError: division by zero

The ZeroDivisionError indicates that we have attempted to divide by zero. To prevent this error from crashing our program, we can use error handling techniques. One common approach is to use a try-except block:

## Create a script named safe_division.py
## Open VS Code editor and create a new file named safe_division.py in ~/project directory
## Add the following content to the file

numerator = 10
denominator = 0

try:
    result = numerator / denominator
    print(result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero")

Save this code as safe_division.py in your ~/project directory. Now, let's run the script:

cd ~/project
python safe_division.py

You should see the following output:

Error: Cannot divide by zero

In this example, the try block attempts to perform the division. If a ZeroDivisionError occurs, the except block is executed, which prints an error message instead of crashing the program.

Another approach is to check if the denominator is zero before performing the division:

## Create a script named check_division.py
## Open VS Code editor and create a new file named check_division.py in ~/project directory
## Add the following content to the file

numerator = 10
denominator = 0

if denominator == 0:
    print("Error: Cannot divide by zero")
else:
    result = numerator / denominator
    print(result)

Save this code as check_division.py in your ~/project directory. Now, let's run the script:

cd ~/project
python check_division.py

You should see the following output:

Error: Cannot divide by zero

Both of these approaches allow you to handle division by zero errors gracefully and prevent your program from crashing. Choose the approach that best suits your needs and coding style.

Summary

In this lab, you learned about the concept of divisibility in mathematics and its application in Python programming. You explored how to determine if a number is divisible by another number by checking if the remainder of their division is zero.

You utilized the modulo operator (%) in Python to find the remainder of a division and implemented conditional statements to print whether a number is divisible by 2, 3, and 5. You created and executed a Python script named divisibility.py to demonstrate this concept.