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

Python倒计时代码在窗口运行报OverflowError问题求助

问题解决:Python倒计时代码的OverflowError问题

问题根源

你遇到的OverflowError: Python int too large to convert to C int,本质原因是输入的小时、分钟、秒是字符串类型,直接参与乘法运算时会重复字符串而非数值计算。比如输入h="1",执行h*3600会得到由3600个"1"组成的超长字符串,转成整数后数值远超出datetime.timedelta底层依赖的C int范围,最终触发溢出错误。

Windows终端看似正常,大概率是你测试时输入的数值极小(比如h=0),此时字符串重复后转int仍为0,刚好不会触发溢出,但这只是巧合,并非代码逻辑正确。

修复方案

方案1:获取输入时直接转为整数

在接收用户输入的环节,就把字符串转为整数,从源头避免类型错误:

import time
import datetime


def countdown(h: int, m: int, s: int):
    total_seconds = h * 3600 + m * 60 + s
    minim = 0
    while total_seconds > minim:
        timer = datetime.timedelta(seconds=total_seconds)
        print(timer, end="\r")
        time.sleep(1)
        total_seconds -= 1
    print("Bzzzt! The countdown is at zero seconds!")


# 输入时直接转换为整数并处理非法输入
try:
    h = int(input("Time in hour :"))
    m = int(input("Time in minute :"))
    s = int(input("Time in seconds :"))
    countdown(h, m, s)
except ValueError:
    print("请输入有效的数字!")

方案2:在函数内部转换参数类型

如果不想修改输入逻辑,可以在countdown函数开头先将参数转为整数:

import time
import datetime


def countdown(h, m, s):
    # 先将参数转为整数,处理非法输入
    try:
        h = int(h)
        m = int(m)
        s = int(s)
    except ValueError:
        print("请输入有效的数字!")
        return
    total_seconds = h * 3600 + m * 60 + s
    minim = 0
    while total_seconds > minim:
        timer = datetime.timedelta(seconds=total_seconds)
        print(timer, end="\r")
        time.sleep(1)
        total_seconds -= 1
    print("Bzzzt! The countdown is at zero seconds!")


h = input("Time in hour :")
m = input("Time in minute :")
s = input("Time in seconds :")
countdown(h, m, s)

优化说明

  • 移除了冗余的类型注解(直接用int替代模糊的int | Any)
  • 添加try-except块处理非数字输入,避免程序直接崩溃
  • 简化了循环条件判断,无需重复转换整数类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:21:01