Question: I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability.

Thanks

```
from math import sqrt

def isprime(n):
  if n ==2:
    return True
  if n % 2 ==0 : # evens
    return False

  max = int(sqrt(n))+1 #only need to search up to sqrt n 
  i=3
  while i <= max: # range starts with 3 and for odd i
    if n % i == 0:
      return False
    i+=2

  return True

reqprimes = int(input('how many primes: '))
primessofar = 0
currentnumber = 2
while primessofar < reqprimes:

  result = isprime(currentnumber)

  if result:
     primessofar+=1
     print currentnumber
     #print '\n'

  currentnumber += 1

```

Answer: 
Firstly, you should not assign max to a variable as it is an inbuilt function used to find the maximum value from an iterable. Also, that entire section of code can instead be written as

```
for i in xrange(3, int(sqrt(n))+1, 2):
    if n%i==0: return False

```

Also, instead of defining a new variable result and putting the value returned by isprime into it, you can just directly do

```
if isprime(currentnumber):

```
Translated from the brilliant guys at [stacktrace.it](http://stacktrace.it/2008/01/progetto-eulero-problema-3/) (Daniele Varrazzo, specifically), this version takes advantage of [a binary min-heap](http://en.wikipedia.org/wiki/Binary_heap) to solve this problem:

```
from heapq import heappush, heapreplace

def yield_primes():
    """Endless prime number generator."""

    # Yield 2, so we don't have to handle the empty heap special case
    yield 2

    # Heap of (non-prime, prime factor) tuples.
    todel = [ (4, 2) ]

    n = 3
    while True:
        if todel[0][0] != n:
            # This number is not on the head of the heap: prime!
            yield n
            heappush(todel, (n*n, n))   # add to heap

        else:
            # Not prime: add to heap
            while todel[0][0] == n:
                p = todel[0][1]
                heapreplace(todel, (n+p, p))
                # heapreplace pops the minimum value then pushes: 
                # heap size is unchanged

        n += 1

```

*This code isn't mine and I don't understand it fully ([but the explaination is here](http://stacktrace.it/2008/01/progetto-eulero-problema-3/) :) ), so I'm marking this answer as community wiki.*