I'm fairly new to Python, and am trying to practice programming by doing Project Euler problems. In order to solve the 7th problem, I decided to first build a simple prime generating function using for loops, which doesn't seem to work.
Here's my code:
primes = [2]
for n in range(2, 10):
for m in range(2, n):
if not(n % m):
primes.append(n)
print primes
The output is [2,4,6,6,8,8,9]
instead of what I intended, i.e. [2,3,5,7]
. The math seems correct to me: Pick a natural number, n
, bigger than two. For all natural numbers m bigger than one, but smaller than n
, check if n
is divisible by m
. If not, add n to the list of primes. Can anyone please tell me what's wrong with my code?
P.S. While I know there are several other (and better) ways of generating primes, I am interested in making my approach (code) work.