You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错求助:TypeError: 'float' object is not callable

问题解决:TypeError: 'float' object is not callable 定时器代码报错

你编写的Python定时器代码在使用time.perf_counter()时触发TypeError: 'float' object is not callable错误,移除该函数后代码可正常运行,你疑惑为何conTime会被转换为float类型。

你的原代码:

import time
totalTime = 0
def start(s):
        start = time.perf_counter()
        while True:
                if time.perf_counter()-start > s:
                        return True


def conversion(Time):
        Time = Time.split(":")
        time1 = int(Time[0])*60
        return time1+int(Time[1])

def main():
        start = time.perf_counter()

        global totalTime
        Time = input("Enter Time [00:00]: ")
        end = time.perf_counter()

        conTime = conversion(Time)
        totalTime += conTime
        totalTime += round(end-start)

        start(conTime)

        print(f"{Time} is Completed!!")

while True:
        main()

报错回溯:

Traceback (most recent call last):
  File "/data/data/com.termux/files/home/timer.py", line 32, in <module>
    main()
  File "/data/data/com.termux/files/home/timer.py", line 27, in main
    start(int(conTime))
TypeError: 'float' object is not callable

问题原因:

核心问题和conTime的类型无关——你在main()函数里把全局的start函数名给覆盖成了float变量:

  • 你先定义了一个名为start的函数,用来实现定时器逻辑;
  • 但在main()里执行start = time.perf_counter()时,这行代码把原本指向函数的start变量,替换成了time.perf_counter()返回的浮点型时间值;
  • 之后调用start(conTime)时,实际上是在尝试调用一个float对象,自然触发"float不可调用"的错误。

修复方案:

只需要修改main()里的变量名,避免和全局的start函数重名:

import time
totalTime = 0
def start(s):
        start = time.perf_counter()
        while True:
                if time.perf_counter()-start > s:
                        return True


def conversion(Time):
        Time = Time.split(":")
        time1 = int(Time[0])*60
        return time1+int(Time[1])

def main():
        # 重命名变量,避免覆盖start函数
        start_time = time.perf_counter()

        global totalTime
        Time = input("Enter Time [00:00]: ")
        end = time.perf_counter()

        conTime = conversion(Time)
        totalTime += conTime
        totalTime += round(end - start_time)  # 同步修改引用的变量名

        start(conTime)

        print(f"{Time} is Completed!!")

while True:
        main()

修改说明:

  • 将main()中的start = time.perf_counter()改为start_time = time.perf_counter();
  • 同时把round(end-start)改为round(end-start_time),确保引用的是正确的计时变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:45:34