类型错误:+= 不支持的操作数类型:'NoneType' 和 'str' [英] TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
问题描述
我是 Python 新手,我确定我做错了什么 - 我想向用户询问三个数字并打印它们的总和,这是我当前的代码:
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
顺便说一下,total = None 是为了尝试声明变量,以便我可以在不设置值的情况下使用它?我明白了
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'
推荐答案
你不应该做 total = None
.NoneType
不能用于加法.
You shouldn't do total = None
. NoneType
cannot be used against addition.
错误消息提示了一个额外的问题:根据您的描述,您正在尝试添加 3 个 数字,但内置 input()
的返回类型是str
.所以这就是你应该写的:
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)
所有要点:
- 正确缩进代码.缩进是 Python 的关键部分.
- 不要在每次循环时将
total
设置为零.只在循环外设置一次 - 注意类型
- 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
这篇关于类型错误:+= 不支持的操作数类型:'NoneType' 和 'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!