首页 > 解决方案 > 如何在python中返回可与某些数字整除的数字的加法?

问题描述

因此,我正在创建一个函数,该函数应返回所有小于等于 x 且可被 4 或 5 整除的数字的加法,但不应同时添加可被两者整除的数字。到目前为止,我已经能够编写能够将数字 4 和 5 整除并返回的函数。但是,我无法编写添加可被两者整除的数字的能力。下图应该显示我希望 python 输出的内容。

在此处输入图像描述

到目前为止,这是我所做工作的代码:

def personal_numbers(num):
    #variable to store the sum
    sum=0
    #running loop through the range
    #if a number is divisible by i 
    for i in range(1000):
        if (i%4==0 and i%5==0):
            sum+=i
        return sum
print(personal_numbers(12))

标签: pythonfor-loopmath

解决方案


两件事情。不要使用 sum 作为变量,Nonetype使用时会得到sum([x,y]). 最后,你的 for 循环中有一个 return。这将在第一次迭代时停止程序。

def personal_numbers(num):
    #variable to store the sum
    sum=0
    #running loop through the range
    #if a number is divisible by i 
    for i in range(1000):
        if (i%4==0 and i%5==0):
            sum+=i
    return sum
print(personal_numbers(12))

推荐阅读