Your code has a few problems which I’ll try to point out:
count = 0
prime = [] # this is obviously meant to collect all primes
candidate = [] # what is this supposed to do then though?
x = 2
y = 1 # never used
while count < 1000: # you start at `count = 0` but never increase the count
# later on, so would loop forever
x = x+1
if x > 1: # x is always bigger than 1 because you started at 2
# and only increase it; also, you skipped 2 itself
if x%2 != 0: # here, all you do is check if the
if x%3 != 0: # number is dividable by any prime you
if x%5 != 0: # know of
if x%7 != 0: # you can easily make this check work
if x%11 != 0: # for any set (or list) of primes
if x%13 != 0: #
candidate.append(x) # why a candidate? If it’s
# not dividable by all primes
# it’s a prime itself
So, building on this, you can make it all work:
primes = [2] # we're going to start with 2 directly
count = 1 # and we have already one; `2`
x = 2
while count < 1000:
x += 1
isPrime = True # assume it’s a prime
for p in primes: # check for every prime
if x % p == 0: # if it’s a divisor of the number
isPrime = False # then x is definitely not a prime
break # so we can stop this loop directly
if isPrime: # if it’s still a prime after looping
primes.append(x) # then it’s a prime too, so store it
count += 1 # and don’t forget to increase the count
Where did the p in the for loop come from?
for x in something
is a construct that will loop over every element in something
and for each iteration it gives you a variable x
that will contain the current value. So for example the following will separately print 1
, 2
, 3
.
for i in [1, 2, 3]:
print(i)
Or for a list of primes, for p in primes
will loop over all your stored primes and in each iteration p
will be one prime from the list.
So the whole check will essentially loop over every known prime, and for each prime it will check if said prime is a divisor of the number. And if we find one prime for which this is the case, we can abort the loop, because the current number is definitely not a prime itself.