Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

python - TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

I am new to Python and I'm sure that I'm doing something wrong - I would like to ask a user for three numbers and print their sum, here's my current code:

for i in range(0, 3):
    total = None
    num = input('Please enter number {}:'.format(str(i)))
    total += num

By the way, the total = None was to try and declare the variable so I could use it without setting a value? I get this

Traceback (most recent call last):
  File "<pyshell#20>", line 4, in <module>
    total += num
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You shouldn't do total = None. NoneType cannot be used against addition.

There's an extra problem suggested by the error message: From your description you're trying to add 3 numbers, but the return type of the builtin input() is str. So this is what you're supposed to write:

total = 0
for i in range(0, 3):
    num = input('Please enter number {}:'.format(str(i)))
    total += int(num)

All the points:

  • Indent the code correctly. Indentation is a crucial part of Python.
  • Don't set total to zero at every loop. Only set it once outside the loop
  • Take care of types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...