Whereas the loop, which should be infinite, freezes after the first loop

My goal is to make a program that prints to the screen all the primes it can find, however I have this problem where the while loop only runs once, rather than 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 tried adding print("You can see this.")

at the very end of the code and it runs, but only once. I'm sure this is a common mistake as Python is very strict about indentation, but could you guys help me open it up? Thanks in advance.

+3


source to share


2 answers


i +=2

is indented too deep, the inner loop never ends.

He must read



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

      

Otherwise it i

never increases and the cycle goes on and on.

+2


source


You need it 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.



+2


source







All Articles