a function that calculates the first prime numbers in python

Here's a function in Python that calculates the first n prime numbers:

main.py
def get_primes(n):
    primes = []
    num = 2
    while len(primes) < n:
        is_prime = True
        for i in range(2, num):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)
        num += 1
    return primes
301 chars
14 lines

The function starts with an empty list called primes, and an initial value of num = 2, which is the first prime number. We then use a while loop to keep finding prime numbers until we have n primes.

Inside the loop, we set a flag variable is_prime to True, which we assume for each value of num. We then use a for loop to iterate through every number from 2 to num-1, checking if num is divisible by any of them (if it is, then num is not prime). If we find that num is divisible by any of those numbers, we set is_prime to False and break out of the loop.

If is_prime is still True after the for loop finishes, it means that num is a prime number, so we add it to the primes list. Finally, we increment num by 1 and continue the loop.

Once we have n primes in the primes list, we return it from the function.

To use this function, you can simply call it with the number of primes you want to find, like this:

main.py
print(get_primes(10))
# Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
69 chars
3 lines

gistlibby LogSnag