简体   繁体   中英

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

I am new to Python and am learning some basics. I would like to know why I am getting this error. The code is:

a = 0
x = int(input('What is your first number? '))
y = int(input('What is your second number? '))
MATH = [x, y]
R = int(input('How many numbers do you want to use? '))
if R > 2:
    R -= 1
    New = input('What is the next number? ')
    MATH.append(New)
counter = 0
answer = MATH[counter]
for i in MATH:
  counter += 1
  MATH[counter]
  answer += answer
print(answer)

The error I'm getting is:

`TypeError                                 Traceback (most recent call last)
<ipython-input-12-ec570ecd992a> in <module>()
     12 for i in MATH:
     13   counter += 1
---> 14   answer += MATH[counter]
     15 print(answer)
     16 

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

Any and all help is appreciated!

You forgot to convert to type int in this line:

New = input('What is the next number? ')

Should be:

New = int(input('What is the next number? '))

I updated the code check now.

x = int(input('What is your first number? '))
y = int(input('What is your second number? '))
MATH = [x, y]
R = int(input('How many numbers do you want to use? '))
if R > 2:
    R -= 1
    New = int(input('What is the next number? ')) #fixed line
    MATH.append(New)
counter = 0
answer = MATH[counter]
for i in MATH:
  counter += 1
  MATH[counter]
  answer += answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM