Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are a number of problems with this code. First, <code>a/divisor == int(a/divisor)</code> is always <code>True</code>, because division in Python is integral (you will always get an integer result). Use <code>a % divisor == 0</code> instead.</p> <p>Another problem is that <code>prime = True</code> is outside the loop, meaning that as soon as one value is declared not prime, no more values can be prime! (<code>prime</code> will never get set back to <code>True</code> anywhere.)</p> <p>A third issue, more of style, is that it is preferred to use a <code>for ... in</code> loop in python, eg</p> <pre><code>for a in xrange(1, 1000): for divisor in xrange(2, a): ... </code></pre> <p>Edit: Regarding your modified code: your <code>if</code> statement at the very end is not indented, and therefore not part of the <code>for</code> loop. It is only being executed once, after the loop ends, meaning <code>prime</code> will be the last value set (where <code>a</code> is <code>999</code>, not a prime). You want to indent the entire <code>if</code> statement to be in your inner <code>for</code> loop. You could condense this, though:</p> <pre><code>for a in xrange(1, 1000): for divisor in xrange(2, a): if a % divisor == 0: break else: print a numberlist.append(a) </code></pre> <p>Note that this uses the <code>for ... else</code> clause. Putting <code>else</code> at the end of a <code>for</code> loop will cause that <code>else</code> block to run <em>only if</em> the loop is not broken by <code>break</code>.</p> <p>As a further comment, starting the whole loop at <code>1</code> will have <code>1</code> in the list, but <a href="http://en.wikipedia.org/wiki/Prime_number" rel="nofollow"><code>1</code> is not a prime</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload