【问题标题】:How to resolve TypeError: 'float' object is not callable如何解决 TypeError:'float' 对象不可调用
【发布时间】:2018-09-22 12:04:06
【问题描述】:
import math

def reportSphereVolume(r):
    SphereVolume = ((4/3)*math.pi*((r)**3))
    return SphereVolume


def reportSphereSurfaceArea(r):
    SphereSurfaceArea = ((4)*math.pi((r)**2))
    return SphereSurfaceArea

radius = int(input("What is the radius of the sphere? " ))
reportSphereVolume(radius)
reportSphereSurfaceArea(radius)

执行时我收到以下信息。

What is the radius of the sphere? 10
Traceback (most recent call last):
  File "D:\Thonny\SphereAreaVolume.py", line 16, in <module>
    reportSphereSurfaceArea(radius)
  File "D:\Thonny\SphereAreaVolume.py", line 11, in reportSphereSurfaceArea
    SphereSurfaceArea = ((4)*math.pi((r)**2))
TypeError: 'float' object is not callable

我迷路了,我一直在看视频和阅读教科书,但我仍然无法解决。 请帮忙。

【问题讨论】:

  • 非常感谢您的回复。我现在明白我的错误了。从现在开始我会小心的。我现在无法打印这些值...有什么想法吗?
  • 每个人都会犯这种错误,即使是经验丰富的程序员。祝您继续接受编程教育。当计时器用完时,您应该接受其中一个答案。对于您的打印问题,请发布一个新问题,其中包含与您在此处所做的类似的示例代码。

标签: python python-3.x


【解决方案1】:

就是这个部分:

math.pi((r)**2)

python 中的括号可以表示不同的含义。您可以像在数学中那样使用它们来对表达式进行分组,就像您在体积和面积计算中所做的那样。但它们也用于函数调用,如reportSphereVolume(radius)。而且它们也不能用于乘法。相反,您必须使用明确的*

math.pi 是一个float 常量,当它用括号写成这样时,python 认为你正试图将它作为一个函数来调用。因此出现错误:TypeError 'float' object is not callable'。应该是:

SphereSurfaceArea = (4)*math.pi*(r**2)

【讨论】:

  • 您应该注意python语法和数学符号之间的区别。这可能是 OP 混乱的根源。
  • 我对您的问题进行了更多编辑,以突出数学符号中的乘法与 python 语法之间的区别,这与括号和函数调用一样重要。随意用自己的方式表达。
【解决方案2】:

注意体积方程和表面积方程之间的差异(添加空格以使差异在视觉上更明显):

SphereVolume =      ((4/3)*math.pi*((r)**3))
SphereSurfaceArea = ((4)  *math.pi ((r)**2))

后者在math.pi 之后缺少乘法运算符 (*)。与代数类不同,大多数编程语言都需要与* 进行显式乘法。名称后面的括号表示python中的函数调用。

我建议您对括号多加小心。它们应该用于使计算的目的更清楚,例如当操作的顺序不是很明显时。在这种情况下,您的一些括号是多余的,使表达式更难阅读。例如,整个表达式周围的括号以及单个数字或变量周围的括号无助于阐明运算顺序,可以将其删除以使表达式更具可读性。另一方面,小数 (4/3) 周围的括号和求幂 (r**3)(r**2) 周围的括号一样有意义,因为它们清楚地表明您希望首先评估这些运算符。考虑到这一点,您可以执行以下操作:

SphereVolume =      (4/3)*math.pi*(r**3)
SphereSurfaceArea = 4*math.pi(r**2)

请注意这是如何更容易阅读并有助于更容易找到错误。

【讨论】:

    【解决方案3】:

    您在第二个函数中犯了一个很小的错误,即表面积 在 math.pi 之后的第 10 行检查你没有使用 * 运算符。所以python把它当作一个函数。 只需在 math.pi 之后添加 * 即可完成 这是代码:

    import math 
    def reportSphereVolume(r): 
        SphereVolume =  
        ((4/3)*math.pi*((r)**3)) 
        return SphereVolume 
    def reportSphereSurfaceArea(r):   
        SphereSurfaceArea =
        ((4)*math.pi*((r)**2)) 
        return SphereSurfaceArea
    radius = int(input("What is the radius of   
    the sphere? " ))
    print("Vol : %f" %  
    (reportSphereVolume(radius)))    
    print("Area : %f" % 
    (freportSphereSurfaceArea(radius)))
    

    希望它有所帮助!

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多