试图获得总和,但似乎没有工作

时间:2013-08-14 22:24:00

标签: 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

4 个答案:

答案 0 :(得分:2)

您的print缩进,这意味着它位于if循环内的for内,因此每个“A”或“B”都会发生这种情况。循环后你想要它。

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

答案 1 :(得分:2)

print语句向左移动,两个缩进级别:

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

现在它将在循环完成后执行,而不是循环的每次迭代。

答案 2 :(得分:0)

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 += 1
print honor_roll_count

答案 3 :(得分:0)

honor_count = student_grades.count("A") + student_grades.count("B")

OR

honor_count = sum([student_grades.count(grade) for grade in "AB"])