How to Create a Prime Number Function in Python?

Estimated read time 2 min read

You can create a prime number function in Python using a simple algorithm that checks if a number is divisible only by 1 and itself. Here’s an example code snippet:

def prime_numbers(n):
    primes = []
    for num in range(2, n+1):
        for i in range(2, int(num**0.5) + 1):
            if (num % i) == 0:
    return primes

# Example usage:

In this example, we define a prime_numbers function that takes a positive integer n as input and returns a list of all prime numbers up to n.

We first initialize an empty list primes to store the prime numbers. We then use a nested for loop to iterate over all numbers from 2 up to n. For each number, we check if it is divisible by any integer other than 1 and itself. We use the int() and ** operators to calculate the square root of the number.

If we find a divisor of the number other than 1 or itself, we break out of the inner loop and move on to the next number. If we have checked all possible divisors up to the square root of the number without finding any factors, we can conclude that the number is prime and append it to the primes list.

Finally, we return the primes list containing all prime numbers up to n.

We test the function by calling prime_numbers(20) to print all prime numbers up to 20. You can modify this code to work with larger ranges of numbers or to input the number range from the user.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply