Python computing and outputting all divisors of a number
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: "
)
)
(
f
"{number}'s factors are: {find_factors(number)}"
)
Code analysis:
find_factorsThe function takes an integernumas its argument.- Initialize an empty list
factorsto store all the factors. - Use
forLoop from 1 tonumfor iteration. - In each iteration, check
numwhether it is divisible by the currentidivisor (i.e.,num % i == 0)。 - if the condition is met, add
itofactorslist. - Finally, return
factorsthe list. - The user inputs a number, and the program calls
find_factorsfunction and outputs the result.
Output result:
请输入一个数字: 28
28 的所有因数是: [1, 2, 4, 7, 14, 28]
Python3 Examples