Skip to main content
 首页 » 编程设计

python之求负数因数的函数

2025年04月02日7itcoder

我需要编写一个函数来查找负数的因数并将它们输出到列表中。我该怎么做?我可以让我的函数做正数(见下文)但不能做负数。

#Finds factors for A and C 
def factorspos(x): 
    factorspos = [1,-6]; 
    print("The factors of",x,"are:") 
    for i in range(1, x + 1): 
        if x % i == 0: 
            factorspos.append(i) 
            print(i) 

我尝试更改循环计数的值,以便它从选择的数字计数到 1(下面的代码)但仍然没有产生任何结果:(

#Finds factors for A and C 
def factorspos(x): 
    factorspos = [int(-6),1]; 
    print("The factors of",x,"are:") 
    for i in range(int(-6), x + 1): 
        if x % i == 0: 
            factorspos.append(i) 
            print(i) 

我已将 Cco 更改为固定数字。

#Finds factors for A and C 
def factorspos(x): 
    Cco = -6 
    factorspos = [int(Cco),1]; 
    print("The factors of",x,"are:") 
    for i in range(int(Cco), x + 1): 
        if x % i == 0: 
            factorspos.append(i) 
            print(i) 
            return factorspos 

请您参考如下方法:

def factorspos(x): 
    x = int(x) 
    factorspos = [] 
    print("The factors of",x,"are:") 
    if x > 0: # if input is postive 
        for i in range(1,x+1): 
            if x % i == 0: 
                factorspos.append(i) 
                print(i) 
        return factorspos 
    elif x < 0: #if input is negative 
        for i in range(x,0): 
            if x % i == 0: 
                factorspos.append(i) 
                print(i) 
        return factorspos 
 
 
print(factorspos(12))   #outputs [1, 2, 3, 4, 6, 12] 
print(factorspos(-12))  #outputs [-12, -6, -4, -3, -2, -1] 

您实际上非常接近解决您的问题。我冒昧地为你所拥有的添加了一个额外的功能。基本上我添加了一个条件检查器来查看输入 x 是正数还是负数,该函数做了两件不同的事情。他们所做的是您提供的,但已清理。

注意事项 range() 从第一个数字(包括第一个数字)开始,到第二个参数少一个数字结束。 range(1,10) 会给你 1 到 9。这就是为什么如果你看,范围从 x 到 0 的负数部分,因为这会说 x 到 -1。在积极部分,它将从 1 变为 x+1,因为 +1 确保我们包含我们的输入。从那以后您知道的其余部分,以及您写的;如果没有,请随时提问。