【问题标题】:TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'类型错误:+= 不支持的操作数类型:“NoneType”和“str”
【发布时间】:2018-07-07 06:14:13
【问题描述】:

我是 Python 新手,我确信我做错了什么 - 我想向用户询问三个数字并打印它们的总和,这是我当前的代码:

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

顺便说一句,total = None 是尝试声明变量,以便我可以在不设置值的情况下使用它? 我明白了

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,请问?
  • 你知道None0有什么区别吗?你知道'0'0有什么区别吗?
  • '0' 是一个字符串,0 是一个数字/int
  • 正如目前所写的,我怀疑代码不会在没有IndentationError 的情况下运行。
  • 抱歉缩进,我猜它会在 python shell 中自动缩进但不会复制它?反正我已经加了缩进

标签: python python-3.x typeerror


【解决方案1】:

你不应该这样做total = NoneNoneType 不能用于加法。

错误消息提示了一个额外的问题:根据您的描述,您尝试添加 3 个 数字,但内置 input() 的返回类型为 str。所以这就是你应该写的:

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

所有点:

  • 正确缩进代码。缩进是 Python 的一个关键部分。
  • 不要在每个循环中将total 设置为零。只在循环外设置一次
  • 注意类型

【讨论】:

  • 当我运行它并尝试打印(总计)时,它只返回最后一个数字,而不是将它们全部加在一起
  • 我正在做一些非常相似的事情,这只是我已经拥有的引发错误的代码。
猜你喜欢
  • 2014-06-15
  • 2023-01-04
  • 2023-01-24
  • 2017-07-11
  • 2019-08-22
  • 2015-09-21
  • 2017-05-27
  • 1970-01-01
相关资源
最近更新 更多