Python while循环无法正常执行且不终止,求修复及原因解析
问题分析与修复
死循环原因
当student的值为2时,命中if student in absent条件,执行continue直接回到循环起始点,但此时**student的数值没有任何变化**。接下来的每一次循环都会重复判断student=2,再次触发continue,彻底卡死在这个状态,形成死循环,所以程序既不会继续打印后续学生的信息,也不会终止运行。
修复后的代码
方案一:在continue前递增学号
absent = [2,5] student = 1 while student < 11: if student in absent : student += 1 # 缺席学生也要让学号推进 continue print(f"student {student} is attended!") student += 1
方案二:将递增操作统一放在循环末尾
absent = [2,5] student = 1 while student < 11: if student not in absent : print(f"student {student} is attended!") student += 1 # 无论是否缺席,每次循环都更新学号
核心逻辑说明
两种方案的本质都是确保循环的控制变量student在每次循环中都会被递增,不会因为continue跳过了递增步骤而停留在某个固定值,从而避免死循环的发生。
内容的提问来源于stack exchange,提问作者Chya
相关产品推荐
相关产品推荐

