Skip to main content
 首页 » 编程设计

python之如何在我的程序中获得除数之和

2025年05月04日9kerrycode

在我的程序中,它应该向用户询问一个数字,然后显示所有可能的除数,但最后,它必须显示所有除数的总和。我在最后一部分遇到了问题,希望得到一些帮助。

我的代码:

    prompt = int(input("Enter an interger: ")) 
 
print("The divisors of the integer you entered are: ") 
for i in range(1, prompt+1): 
    if(prompt%i==0): 
        print(i) 
        print(f") 

例如用户输入 20:

The divisors of the integer you entered are: 
 
1 
 
2 
 
4 
 
5 
 
10 
 
20 
 
The sum of the divisors is: 42 

请您参考如下方法:

只需简单修改您的代码即可达到目的。喜欢:

prompt = int(input("Enter an interger: ")) 
 
print("The divisors of the integer you entered are: ") 
divisor_sum = 0 #updated line 
for i in range(1, prompt+1): 
    if(prompt%i==0): 
        print(i) 
        divisor_sum+=i #calculate sum of all divisors 
 
print("The sum of divisors " + str(divisor_sum)) #print the sum of divisors 

你也可以使用list comprehension让你的程序更短更智能,比如:

prompt = int(input("Enter an interger: ")) 
 
divisors = [i for i in range(1,prompt+1) if prompt%i==0] 
divisor_sum = sum(divisors) 
 
print("The divisors of the integer you entered are: ") 
for i in divisors: 
    print(i) 
 
print("The sum of divisors " + str(divisor_sum))