用于查找一个数的因数的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


源代码

# Python Program to find the factors of a number

# This function computes the factor of the argument passed
def print_factors(x):
   print("The factors of",x,"are:")
   for i in range(1, x + 1):
       if x % i == 0:
           print(i)

num = 320

print_factors(num)

输出

The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

注意:要查找另一个数的因数,请更改 num 的值。

在这个程序中,要查找因数的数存储在 num 中,然后将其传递给 print_factors() 函数。该值在 print_factors() 中赋值给变量 x

在函数中,我们使用 for 循环从 i 等于 x 开始迭代。如果 x 能被 i 整除,则 ix 的一个因数。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战