Python脚本IF语句执行异常:满8条条目选No未输出未排序列表
问题分析与修复方案
问题根源
当录入满8条数据选择“no”不排序时,程序直接结束且未打印列表,核心原因是:
添加完第8条数据后,列表长度变为8,此时先触发if len(Race_participants) >=4的判断,若选择“no”会执行continue直接回到while循环开头,而此时len(Race_participants) <8条件不成立,循环直接终止,后续用于打印未排序列表的if len(Race_participants)==8代码块完全没机会执行。
修复及优化后的代码
Race_participants = [] Mworldrec = 9.58 Meuropeanrec = 9.86 Mbritishrec = 9.87 Fworldrec = 10.49 Feuropeanrec = 10.73 Fbritishrec = 10.99 # 把函数定义移到循环外,避免重复定义 def get_time(participant): return participant.get('time') def get_name(participant): return participant.get('name') def get_gender(participant): return participant.get('gender') while len(Race_participants) < 8: name = str(input("\nWhat is the participants name? ")).lower() gender = str(input("\nIs the participant male or female? ")).lower() # 改为float类型,支持小数时间输入 time = float(input("\nWhat is the participants race time? ")) records_beaten = [] if gender == "male": if Mworldrec > time: records_beaten.append("mens world record") if Meuropeanrec > time: records_beaten.append("mens european record") if Mbritishrec > time: records_beaten.append("mens British record") else: if Fworldrec > time: records_beaten.append("womens world record") if Feuropeanrec > time: records_beaten.append("womens european record") if Fbritishrec > time: records_beaten.append("womens British record") if records_beaten: print("\nParticipant", name,"has beaten the following records: ") for record in records_beaten: print("\n", record) print("\nParticipant" ,name, "Successfully recorded") person = { 'name': name, 'gender': gender, 'time': time } Race_participants.append(person) # 仅在未达到8条时询问排序,避免重复询问 if len(Race_participants) >=4 and len(Race_participants) <8: user_choice = input("Do you want to sort the list? (yes/no)").lower() if user_choice == "yes": Race_participants.sort(key=get_time) print("Sorted list in ascending order" ,Race_participants) elif user_choice != "no": print("Invalid choice. Please enter 'yes' or 'no'.") # 选择no时不做操作,继续循环即可,无需continue # 循环结束后统一处理满8条的情况 print("You have reached the maximum amount of entries") user_choice = input("\nDo you want to sort the list? (yes/no)").lower() if user_choice == "yes": Race_participants.sort(key=get_time) print("Sorted list in ascending order" ,Race_participants) elif user_choice == "no": print("Unsorted list:", Race_participants) else: print("Invalid choice. Please enter 'yes' or 'no'.")
关键优化点
- 将排序相关函数移到循环外部,避免每次循环重复定义函数,提升性能
- 把
time输入改为float类型,适配跑步记录的小数场景,避免输入小数时报错 - 拆分了满4条但未到8条、以及满8条后的排序询问逻辑,避免重复触发询问,同时解决了原代码中
continue导致的跳过打印问题 - 循环结束后单独处理满8条的情况,确保无论选择yes/no都能执行对应的打印操作
内容的提问来源于stack exchange,提问作者JordonH16
相关产品推荐
相关产品推荐

