为何引用字典键15-23时Python代码无法正常输出?
问题分析与修复
你代码中输入15-23时部分章节(如16-23里时长小于60的章节)无法输出当前章节时长,核心原因是处理时长小于60的分支时,未给current_total_minutes赋值:
- 当
current_total_time < 60时,current_total_minutes仍为初始值0,后续判断current_total_minutes ==1或>=2均不成立,导致没有触发任何打印语句。
修复方法:在elif (current_total_time > 0) and (current_total_time < 60):分支的第一行添加赋值语句:
current_total_minutes = current_total_time
这样时长小于60的章节就能正确获取分钟数,触发对应的打印逻辑。
代码简化方案
针对这段冗长的代码,可以学习以下Python技巧来简化:
- 用
divmod()快速拆分小时和分钟:替代手动计算余数与除法,一行代码即可得到小时和分钟的数值current_total_hours, current_total_minutes = divmod(current_total_time, 60) - 用条件表达式处理单复数:无需多层嵌套判断,直接在字符串中用三元表达式处理
hour/hours、minute/minutes的单复数hour_str = f"{current_total_hours} hour{'s' if current_total_hours !=1 else ''}" minute_str = f"{current_total_minutes} minute{'s' if current_total_minutes !=1 else ''}" - 提取重复逻辑为函数:将时长格式化逻辑封装成函数,减少代码重复,提升可读性
def format_duration(minutes): hours, mins = divmod(minutes, 60) parts = [] if hours > 0: parts.append(f"{hours} hour{'s' if hours !=1 else ''}") if mins > 0: parts.append(f"{mins} minute{'s' if mins !=1 else ''}") return " and ".join(parts) - 增加输入校验:防止用户输入非1-23的数字导致报错,提升程序健壮性
while True: try: current_section = int(input('What section are you currently on? (1-23)\n')) if 1 <= current_section <=23: break print("请输入1-23范围内的章节号!") except ValueError: print("请输入有效的数字!")
简化后的完整代码示例
video_dict = { 1:19,2:54,3:122,4:9,5:75,6:174,7:100,8:81,9:29,10:46, 11:138,12:23,13:17,14:143,15:143,16:24,17:45,18:28, 19:3,20:41,21:45,22:15,23:1 } def format_duration(minutes): hours, mins = divmod(minutes, 60) parts = [] if hours > 0: parts.append(f"{hours} hour{'s' if hours !=1 else ''}") if mins > 0: parts.append(f"{mins} minute{'s' if mins !=1 else ''}") return " and ".join(parts) # 输入校验 while True: try: current_section = int(input('What section are you currently on? (1-23)\n')) if 1 <= current_section <=23: break print("请输入1-23范围内的章节号!") except ValueError: print("请输入有效的数字!") current_total_time = video_dict[current_section] duration_str = format_duration(current_total_time) print(f'Section {current_section} is {duration_str} long.\n')
内容的提问来源于stack exchange,提问作者Showtunes
相关产品推荐
相关产品推荐

