why is 2 printed as a prime when if statement says it should not be
<p>i know 2 is a prime number (btw), but when this code is ran it doesn't match the if statement condition <code>if n % x == 0</code>. but <code>2 % 2 == 0</code> so it should be a equal    </p>

<pre><code>for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
           print(n, 'equals', x, '*', n//x)
           break
    else:
    # loop fell through without finding a factor
         print(n, 'is a prime number')
</code></pre>

<p>From the Python documentation of <a href="https://docs.python.org/3/library/stdtypes.html#typesseq-range" rel="nofollow"><code>range()</code></a></p>

<blockquote>
  <p>For a positive <em>step</em>, the contents of a range <code>r</code> are determined by the formula <code>r[i] = start + step*i</code> where <code>i &gt;= 0</code> and <code>r[i] &lt; stop</code>.</p>
  
  <p>A range object will be empty if <code>r[0]</code> does not meet the value constraint.</p>
</blockquote>

<p>So when <code>n = 2</code>, <code>range(2, n)</code> is an empty range, because <code>r[0]</code> is <code>2</code> and that doesn't meet the constraint <code>2 &lt; 2</code>. Therefore <code>for</code> loop never runs, so it never breaks, and as a result, the <code>else:</code> block is executed and reports that it's prime.</p>

python python-3.x