3

I've seen many different ways to break out of two nested loops at once, but what is the quickest and simplest for my code?

primes = [2]
for a in range(3, 500, 2):
    for b in range(2, int(a ** 0.5 + 0.5)):
        if a % b != 0:
            primes.append(a)
        if a % b == 0:
            [x for x in primes if x != a]
            # double break
awsomeguy
  • 191
  • 3
  • 11
  • 1
    I'm not entirely sure what you're trying to achieve with this code, but I'm pretty sure what you've written doesn't do it. The list comprehension doesn't do anything, and the list called 'primes' won't just include primes. Consider writing a function `is_prime(p)` that tests a single value for being a prime and then you won't need to break from nested loops. – Duncan Mar 02 '13 at 12:45
  • I know @Duncan, I've realised now but thanks for the answers anyway – awsomeguy Mar 02 '13 at 12:52
  • LewisC, I have an answer for you concerning the algorithm of your code, not the question of double breaking out of nested loops. But this thread has been closed. How could I post it to you, please ? – eyquem Mar 03 '13 at 22:38

3 Answers3

3

Put the loops in a function and use the return keyword:

def func(primes):
    for a in range(3, 500, 2):
        for b in range(2, int(a ** 0.5 + 0.5)):
            if a % b != 0:
                primes.append(a)
            if a % b == 0:
                [x for x in primes if x != a]
                return

primes = [2]
func(primes)

This tends to be a good thing when it makes the programmer write modularized code.

Nadir Sampaoli
  • 5,437
  • 4
  • 22
  • 32
0

Refactor the double loop as a function and use return to break out.

infrared
  • 3,566
  • 2
  • 25
  • 37
0

If you don't want to use a function you can use a variable. Here it is flag

  primes = [2]
    flag = 0
    for a in range(3, 500, 2):
        for b in range(2, int(a ** 0.5 + 0.5)):
            if a % b != 0:
                primes.append(a)
            if a % b == 0:
                [x for x in primes if x != a]
                flag = 1
                break
        if flag:
            break
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38