2

I wrote a program in Python to generate prime numbers here is the program

def genPrimes(n):
    primes = [2]  # primes generated so far
    last = 3  # last number tried
    while last <= n:        
        for p in primes:
            if last % p == 0 and math.sqrt(p) <= last:
                break
        else:
            primes.append(last)
        last += 2
    return primes

http://codepad.org/d33tsQyT

This program is producing a right answer. If you see the indentation for else: statement it is wrongly placed. if i try to place the else statement in if block interpreter is showing memory error. Can anyone tell why this is happening.

Thanks in advance Maries

1
  • The code was clearly not indented correctly (read: not indented at all). I tried to fix it, so it no longer just raises an exception as soon as you try to load the file or paste the text—but since the actual problem is most likely related to incorrect indentation, the OP really needs to check whether I've got it right. Commented Jan 24, 2013 at 1:30

2 Answers 2

4

The else is actually attached to the for loop, and executes if the program doesn't break out of the loop. In your case, it executes if none of the primes divide into the number, so the number is prime and gets appended to the list.

See also the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks again. I don't know till this i can use else with for loop.
2

It's not placed incorrectly, python is assuming you're using a for-else loop.

From the docs:

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.