Iterating prime numbers in Python

Problem:

Using Python you want to iterate through consecutive prime numbers

Solution:

You can use gmpy2‘s next_prime() to do this:

import gmpy2

def primes(start=2):
    n = start
    while True:
        n = gmpy2.next_prime(n)
        yield n

# Usage example 1
for prime in primes():
    print(prime)

# Usage example 2
for i, prime in enumerate(primes()):
    print("The {}th prime number is {}".format(i, prime))