简体   繁体   中英

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

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 ... !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM