Python开发倒计时器时if语句错误触发非预期分支导致报错
问题原因
- 最核心的错误是条件判断的逻辑写法错误:你写的
if 'minutes' or 'minute' in test_input不符合Python的语法逻辑,Python会将这个表达式拆分为if ('minutes') or ('minute' in test_input),而非你预期的判断两个关键词是否存在。非空字符串'minutes'的布尔值永远为True,所以这个if分支永远会触发,永远不会走到后续的小时判断分支,输入10 hours的时候,分支里只替换了分钟相关的关键词,字符串里还保留hours,转int就会抛出报错。 - 第二个小问题是类方法的定义不规范:你定义的
timer类中的timer方法默认是实例方法,第一个参数应该接收实例对象self,你现在直接把第一个参数设为test_input,用类直接调用虽然能临时跑通,但属于不规范的写法,后续扩展容易出问题。 - 第三个问题是代码冗余+命名冲突:小时和分钟分支的倒计时逻辑完全重复,没必要写两遍;且你在分支内定义了和类名重名的
timer变量,容易触发隐式bug。
修复方案
- 修正所有条件判断的逻辑,明确写出每个判断的完整表达式
- 给类方法添加
@staticmethod装饰器,声明为静态方法,不需要实例即可调用 - 把重复的倒计时逻辑抽为单独的函数,修改冲突的变量名,优化代码结构
修复后完整代码
import time class Timer: @staticmethod def countdown(seconds): while seconds: mins, secs = divmod(seconds, 60) time_str = '{:02d}:{:02d}'.format(mins, secs) print(time_str, end="\r") time.sleep(1) seconds -= 1 print('ALARM') @staticmethod def timer(test_input): if 'minutes' in test_input or 'minute' in test_input: nt = test_input.replace('minutes','').replace('minute','').strip() nt = int(nt) total_seconds = nt * 60 print(f"倒计时总时长:{total_seconds}秒") Timer.countdown(total_seconds) elif 'hours' in test_input or 'hour' in test_input: nt = test_input.replace('hours','').replace('hour','').strip() nt = int(nt) total_seconds = nt * 3600 print(f"倒计时总时长:{total_seconds}秒") Timer.countdown(total_seconds) else: print("输入格式不支持,请输入带hour/hours或minute/minutes的内容") test_input = input('请输入倒计时时长,例如10 hours/5 minutes:') Timer.timer(test_input)
内容的提问来源于stack exchange,提问作者scripter2
相关产品推荐
相关产品推荐

