Ratnapal Shende
Ratnapal Shende

Reputation: 106

using break and else conditional statements with for loop in list comprehension

How to break for loop in list comprehension based on condition and use else block after it?

here is code that I want to convert in list comprehension:

x=int(input("Enter a number : "))

for i in range(2,x+1):
    for j in range(2,i):
        if i%j==0:
            break
    else:
        print(i)

#this program prints all prime numbers upto x. 

My Attempt :

x=int(input())

def end_loop():
    raise StopIteration
    
prime=list(i for i in range(2,x+1) for j in range(2,i) end_loop() if i%j==0 )

print(prime)

Output :

SyntaxError

Required Output :

All prime numbers upto x

I prefer :

⏺️One liner

⏺️Pure python

Upvotes: 0

Views: 102

Answers (1)

Samwise
Samwise

Reputation: 71424

The trick is to think about what condition the for loop is checking for, and then think about different ways of expressing it. In this case, the loop is testing to see if the i value is divisible by any of the j values:

print([
    i for i in range(2, int(input("Enter a number : ")) + 1)
    if not any(i % j == 0 for j in range(2, i))
])

Note that instead of not any(i % j == 0 ... you could just say all(i % j ...!

Upvotes: 3

Related Questions