-1

I'm really new at Python and programming in general. I'm supposed to add the first 7 numbers in the list

grades = [ '9', '7', '7', '10', '3', '9', '6', '6', '2' ]

so I wrote this code:

print("1.", grades[0] + grades [1] + grades [2] + grades [3] + grades [4] + grades[5] + grades[6] )

but it only prints out "97710396" which is the numbers just printed out as it was an index without spaces. How do I add them so I can get 51 to print out?

falsetru
  • 357,413
  • 63
  • 732
  • 636

7 Answers7

1

Without giving too much away... the "numbers" in your list are actually strings, and python allows you to add strings... by concatenating them together. So 'a' + 'b' + '9' gives you 'ab9'. You need to convert these strings into ints as int('19'), so int('9') + int('7') gives 16.

U2EF1
  • 12,907
  • 3
  • 35
  • 37
1

Convert everything to an integer, sum what you need, print it:

print("1.",sum(map(int, grades[:7])))
Dair
  • 15,910
  • 9
  • 62
  • 107
0

You need to convert strings to ints to do numeric operations (instead of string concatenations):

grades = ['9', '7', '7', '10', '3', '9', '6', '6', '2']
grades = [int(x) for x in grades]
print("1.", grades[0] + grades[1] + grades[2] + grades[3] +
            grades[4] + grades[5] + grades[6])

Or, using sum with list slice (useful if the items to add are continuous items)

grades = ['9', '7', '7', '10', '3', '9', '6', '6', '2']
grades = [int(x) for x in grades]
print("1.", sum(grades[:7]))
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

These are individual strings. You cannot do math on strings.

What happens when you do + on strings is called string concatenation.

ie. '1'+'2' will produce '12' and not '3'

You need to convert these to integers using int() in order to perform arithmetic.

var result = int('1') + int('2')
>> 3

So either

print("1.", int(grades[0]) + int(grades [1]) + int(grades [2]) + int(grades [3]) + int(grades [4]) + int(grades[5]) + int(grades[6]) )

or a snazzy list comprehension with list slicing and sum

grades = [int(x) for x in grades]
print("1.", sum(grades[:7]))
Community
  • 1
  • 1
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0
sum = 0
for i in range(0,7):
    sum += int(grades[i])
print(sum)
Magnilex
  • 11,584
  • 9
  • 62
  • 84
Loupi
  • 550
  • 6
  • 14
0

The list grades[] contains string variables. Integers are whole numbers. You need to change the values in the grades[] list to integers. To do that, you need to remove the quotes around the values in grades[]. Then it will output the sum of all the numbers in that list. Hope this helps.

Daniel Lewis
  • 88
  • 2
  • 9
-1

You can use reduce with lambda for this ,

>>> print( "1.",reduce(lambda x,y:int(x)+int(y),grades[:7]))

As you tagged this question with python 3.x the reduce is now part of functools module.

import functools
print( "1.",functools.reduce(lambda x,y:int(x)+int(y),grades[:7]))
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81