1

我正在学习 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

4 回答 4

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
于 2013-08-14T22:26:29.223 回答
2

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

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

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

于 2013-08-14T22:26:57.160 回答
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
于 2013-08-14T22:29:08.530 回答
0
honor_count = student_grades.count("A") + student_grades.count("B")

或者

honor_count = sum([student_grades.count(grade) for grade in "AB"])
于 2016-04-01T09:43:15.227 回答