如何让while循环仅在结果变化时打印一次?Python倒计时程序优化求助
问题描述
我编写了一个从4倒计时至0的简短程序,希望每个数字仅打印一次后再切换到下一个数字(即4、3、2、1、0),但当前每个数字会被重复打印。
我的代码:
import time def timer(): max_time = 4 start_time = time.time() while max_time > 0: difference = time.time() - start_time if 1 > difference > 0: print(max_time) if 2 > difference > 1: max_time = 3 print(max_time) elif 3 > difference > 2: max_time = 2 print(max_time) elif 4 > difference > 3: max_time = 1 print(max_time) elif 5 > difference > 4: print('Go') break timer()
当前输出:
4 4 4 4 3 3 3 3 2 2 2 2 1 1 1 1
期望输出:
4 3 2 1
问题原因
你的代码中while循环会持续高频运行,在每个时间区间(比如0-1秒)内,循环会多次触发print语句,导致同一个数字被重复打印。同时逻辑中硬编码了max_time的赋值,不仅不够灵活,也没处理0的输出逻辑。
解决方案
方案一:极简实现(推荐)
利用time.sleep()控制每秒输出一个数字,逻辑简单直接,完全符合需求:
import time def timer(): # 从4倒序遍历到1 for num in range(4, 0, -1): print(num) time.sleep(1) # 最后输出Go print('Go') timer()
方案二:修复原时间差逻辑
如果要保留基于时间差的判断方式,需要添加一个集合记录已打印的数字,避免重复输出:
import time def timer(): max_time = 4 start_time = time.time() printed_nums = set() # 存储已经打印过的数字 while True: difference = time.time() - start_time # 计算当前应该显示的数字 current_num = max_time - int(difference) # 数字大于0且未打印过才输出 if current_num > 0 and current_num not in printed_nums: print(current_num) printed_nums.add(current_num) # 倒计时结束后输出Go并退出循环 if difference >= max_time: print('Go') break timer()
内容的提问来源于stack exchange,提问作者luke
相关产品推荐
相关产品推荐

