Python - sum an array imported from a CSV file
Question: I am trying to sum up the values from a csv file after being placed into a
list, i want to add them all together. The list as it goes:

    
    
    '50', '51', '53', '55', '56', '56', '56', '61', '64', '67', '68', '71', '79', '81', '86', '86', '87', '94', '96', '98', '99' 'Score'
    

The code gets these values from the csv and places the vales into a list

    
    
    import csv
    
    f=open('IT_Programming_data.csv')
    
    csv_f = csv.reader(f)
    score = [] 
    for row in csv_f:"score"      
      score.append(row[1])
      a = score
      b = sum(a)
      print (b)
    f.close()
    

When i attempt to sum up the list i get the error:  

    
    
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

sum works when you do:  
  

    
    
    a = [1,3,4]
    
    b = sum(a)
    
    print (b)
    

Which returns '8'

How do i make it work with a list imported from the csv, i have no idea


Answer: You try to add a string and a number which will raise a ValueError, try this
code to deal with the Exception:

    
    
    import csv
    
    f = open('IT_Programming_data.csv')
    
    csv_f = csv.reader(f)
    score = [] 
    for row in csv_f:
      try:
        num = int(row[1].strip()) # try to switch type
        score.append(num)
      except Exception,error: # fail to switch, print error
        print(error)
    
    b = sum(score)
    print(b)
    
    f.close()
    

