python - 试图获得总和,但似乎没有用

标签 python for-loop

我正在学习 python 并正在研究这个问题,但似乎无法让它发挥作用。执行此代码时,我在不同的行上得到数字 1 到 8。我怎样才能只打印 8 的计数?

honor_roll_count = 0
student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]
for grade in student_grades:
    if grade in "AB":
        honor_roll_count = honor_roll_count + 1
        print honor_roll_count

最佳答案

您的 print 是缩进的,这意味着它在 for 循环内的 if 内,因此它发生在每个“A”或“乙”。你想要在循环之后得到它。

for grade in student_grades:
    if grade in "AB":
        honor_roll_count = honor_roll_count + 1
print honor_roll_count

关于python - 试图获得总和,但似乎没有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243337/

相关文章:

linux - 语法错误 : operand expected when using Bash

python - gtk:设置事件窗口

python - 由于 GNU Radio block 的快速输入流而导致绘图卡住

python - 如何使用 pandas 从 GitHub 读取 CSV 文件

python - Python 中的点符号。方法应该在对象之前还是之后?

javascript - 在 for 循环中创建 .on() 元素时,如何使 .on(function) 调用当前索引?

c++ - 使用 Opencv C++ 对循环进行矢量化

python - 使用selenium解析网页时的表单、输入问题

python - 在 python 中循环一个未命名的字典

python - 在Python中循环和计算json响应