Python Calculate and Output All Divisors of a Number
Description: We will write a Python program to calculate and output all divisors of a given number. A divisor is an integer that can divide the number without a 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"All factors of {number} are: {find_factors(number)}")
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"All factors of {number} are: {find_factors(number)}")
Code analysis:
find_factorsThe function accepts an integernumas a parameter.- Initialize an empty list
factorsto store all the factors. - Use
forloop from 1 tonumto iterate. - In each iteration, check
numwhether it can be divided by the currentiwithout a remainder (i.e.,num % i == 0)。 - If the condition is satisfied, add
ito thefactorslist. - Finally return
factorsthe list. - The user inputs a number, the program calls
find_factorsthe function and outputs the result.
Output result:
请输入一个数字: 28 28 的所有因数是: [1, 2, 4, 7, 14, 28]Other extensions
Python3 Examples