Python Tutorials

Python Programs

Python Find the Factors of a Number


Python Find the Factors of a Number

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.


What are Factors

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.


Syntax

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


Finding the factors of a number

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,

  1. Define a function named find_factors that takes one parameter n.
  2. Initialize an empty list to store the factors.
  3. Use a for loop to iterate from 1 to n (inclusive).
  4. In each iteration, check if n is divisible by the current number i. If true, append i to the list of factors.
  5. Return the list of factors.
  6. Call the function with a sample number and print the result.

Python Program

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)

Output

Factors of 12 are: [1, 2, 3, 4, 6, 12]