Write a Python program to find all divisors of an integer or number using for loop.
Python Program to find all divisors of an integer using loops
In this example, the Python for loop iterate from 1 to a given number and check whether each number is perfectly divisible by number. If True, print that number as the divisor.
num = int(input("Please enter any integer to find divisors = "))
print("The Divisors of the Number = ")
for i in range(1, num + 1):
if num % i == 0:
print(i)

Some users may use n /2 as the for loop range maximum value. However, the number is also divisible by itself. So, the approach may be wrong. However, for long lists, we can append the actual number at the end.
n = 20
for i in range(1, int(n / 2) + 1):
if n % i == 0:
print(i, end = ' ')
1 2 4 5 10
To store all divisors of an integer in a list, we can follow this approach. Here, we declare an empty Python list. Inside the for loop’s if condition, we use append to add each divisor to the list.
n = 20
div = []
for i in range(1, n + 1):
if n % i == 0:
div.append(i)
print(div)
[1, 2, 4, 5, 10, 20]
Python Program to find all divisors of an integer using a while loop. Refer to the Python while loop.
num = int(input("Please enter any integer to find divisors = "))
i = 1
while(i <= num):
if num % i == 0:
print(i)
i = i + 1
Please enter any integer to find divisors = 100
1
2
4
5
10
20
25
50
100
In this Python example, we created a findDivisors function that will find and return all the divisors of the given number.
def findDivisors(num):
for i in range(1, num + 1):
if num % i == 0:
print(i)
# End of Function
num = int(input("Please enter any integer to find divisors = "))
findDivisors(num)
Please enter any integer to find divisors = 500
1
2
4
5
10
20
25
50
100
125
250
500
Find all divisors of a number using a list comprehension
The Python range function generates numbers from 1 to the given number. On each iteration, the modulo operator (%) in the if statement checks whether the number divided by 2 returns 0. If true, add it to the list.
n = 30
div = [i for i in range(1, n + 1) if n % i == 0]
print(div)
[1, 2, 3, 5, 6, 10, 15, 30]
Also Read