Python Calculate and Output All Divisors of a Number

Document 对象参考手册Python3 Examples

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)}")

Code analysis:

  1. find_factorsThe function accepts an integernumas a parameter.
  2. Initialize an empty listfactorsto store all the factors.
  3. Useforloop from 1 tonumto iterate.
  4. In each iteration, checknumwhether it can be divided by the currentiwithout a remainder (i.e.,num % i == 0)。
  5. If the condition is satisfied, addito thefactorslist.
  6. Finally returnfactorsthe list.
  7. The user inputs a number, the program callsfind_factorsthe function and outputs the result.

Output result:

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

Document 对象参考手册Python3 Examples

Other extensions