【问题标题】:How can i calculate the sum of the grades in the marks list with for loop如何使用for循环计算标记列表中的成绩总和
【发布时间】:2021-12-30 13:50:07
【问题描述】:
marks=[3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

d=len(marks)

s=0

for s in range(d):
    f=42/d
    print("The final grade:" + str(f))

【问题讨论】:

  • 您在寻找sum(marks)吗?
  • 基本上我想通过总分除以有多少来找到最终成绩
  • 神奇的42从何而来? (列表中的总和实际上是 44,但是如果你必须把这个数字放在代码中,代码不会做任何有用的事情......)
  • 对不起,我的意思是 44。也是,它可以工作,但如果你有不和谐或某事,你可以把你的标签发给我,以便给你发送确切的练习

标签: python list loops for-loop


【解决方案1】:

对您的代码的一些评论:

marks = [3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

# this is OK, but you can just use len(marks), unless you want to save the value
d = len(marks)

# you initialise s, but that's not needed if you plan to use it as a loop variable
s=0

# you make s loop over the length of marks, but you can just loop over marks
for s in range(d):
    # this number appears out of nowhere, and you're dividing 42 by the length?
    f=42/d
    print("The final grade:" + str(f))

你追求的是:

marks = [3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

number_of_marks = len(marks)

total = 0
for mark in marks:
    total += mark

result = total / number_of_marks 
print("The final grade:" + str(result))

但有一种更简单的方法:

marks = [3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

result = sum(marks) / len(marks)
print("The final grade:" + str(result))

【讨论】:

  • 1) 使用 len() 函数。将标记数保存在单独的变量中。 2)您可以在 for 循环中添加标记。 - 在循环之前,设置 sum 变量。最初为 0。 - 在求和的循环中,添加每个标记。 3)要获得最终成绩,将总分除以有多少。然后输入你得到的号码。 (这是确切的问题)顺便说一句,感谢您的时间和帮助我,我是编程新手,我尽力不做愚蠢的事情
  • 确保你理解你写的每一段代码(或者至少你认为你理解),不要写代码希望它能起作用——你可以这样做来获得理解,但不要'在您认为自己真正理解并且不会“做愚蠢的事情”之前,请继续前进;-)。通过这些作业,你经常被要求做一些事情,目的是让你理解一些东西,或者使用你在以后的作业中创建的任何东西,而不是因为这是最好的方法——所以你在 StackOverflow 上得到的答案可能不会成为被要求的东西。
  • 你是一个伟大的人,感谢你的时间,并继续帮助人们感谢你的时间(:
  • 很高兴为您提供帮助,请勾选您接受的答案旁边的复选标记,这样您的问题将不再显示为未回答。
  • 这到底是哪里?
【解决方案2】:

试试这个:

marks=[3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

ms = 0

for s in marks:
    ms+=s

f = ms/len(marks)

print("The final grade:" + str(f))

【讨论】:

    【解决方案3】:

    试试这个: 标记=[3, 5, 4, 2, 5, 5, 3, 5, 4, 4, 4]

    毫秒 = 0

    对于标记中的 s: ms+=s

    f = ms/len(标记)

    print("期末成绩:" + str(f))

    print
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多