简体   繁体   English

一个简单的python项目,总和和平均值

[英]A simple python project with sum and average

I use python 3 and I have to make a program that creates all the multiples of 5 to 100,then print them as well as their average.I have tried this but... 我使用python 3,我必须创建一个程序,创建5到100的所有倍数,然后打印它们以及它们的平均值。我试过这个但是......

for i in range(0, 101):
    if i % 5 == 0:
        x = 0
        x += 1
        y = sum(i)
        z = y/x 
        print(i)
        print(z)

When I try this i get : 当我尝试这个时,我得到:

 Traceback (most recent call last):
  File "C:/Users/Chriskaf/Desktop/(3)count.py", line 5, in <module>
    y = sum(i)
TypeError: 'int' object is not iterable

Thanks for you time :) 谢谢你的时间:)

A possible solution would be to create a list where you save all values. 一种可能的解决方案是创建一个保存所有值的列表。 Then apply the sum and average : 然后应用sumaverage

total = []
for i in range(0, 101):
    if i % 5 == 0:
        total.append(i)

total_sum = sum(total)
total_average = sum(total)/len(total)

try this: 尝试这个:

counter = 0

sum_numbers = 0

for number in range(1,101):

    if number % 5 ==0:

        counter += 1

        sum_numbers += number

        avg = sum_numbers / float(counter)

        print (number, avg)

Output: 输出:

(5, 5.0)
(10, 7.5)
(15, 10.0)
(20, 12.5)
(25, 15.0)
(30, 17.5)
(35, 20.0)
(40, 22.5)
(45, 25.0)
(50, 27.5)
(55, 30.0)
(60, 32.5)
(65, 35.0)
(70, 37.5)
(75, 40.0)
(80, 42.5)
(85, 45.0)
(90, 47.5)
(95, 50.0)
(100, 52.5)

Your code had a couple of issues. 您的代码有几个问题。

  • the x counter was reset on every iteration (it was always set to 0, and after that to 1) x计数器在每次迭代时都被重置(它总是设置为0,之后设置为1)
  • missuse of sum (error code here) - you cant sum a single digit (which is what i is) - the sum function description is: sum(sequence[, start]) -> value Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). 错误使用sum (这里是错误代码) - 你不能sum一个数字(这就是i的意思) - 和函数描述是: sum(sequence [,start]) - > value返回一个数字序列的总和(NOT字符串)加上参数'start'的值(默认为0)。 When the sequence is empty, return start. 当序列为空时,返回start。
  • you are dividing y by an int (would result in nearest round int, I believe you want float results) 你把y除以一个int (会导致最接近的圆int,我相信你想浮动结果)

Hope that helps! 希望有所帮助!

Even better, use the "step" parameter of range to get exactly the numbers you want. 更妙的是,使用的范围 “台阶”参数,达到您想要的号码。 Also, don't re-compute the sum. 另外,不要重新计算总和。

total = [i for i in range(5, 101, 5)]
total_sum = sum(total)
total average = total_sum / len(total)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM