In this tutorial, we will learn how to find the factors of a number in Python. We will cover the basic concept of factors and implement a function to find all factors of a given number.
Factors of a number are integers that can be multiplied together to produce the original number. For example, the factors of 12 are 1, 2, 3, 4, 6, and 12.
The syntax to find the factors of a number in Python is:
def find_factors(n):
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
We can create a function to find all factors of a given number by iterating through possible divisors and checking if they divide the number without a remainder.
For example,
find_factors
that takes one parameter n
.for
loop to iterate from 1 to n
(inclusive).n
is divisible by the current number i
. If true, append i
to the list of factors.def find_factors(n):
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
# Find the factors of 12
result = find_factors(12)
# Print the result
print('Factors of 12 are:', result)
Factors of 12 are: [1, 2, 3, 4, 6, 12]