python - 如何在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))
解决方案
两件事情。不要使用 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))
推荐阅读
- android - 在onCreate中使用getActivity时如何让onCreate在onCreateView之前加载?
- php - Woocommerce 自定义订单状态更改日期
- google-bigquery - BigQuery上比特币交易的最大时间戳?
- javascript - 使用 JavaScript 检测文件系统上的页面何时发生更改
- javascript - 从 Controller 获取数据到 Javascript 并将其传递到 Modal Codeigniter
- function - 为什么我的 Scheme Cube-Root 程序中出现此错误?
- r - 使用 R 从网站中提取表格数据
- python - 使用 scipy 时找不到模块
- jquery - Tooltipster 在为其动态生成内容时不会展开
- php - 你如何在html中格式化php?