user6359012 user6359012 - 6 months ago 9
Python Question

How to find prime number's but theres bugs. I can't find out

I write a program that find the prime numbers . My teacher told me to do that in three steps . Firstly i had to generate all odds numbers . Then i need to check if it is devigable or not . To do that he tell me to use % operator . Here is my code :

for num in range(3,10):
if num%2 != 0: #generating odds
for i in range(3,num):
if num%i != 0:
print num
else:
None
else:
None


Now my question is , the above code is right to generate prime ?

The above code gives me wrong ans . But where's the bugs here ? I need the explenation .

Sample output of the above code is:
3
5
5
5
7
7
7
7
7
9
9
9
9
9
9

Answer

The second for loop should be terminated if num is not a prime number.

for num in range(3, 100):
    if num % 2 != 0:
        for i in range(3, num):
            if num % i == 0:
                break
        else:
            print(num)

I found the official document for you:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Luckily, it provides with a sample about prime number.