Skip to content

TypeError: unsupported operand 类型(s)

错误信息

                unsupported operand 类型(s) for +: 'int' and 'str'
              

快速摘要

你 used 值使用运算符 or 函数那个 doesn't 接受那个类型 — 如添加字符串到 integer.

为什么发生

  • Mixed int and str in arithmetic or concatenation 操作

  • Called 函数使用实参的 错误类型 (e.g., len(5))

  • Used 运算符 on 类型那个 don't support 它

最小示例

✗ 错误代码
age = 25
message = "I am " + age + " years old"
✓ 修复代码
age = 25
message = "I am " + str(age) + " years old"

Python 能't concatenate str and int — convert age 到字符串使用 str(age) 之前 concatenating.

如何诊断

  • 读取错误 — 它 names 类型 and 操作 involved

  • 检查类型的 operands 使用 类型() or isinstance()

  • Trace 哪里每个值 came 从到 查找类型 mismatch

如何修复

  • Convert 值到 正确类型 explicitly (e.g., str(age), int(s))

  • Fix 变量那个持有错误类型 at 它的源

  • Use isinstance() 检查之前操作

如何预防

  • Use 类型 hints (def foo(x: int) -> str:) 到 catch mismatches

  • 验证函数输入使用 isinstance() 之前 using 它们

相关资源

相关术语

相关课程

相关练习

← 返回语言