You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环死循环求助:无法遍历列表偶数元素

Python while循环死循环问题分析与修复

你的代码陷入死循环的核心原因很明确:i += 1被放在了if代码块内部。

当遍历到列表中的奇数时(比如第一个元素1),numbers[i] % 2 == 0的条件不满足,不会执行print和i += 1操作。此时变量i的值始终停留在当前位置,循环条件i < length永远成立,导致循环无法终止。

修复方案1:调整计数器位置

把i += 1移到if语句外面,确保无论当前元素是奇数还是偶数,计数器都会递增,遍历完所有元素后循环自然终止:

def print_evens(numbers):
    """Prints all even numbers in the list
    """
    length = len(numbers)
    i = 0
    while i < length:
        if numbers[i] % 2 == 0:
            print(numbers[i])
        i += 1  # 每次循环都递增计数器,避免停留在奇数位置
            
print_evens([1, 2, 3, 4, 5, 6])

修复方案2:改用for循环(更推荐)

Python的for循环可以直接遍历列表元素,不需要手动维护计数器,能从根源上避免这类错误,代码也更简洁:

def print_evens(numbers):
    """Prints all even numbers in the list
    """
    for num in numbers:
        if num % 2 == 0:
            print(num)
            
print_evens([1, 2, 3, 4, 5, 6])

内容的提问来源于stack exchange,提问作者kyxgp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:25:24