3

My goal is to make a program that prints onscreen all of the prime numbers it can find, however I have this issue where the while loop runs only once, instead of repeating forever.

def isPrime(num):
    if num < 2:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False
    i = 3
    while i * i <= num:
        if num % i == 0:
            return False
            i += 2

x = 1
while True:
    x += 1
    if isPrime(x):
        print (x)

I also have tried adding print("You can see this.") at the very end of the code, and it runs, but only once. I'm sure it's a common mistake, since Python is very strict on indentation, but could you guys help me discover it? Thanks in advance.

2 Answers2

2

The i +=2 is indented too deep, the inner loop never quits.

It should read

while i * i <= num:
    if num % i == 0:
        return False
    i += 2

Otherwise i never increases and the loop goes on and on and on.

user2722968
  • 13,636
  • 2
  • 46
  • 67
2

You need to return True at the very end, after and outside the final loop. Otherwise the function ends without explicitly returning anything, so it implicitly returns None which is interpreted as false.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89