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

如何停止倒计时循环?实现倒计时至0时终止循环并显示提示消息

倒计时到0终止循环并显示提示的解决方案

修改后的代码

import time

countdown = 100

while countdown >= 0:
    display = " [ Countdown {:03d} ] ".format(countdown)
    print(display, end="\r")
    if countdown == 0:
        print("\n[ 倒计时结束! ]")
        break
    time.sleep(2)
    countdown -= 1

关键修改说明

  • 把无限循环while True替换为while countdown >= 0,明确循环仅在倒计时数值有效时运行
  • 新增判断逻辑:当倒计时数值为0时,打印结束提示并通过break直接终止循环
  • 调整time.sleep(2)的执行位置,避免倒计时到0后还等待2秒才结束流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:39:19