The sum of scores not adding up

My initial code looks like the below but that only prints the last grade:

def grade_sum(scores):
  total = 0
  for s in scores:
    total =+ s
  return total

print grade_sum(grades)

However, if I change it to below it does add up, I thought =+ should add the total and the next value together? I think I had this issue understanding in an earlier section so thought I’d investigate now.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
  total = 0
  for s in scores:
    total = total + s
  return total

print grades_sum(grades)

Hi @fire_munki,

In your first code example, you have:

    total =+ s

It should be:

    total += s

For gods sake!

Thank you, dyslexia strike again. Maybe writing it out long hand is a suitable method for overcoming it!

1 Like

Do you know why what you had in your first example produced that result?

Not really, I’m sure it’s something simple.

=+ is not a single valid token or symbol in Python. It parses as two valid tokens, namely, = and +. Here, = is an assignment operator, and + serves as a unary positive operator. Python interprets your statement as:

    total = +s

In the above, we are assigning +s to total. Applying a unary positive operator to an int or a float results in the same value as that of the operand. Accordingly, the above is equivalent to the following assignment statement:

    total = s

In your first code example, that assignment executes during each iteration of the loop, which replaces the previous value of total with the current value of s. During the final iteration of the loop, the value of the last item in the scores list is what is assigned to total, and that is the value that gets returned by the function.

Edited on September 2, 2019 to identify + as a unary positive operator in this context