ValueError: invalid literal for int() with base 10: 'C' , Where is the conversion from string into integer happening?

Question:

I have reviewed similar errors. It seems that somewhere in my code I am converting a string into integer. But I do not know where.

I have an input list ‘ops’, which contains strings. I also have another list ‘record’ that I am filling up with integers.

def baseball_game (ops):
  record = []
  for i in range (len(ops)):
    if ops[i] == 'C': 
      record.pop()   #I remove last element. I am mot converting into integer.
      print(record)
    if ops[i] == 'D':
      record.append(record[-1] * 2)  #I am doubling the value of last element, which is already an integer.
      print(record)
    if ops[i] == '+':
      record.append(record[-1] + record[-2]) #I am adding last 2 elements, which are NOT integers.
      print(record)
    else:
      record.append(int(ops[i])) #I am converting into integer any value which is NOT 'C', 'D' nor '+'
      print(record)
  return sum(record)

enter image description here

Asked By: Aizzaac

||

Answers:

The problem is that you have 3 if blocks in a row, and you are expecting them to behave like elifs.

When ops[i] is 'C', it enters the first if block, and then, because 'C' != '+', it enters the else block at the end.

Answered By: TallChuck
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.