Python Practice › Loop Programs › Program 29
Factors of a number
Write a Python program to find all the factors of a number.
Input
36
Output
[1, 2, 3, 4, 6, 9, 12, 18, 36]
Approach
- Test every number from 1 to n; keep those that divide n exactly.
Solution
n = 36factors = []for d in range(1, n + 1): if n % d == 0: factors.append(d)print(factors)Output
[1, 2, 3, 4, 6, 9, 12, 18, 36]
Line by line
Line 4
n % d == 0 means d is a factor.
Learn the concept
New to this topic? Read the lesson, then come back.