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

如何用Python制作计时器?运行倒计时代码出现TypeError如何修复?

问题修复方案

错误原因

你遇到的类型报错是因为Python的input()函数默认返回字符串类型,你直接将用户输入的字符串传入countdown函数后,函数内执行time -= 1操作时,试图对字符串做整数减法运算,不符合语法要求因此抛出异常。

同时原代码还存在两个隐藏问题:

  • 当time变量递减到0时会先退出while循环,循环内time == 0的判断分支永远不会执行,时间到的提示无法打印
  • os.system('clear')仅适配Linux/macOS系统,Windows环境下清屏会报错

修复后完整代码

from time import sleep
import os

def countdown(time_sec = 5):
    while time_sec > 0:
        print(time_sec)
        sleep(1)
        # 兼容多系统清屏逻辑
        os.system('cls' if os.name == 'nt' else 'clear')
        time_sec -= 1
    print("Time is going up")

if __name__ == "__main__":
    try:
        input_time = int(input('Input number of seconds to countdown: '))
        if input_time <= 0:
            print("Please enter a positive integer")
        else:
            countdown(input_time)
    except ValueError:
        print("Invalid input, please enter a number")

主要修改点

  • 用int()将用户输入的字符串转为整数类型,同时增加try-except捕获非数字输入的异常,避免程序直接崩溃
  • 调整了循环逻辑,将时间到的提示放到循环外,保证提示正常输出
  • 增加了系统判断逻辑,自动适配Windows、Linux、macOS的清屏命令
  • 增加输入合法性校验,避免用户输入负数、0导致的倒计时逻辑异常
  • 将参数名从time改为time_sec,避免和Python内置time模块重名引发潜在冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:15:05