求和与除法示例 (Python)
>>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
我如何使用循环自动进行求和和除法?
编辑:也许我不清楚 - 我想要一个循环继续求和(7的倍数,例如1-7、1-14、1-21等..)直到它达到x(x是用户输入)
好吧,弄清楚了:
def sum_and_div_of_multiples_of_7(x):
y = 7
while (y <= x):
mof7 = range(1,y)
print ('mof7 is', mof7)
total = sum(mof7)
print ('total =', total)
div = total/7
print ('div =', int(div), '\n')
y = y+7 # increase y
x = 70
sum_and_div_of_multiples_of_7(x)
>>> sum((1, 2, 3, 4, 5, 6, 7))
28
>>> 28/7
4.0
>>> sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14))
105
>>> 105/7
15.0
>>>
How do I automate this sum and division using a loop maybe?
Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 etc..) until it reaches x (x is the user input)
Okay, figured it out:
def sum_and_div_of_multiples_of_7(x):
y = 7
while (y <= x):
mof7 = range(1,y)
print ('mof7 is', mof7)
total = sum(mof7)
print ('total =', total)
div = total/7
print ('div =', int(div), '\n')
y = y+7 # increase y
x = 70
sum_and_div_of_multiples_of_7(x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
直接答案:
更有效的答案:
The direct answer:
The more efficient answer:
例子:
技巧很简单,你想对7的倍数求和,
要得到7的第i个倍数,只需
i*7
range
是一个Python函数来获取从 0 到 x 的数字列表sum
对列表求和。只需将这些部分组合在一起即可
Example:
The trick is very simple, you want to sum multiples of 7,
To get the ith multiple of 7, it's just
i*7
range
is a python function to get a list of numbers from 0 tox
sum
sums a list.Just put these pieces together
我不确定你想要什么,但也许是这样的:
I'm not sure what you want, but maybe it is something like:
我的版本:
My version:
如果我正确理解你的问题。您希望能够接受用户输入 - x,然后将值 1-7 相加,然后除以 7,如果 qoutient 高于 x 则停止,否则继续将 1-14 相加,除以 7 并检查该商- 并以7的倍数继续?
我的简单解决方案是
if i understand your problem correctly. You want to be able to accept user input - x, and then sum values 1-7 then devide by 7, if the qoutient is higher than x stop there, otherwise continue to sum up 1-14, devide by 7 and check that quotient - and continute in multiples of 7?
My easy sollution is