Joseph Burrows Joseph Burrows - 1 year ago 217
Python Question

Python Iterating over a list


with the total extra credit received given list
. Full credit is 100, so anything over 100 is extra credit. For the given program,
is 8 because 1 + 0 + 7 + 0 is 8. Sample output for the given program:
Sum extra: 8

Forgive me I am a starter on coding and really bad at it!
And this is my code (that is not working) Please help!:

test_grades = [101, 83, 107, 90]

sum_extra = -999 # Initialize 0 before your loop

while test_grades > 100:
test_grades = test_grades - 100
sum_extra = test_grades[0:3]

for test_grades[0:3] > 100:
test_grades = test_grades - 100
sum_extra= test_grade[0] + test_grades[1] + test_grades[2] + test_grades[3]

print('Sum extra:', sum_extra)

Which of my two loops would be better for this question and how can i edit them so that they become better? Because i can tell they are not going to work! any help is wanted! thank you! :)

Answer Source

Your first loop will fail because test_grades is of type list, so it would not make sense to say while list < 100.

an alternative while loop would look like:

i = 0;
while i < len(test_grades):
   if test_grades[i] > 100:
      test_grades[i] -= 100
      test_grades[i] = 0
print sum(test_grades)

Your second loop once again will fail because test_grades[0:3] is once again of type list, and you cannot have for list < 100. See L. M's answer for an alternative.

A for loop would be better for this type of question because you are iterating over elements, there is no real 'condition' to check, which would make a while loop better stylistically (they result in the same output).

A 'pythonic' approach would be to use a list comprehension:

test_grades = [101, 83, 107, 90]
extra_grades = [grade - 100 for grade in test_grades]
print sum(filter(lambda x: x > 0, extra_grades)) #prints 8
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download