Nykki Ogbomoh
Nykki Ogbomoh

Reputation: 11

Fix beginner's code used to formulate a list of primes

The code results in the list being appended with odd numbers instead of prime numbers. If the odd number is not divisible by 3, then the list will generate the particular number at least 3 times:

for i in range(2,100):
    for x in range(2,i):
        if (i %x==0):
            break
        else:
            prime.append(i)
        print(prime)

I expected to generate one list of prime numbers ranging from (2, 100). However the actual output is:

...
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11]
...

Upvotes: 1

Views: 47

Answers (2)

cdlane
cdlane

Reputation: 41895

This is simply due to two indentation errors: one on your else statement; one on your print statement:

prime = []

for i in range(2, 100):
    for x in range(2, i):
        if i % x == 0:
            break
    else:  # no break
        prime.append(i)

print(prime)

In Python, correct indentation matters. The else on the for loop executes only if the for loop doesn't exit via the break statement. As @B.Go notes, this isn't an efficient prime generator, but it is a working one.

Upvotes: 2

B. Go
B. Go

Reputation: 1424

That's exactly what you wrote in the code: each time a number, say 7, is not divided exactly by x (for 2, 3, 4, 5, 6), you append the number in the list.
You should add it once only after the for is done.
And you should skip all even dividers except the 2, it would be much faster. Range can step by 2 to do that, after you tested with 2 outside of that...

Upvotes: 1

Related Questions