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 tox-1. - If we find any divisor (
x % i == 0), webreakout of the innerforloop immediately. - The
elseblock only runs if the innerforloop finishes without hitting abreak—meaning no divisors were found, soxis 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
iin the inner loop, ifxisn't divisible byi(theifcondition fails), we immediately run theelseblock and printx. - This means non-prime numbers can get printed multiple times, and primes get printed repeatedly too. For example, if
num=5:x=3:i=2doesn't divide 3 → print 3 oncex=5:i=2,i=3,i=4all 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 (nobreak). Perfect for prime checks, since we confirm no divisors exist. - If
else: Runs every time theifcondition isn't met. This leads to spurious prints because we're not waiting to check all possible divisors before deciding ifxis prime.
内容的提问来源于stack exchange,提问作者Khang Nguyen
相关产品推荐
相关产品推荐

