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

Python中不同缩进的else语句为何导致输出结果差异?两段质数打印代码疑问解析

Why Do These Two Python Snippets Produce Different Outputs?

Hey there! The key difference between these two pieces of code boils down to which statement the else clause is attached to—Python lets else pair with both if statements and loops (for/while), and that changes everything.

Let's Break Down the First Snippet

This code uses a for loop's else clause, which is a unique Python feature:

print("Prime numbers between 0 and", num)
for x in range(0, num+1):
    if x > 1:
        for i in range(2, x):
            if (x % i) == 0:
                break
        else:  # This else belongs to the FOR loop, not the IF!
            print(x)

Here's how it works:

  • For each number x > 1, we check divisibility from 2 up to x-1.
  • If we find any divisor (x % i == 0), we break out of the inner for loop immediately.
  • The else block only runs if the inner for loop finishes without hitting a break—meaning no divisors were found, so x is a prime number. This is the correct logic for finding primes.

Now the Second Snippet

Here, the else is tied to the inner if statement instead of the for loop:

print("Prime numbers between 0 and", num)
for x in range(0, num+1):
    if x > 1:
        for i in range(2, x):
            if (x % i) == 0:
                break
            else:  # This else belongs to the IF statement
                print(x)

This changes the behavior entirely:

  • For each i in the inner loop, if x isn't divisible by i (the if condition fails), we immediately run the else block and print x.
  • This means non-prime numbers can get printed multiple times, and primes get printed repeatedly too. For example, if num=5:
    • x=3: i=2 doesn't divide 3 → print 3 once
    • x=5: i=2, i=3, i=4 all don't divide 5 → print 5 three times
  • Primes like 2 don't get printed at all, since the inner loop range(2,2) is empty and never runs.

Quick Recap

  • Loop else: Runs only when the loop completes normally (no break). Perfect for prime checks, since we confirm no divisors exist.
  • If else: Runs every time the if condition isn't met. This leads to spurious prints because we're not waiting to check all possible divisors before deciding if x is prime.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 00:32:30