You need to enable JavaScript to run this app. Python代码触发TypeError: 'int' object is not callable报错排查
优惠活动
大模型
产品
解决方案
定价
更多

Python代码触发TypeError: 'int' object is not callable报错排查

报错核心原因

代码中把乘法运算错误写成了函数调用格式,这是触发TypeError: 'int' object is not callable的根本原因。

Python语法中,两个数值做乘法必须显式写出乘号*,如果把两个变量直接以「变量(参数)」的形式写在一起,解释器会将括号前的内容识别为函数名,尝试执行调用操作。但代码里的population和richness都是整型变量,不具备可调用属性,因此直接抛出类型错误。


问题具体定位

你判断的出错位置是准确的,问题就出在最后一行计算辛普森指数的代码段:

print("Your simpsons biodiversity index is " + str(1-((population(population-1))/(richness(richness-1)))))

这行代码里的两处计算逻辑存在语法问题:

  • population(population-1):被Python识别为“调用值为population的整数函数,传入population-1作为参数”
  • richness(richness-1):被Python识别为“调用值为richness的整数函数,传入richness-1作为参数”
    两处操作都不符合整型变量的使用规则,触发报错。

修正方案

只需要在两处存在隐式乘法的位置补上乘号*,就能让代码正常运行:

richness = int(input("How many species are in your ecosystem? "))
population = 0
for x in range (1, (richness+1)):
    population = population + int(input("What's the population of species " + str(x) + "? "))
print("Your species richness is " + str(richness))
# 修正:补充两处缺失的乘号
print("Your simpsons biodiversity index is " + str(1 - ((population * (population - 1)) / (richness * (richness - 1)))))

内容的提问来源于stack exchange,提问作者Oskar Brady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.21 00:36:03