Python Find All Factors of a Number
In Python, we can write a simple program to find all factors of a number. Factors are integers that can divide the number evenly. For example, the factors of 6 are 1, 2, 3, 6.
Example
def find_factors(n):
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
number = 12
print(f"Factors of {number} are: {find_factors(number)}")
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
number = 12
print(f"Factors of {number} are: {find_factors(number)}")
Code analysis:
find_factors(n)Is a function used to find and return all factors of a number.factors = []Initialize an empty list to store the found factors.for i in range(1, n + 1)Loop from 1 to n, checking whether each number is a factor of n.if n % i == 0Check whether i is a factor of n; if so, add it tofactorsthe list.return factorsReturn the list containing all factors.number = 12Set the number for which to find factors.print(f"Factors of {number} are: {find_factors(number)}")Print all factors of 12.
Output result:
Factors of 12 are: [1, 2, 3, 4, 6, 12]Other extensions
Python3 Examples