Home > Back-end >  Converting List Comprehension with if all conditions to Loops in Python
Converting List Comprehension with if all conditions to Loops in Python

Time:10-07

I'm trying to convert a list comprehension I have as part of a course I'm doing to a for loop but keep bumping into errors/mistakes. I'm using an if all in the list comprehension which I can't work out what ordering/how to incorporate this into a for loop.

My code is:

def count_primes(num):
    prime = [x for x in range(2,num) if all (x % y != 0 for y in range (2,x))]
    return len(prime)

I've currently tried (but not working)

def count_primes(num):
    primes = [2]
    for x in range(3,num):
        for y in range(2,x):
            if x % y == 0:
                break
            else:
                primes.append(x)
                break

    return len(primes)

CodePudding user response:

This should do the trick

primes = [2]
for x in range(3, num):
    all_check = True
    for y in range(2, x):
        if x % y == 0:
           all_check = False
            break
    if all_check:
        primes.append(x)

You weren't actually looping all the way through in your example to check the value.

  • Related