Factors of a Number in Python Using While Loop

The factor of Number Definition

In math, a factor is a number that divides another number evenly, that is, with no remainder. Factors can be algebraic expressions as well, dividing another expression evenly. Factors of a number can be referred to as numbers or algebraic expressions that evenly divide a given number/expression. The factors of a number can either be positive or negative.

81÷9 = 9

Program to Print Factors of a Number in Python Using While Loop

num = int(input("Enter a number:"))
i = 1
while i <= num  :
   if (num  % i==0) :
        print("The factor of",num ,"are:",i)
   i = i + 1
Output:
Enter a number:15
The factor of 15 are: 1
The factor of 15 are: 3
The factor of 15 are: 5
The factor of 15 are: 15

Code Explanation: Factors of a Number in Python Using While Loop

Let’s understand this code now. In this program, we will use a while loop. Here we are taking user input for a number to get factorial and convert the same number into an int, and we will store this into a variable num. Now in the next line, define variable i and assign value 1; we use it as a counter.

In the next line, we have a while loop, and this loop will execute till i is less than or equal to num. Inside the while block, we will check if num is divisible by i which is the counter. If num is divisible by i, then i is a factor of num, and we will print the i with a message. Outside of the condition, we will write our increment of the counter.

About The Author