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

Python computing and outputting all divisors of a number

Python computing and outputting all divisors of a number

Document Object Reference Manual Python3 Examples

Description: we will write a Python program to compute and output all divisors of a given number. A divisor is an integer that divides the number evenly with no remainder.

Example

def

find_factors

(

num

)

:

    factors

=

[

]

   

for

i

in

range

(

1

,

num +

1

)

:

       

if

num % i

==

0

:

            factors.

append

(

i

)

   

return

factors

number

=

int

(

input

(

"Please enter a number: "

)

)

print

(

f

"{number}'s factors are: {find_factors(number)}"

)

Code analysis:

  1. find_factors The function takes an integer num as its argument.
  2. Initialize an empty list factors to store all the factors.
  3. Use for Loop from 1 to num for iteration.
  4. In each iteration, check num whether it is divisible by the current i divisor (i.e., num % i == 0)。
  5. if the condition is met, add i to factors list.
  6. Finally, return factors the list.
  7. The user inputs a number, and the program calls find_factors function and outputs the result.

Output result:

请输入一个数字: 28
28 的所有因数是: [1, 2, 4, 7, 14, 28]

Document Object Reference Manual Python3 Examples