vendredi 31 août 2018

Python IF Else and For loop workflow

I am trying to write a function that returns the number of prime numbers that exist up to and including a given number.

Initially this was my code:

def count_primes(num):

prime = [2]

x = 3

if num < 2:
    return 0

while x <= num:
    for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
        else:
            prime.append(x)
            x += 2

return len(prime)

How ever I realise this code will run forever because of the following line of code:

for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
        else:
            prime.append(x)
            x += 2

Can anyone help to explain to me why will this end up with an infinite loop compared to the following code?

for y in prime:
        if x%y == 0:
            print('not prime')
            x+=2
            break
else:
    prime.append(x)
    x += 2

Aucun commentaire:

Enregistrer un commentaire