Python program to check prime number

Description: Write a Python program to check whether a number is prime.

Rules and hints:

  • A prime number is greater than 1 and has no divisor other than 1 and itself.
  • You only need to test divisors up to the square root of the number.

Python program to check a prime number

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

for n in (2, 15, 17, 1):
    if is_prime(n):
        print(n, "is prime")
    else:
        print(n, "is not prime")

Output:

Tutorials Class - Output Window

2 is prime
15 is not prime
17 is prime
1 is not prime

How it works

  • Numbers below 2 are not prime.
  • For 15 the loop tests 2 and 3. Since 15 % 3 == 0, it returns False.
  • For 17 the loop tests 2, 3 and 4. None divides it, so it is prime.
  • As soon as one divisor is found, return False ends the function early.

Learn more about the similar topics:
Tutorials
Python Conditional Statements
Python While Loop
Python for loop
Python Jump Statements
Exercises & Assignments
Python program to check even or odd number
Python program to find the largest of three numbers
Python program to check leap year
Python program to print multiplication table
Python program to find factorial of a number
Python program to print Fibonacci series
Python program to check prime number
Interview Questions & Answers
No Content Found.