Joe Carvagio
Joe Carvagio

Reputation: 1

Printing error in Python?

I'm new to Python, I've only done programming in Java before recently. I am writing a basic program in Python to print out the 1000th prime number and while I did get it to work, for some reason it's also printing out the next 7 numbers unless I use an unnecessary break:

import math

n=2 
location =0

while location < 999 :      
   if location == 998 :
      print n
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

prints

7919
7920
7921
7922
7923
7924
7925
7926

but

while location < 999 :
   if location == 998 :
       print n
        break
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

prints

7919

Can anyone tell me why this is happening? Also when I was trying to fix this, I found that the shell would only print this once, then if I copied the code, whether I altered it or not, it wouldn't print anything. I would need to restart the shell each time I wanted to alter the code.

Upvotes: 0

Views: 102

Answers (2)

Schleis
Schleis

Reputation: 43700

In the first case, you are printing until you have found the next prime. It is continuing in the while loop. And since location == 998 is true, it prints the numbers. Then when it finds the next prime location < 999 resolves to false and the while loop is completed.

You need the break so that the code leaves the while loop when you found the prime.

If you don't want to break move the print out of the loop and reduce the while condition by 1.

while location < 998 :
    n=n+1
    srn = math.sqrt(n)
    srn = int(srn)
    while  srn > 1 :
        if  n % srn == 0 :
            break
        elif srn==2 and n%srn != 0 :
            location = location+1
        srn = srn-1

print n

Upvotes: 2

Slater Victoroff
Slater Victoroff

Reputation: 21914

That break is totally needed. Your code is printing out everything between the 1000th and 1001th prime in the first example. Print doesn't exit, so you're telling your code to print every number it tests while location is 998, but it doesn't actually stop running until location reaches 999.

Upvotes: 1

Related Questions