Python代码 在线执行

Python 程序:查找数字的因数

/examples/factor-number

在此程序中,您将学习使用for循环查找数字的因数。

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


源代码

# 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可被x完全整除,则它是x的因数。