Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python finding all factors of a number

Python finding all factors of a number

Document Object Reference Manual Python3 Examples

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

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 == 0 Check whether i is a factor of n; if so, add it to factors list.
  5. return factors Return the list containing all factors.
  6. number = 12 Set the number whose factors to find.
  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 Object Reference Manual Python3 Examples