Python Find All Factors of a Number

Document 对象参考手册Python3 Examples

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)}")

Code analysis:

  1. find_factors(n)Is a function used to find and return all factors of a number.
  2. factors = []Initialize an empty list to store the found factors.
  3. for i in range(1, n + 1)Loop from 1 to n, checking whether each number is a factor of n.
  4. if n % i == 0Check whether i is a factor of n; if so, add it tofactorsthe list.
  5. return factorsReturn the list containing all factors.
  6. number = 12Set the number for which to find factors.
  7. 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]

Document 对象参考手册Python3 Examples

Other extensions