Reputation: 31
I'm learning python and was working on this question and can't seem to get it to work. When this code is executed I get the numbers 1 thru 8 on separate lines. How can I to just print the count of 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
Upvotes: 1
Views: 89
Reputation: 1535
honor_count = student_grades.count("A") + student_grades.count("B")
OR
honor_count = sum([student_grades.count(grade) for grade in "AB"])
Upvotes: 0
Reputation: 553
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
Upvotes: 0
Reputation: 1124388
Move the print
statement to the left, two indentation levels:
for grade in student_grades:
if grade in "AB":
honor_roll_count = honor_roll_count + 1
print honor_roll_count
Now it'll be executed after the loop has completed, instead of for every iteration of the loop.
Upvotes: 2
Reputation: 95335
Your print
is indented, which means it's inside the if
inside the for
loop, so it happens for every "A" or "B". You want it after the loop.
for grade in student_grades:
if grade in "AB":
honor_roll_count = honor_roll_count + 1
print honor_roll_count
Upvotes: 2