Python Program to find Factors of a Number

Write a Python Program to find Factors of a Number using While Loop, For Loop, and Functions with example.

Python Program to find Factors of a Number using While Loop

This Python program allows users to enter any integer value. Next, this Python program finds Factors of that number using a While Loop. Remember, Integers that are entirely divisible by a given integer (it means remainder = 0) called as factors.

number = int(input("Please Enter any Number: "))

value = 1
print("Factors of a Given Number {0} are:".format(number))

while (value <= number):
    if(number % value == 0):
        print("{0}".format(value))
    value = value + 1
Please Enter any Number: 4
Factors of a Given Number 4 are:
1
2
4

Within the Python while loop, there is an If statement to check whether Number divisible by value is exactly equal to 0 or not. If it is true, it prints that integer. Otherwise, it skips that integer and checks the next integer. Here, number= 4, value = 1

First Iteration
(value<= number) – It means (1 <= 4) is True
Now, Check the if condition
if (number%value == 0)  => (4 % 1 ==0) – This condition is TRUE. So, 1 printed

value= value+1 – means value become 2

Second Iteration
value= 2 and Number= 4 – It means (2 <= 4) is True
if(4 % 2 ==0) – This condition is TRUE. So, 2 printed

Third Iteration
value= 3 and Number= 4 – It means (3 <= 4) is True
if(3 % 2 ==0) – Condition is FLASE. So, 3 Skipped

Fourth Iteration
i = 4 and Number= 4 – It means (4 <= 4) is True
if(4 % 4 ==0) – Condition is TRUE. 4 printed

Next, value become 5 – It means condition (5 <= 4) is False. So, loop Terminated. The factors of a given 4 = 1, 2, 4.

Python Program to find Factors of a Number using For Loop

In these factors of a number program, we just replaced the While Loop with For Loop.

number = int(input("Please Enter any Number: "))

print("Factors of a Given Number {0} are:".format(number))

for value in range(1, number + 1):
    if(number%value == 0):
        print("{0}".format(value))
Python Program to find Factors of a Number 2

Python Program to find Factors of a Number using Functions

This Python factors of a number program is the same as the above example. But in this Python program, we separated the factors logic by defining a new function called Find_factors.

def Find_Factors(number):
    for value in range(1, number + 1):
        if(number % value == 0):
            print("{0}".format(value))

num = int(input("Please Enter any Number: "))

print("Factors of a Given Number {0} are:".format(num))
Find_Factors(num)
Please Enter any Number: 222
Factors of a Given Number 222 are:
1
2
3
6
37
74
111
222