Python finding all factors of a number
In Python, we can write a simple program to find all factors of a number. A factor is an integer that divides 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
(
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 tofactorslist.return factorsReturn the list containing all factors.number = 12Set the number whose factors to find.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]
Python3 Examples