Check if a number is divisible by a number in Python

In this tutorial, we will learn how to check if the number is divisible by a number in Python. With the basic knowledge of operators in Python, it is quite easy to check the divisibility.  Check: The conceptual understanding of operators in python
There are many ways to check the divisibility of a number by another number.
We can directly check for condition x%y==0 or we can define a function to perform division and return a boolean value. Defining a function is quite easy. Using a function to perform some specific task reduces code redundancy.

Lets Code

def divide(num1,num2):
return True if num1%num2==0 else False

here we have created a function that takes two arguments and performs a modulo operation on them. If the operation results in the complete division of numbers, the function returns True else False.

a,b=[int(i) for i in input().split()]
if divide(a,b):
      print(f"{b} divides {a}")
else:
      print("No complete division")

here, we have called the user-defined function divide() and passed two numbers taken from the user.  If the division is complete the function will return True else it will return False.

output:
4 2
2 divides 4
7 8
No complete division
42 6
6 divides 42

This is how our function works. We can also do this job by avoiding the creation of function.
Without Function:

a,b=[int(i) for i in input().split()]
if a%b==0:
     print(f"{b} divides {a}")
else:
     print("No complete division")
output:
4 2
2 divides 4
7 8
No complete division
42 6
6 divides 42

Example: Find all numbers from 1 to 100 divisible by 3

for i in range(1,101):
     if i%3==0:
          print(i,end=" ")
output:
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99

This is how we can easily find if a number divides a number in Python.

Also read: Python program to find perimeter of circle

Leave a Reply

Your email address will not be published. Required fields are marked *