How To Check If A Number Is Prime In Python

Checking if a number is prime or not is a fundamental concept in computer science. It also finds its applications in cryptography, specifically in the implementation of the RSA algorithm. In this tutorial, we’ll learn how to check if a number is prime using Python.

What is a Prime Number?

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, the first six prime numbers are 2, 3, 5, 7, 11, and 13.


Before we proceed, make sure you have a basic understanding of Python programming and its syntax. If you’re new to Python, you can check out this introduction to Python programming.

Step 1: Take input from a user

First, let’s ask the user to input a number which we will later check if it’s prime or not.

Step 2: Create a Function to Check If a Number is Prime

Now, let’s create a function called is_prime that takes an integer input (which is the number we want to check) and returns a boolean value, True if the number is prime, and False otherwise.

The function starts by checking if the number is less than or equal to 1, in which case it returns False. For numbers greater than 1, it checks for any divisors between 2 and the number itself. If a divisor is found, it returns False, otherwise, it returns True.

Step 3: Check If the Number is Prime and Display the Result

Now, we’ll use the is_prime function to check if the number entered by the user is prime or not, and display the result accordingly.

Full Code:

Sample Output:

Enter a number: 13
13 is a prime number.
Enter a number: 20
20 is not a prime number.


In this tutorial, we learned how to check if a number is prime using Python. We created a function called is_prime, which takes an integer input and returns True if the number is prime, and False otherwise. You can now use this function to create more complex programs involving prime numbers, such as generating prime numbers between two numbers or finding prime factors of a number.