check if a number is prime in python

Here's a simple function to check if a number is prime in Python:

main.py
import math

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            return False
    return True
173 chars
10 lines

The function takes an integer n as input, and returns True if it is prime, and False otherwise.

The function first checks if n is less than 2, because 2 is the smallest prime number. If n is less than 2, the function returns False.

Next, the function starts a loop from 2 to the square root of n (rounded up to the nearest integer using math.sqrt() and int() functions). If n is divisible by any number in this range, it is not a prime and the function returns False.

If the loop completes without finding any factors, n is a prime and the function returns True.

gistlibby LogSnag