python script to give a list of prime no.

Pieter van Oostrum pieter-l at vanoostrum.org
Sun Apr 5 13:46:00 EDT 2020


Sathvik Babu Veligatla <sathvikveligatla at gmail.com> writes:

> hi,
> I am new to python, and i am trying to output the prime numbers beginning from 3 and i cannot get the required output.
> It stops after giving the output "7" and that's it.
>
> CODE:
> a = 3
> l = []
> while True:
>     for i in range(2,a):
>         if a%i == 0:
>             l.append(1)
>         else:
>             l.append(0)
>
>     if l.count(1) == 0:
>         print(a)
>         a = a + 2
>     elif l.count(1) >> 0:
>         a = a + 2
>     
>
>
> Any help is appreciated,
> Thank you.

As others have already noticed, the l.count(1) >> 0: is faulty. You probably meant
l.count(1) > 0:, but else would be simpler.

But then, once there is a 1 in l that never disappears, so after that it will never print any more numbers. You should put the l = [] AFTER the while True, so that you start with a new empty list every cycle.

And then, putting 0 an 1's in a list and then counting how many 1's there are is quite inefficient. Just counting from the beginning would be more efficient. Like:

a = 3
while True:
    count = 0
    for i in range(2,a):
        if a%i == 0:
            count += 1
    if count == 0:
        print(a)
        a = a + 2
    else:
        a = a + 2

Which can be simplified to:

a = 3
while True:
    count = 0
    for i in range(2,a):
        if a%i == 0:
            count += 1
    if count == 0:
        print(a)
    a = a + 2

And you effectively use the counter as a boolean, so replace is by a boolean.

a = 3
while True:
    is_prime = True
    for i in range(2,a):
        if a%i == 0:
            is_prime = False
            # once we found a divisor, it is no use to continue
            break
    if is_prime:
        print(a)
    a = a + 2

Further optimizations are possible, for example use range(2,a/2) or even range (2, sqrt(a)).
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list