find the nth prime number in python

Here's a Python function that returns the nth prime number:

main.py
def nth_prime(n):
    """
    Returns the nth prime number.
    """
    prime_list = [2]  # List of prime numbers
    num = 3  # Current number being evaluated
    while len(prime_list) < n:
        # Check if current number is prime
        is_prime = True
        for prime in prime_list:
            if num % prime == 0:
                is_prime = False
                break
        if is_prime:
            prime_list.append(num)
        num += 2  # Only odd numbers can be prime (except 2)
    return prime_list[-1]  # Return the nth prime number
553 chars
18 lines

The function first initializes a list, prime_list, with the first prime number, 2. It then starts iterating through odd numbers, evaluating each one to check if it's prime. If a number is prime, it's added to prime_list. The iteration continues until prime_list has n prime numbers. Finally, the function returns the last element (prime_list[-1]) which is the nth prime number.

gistlibby LogSnag