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.
Prerequisites
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.
1 |
number = int(input("Enter a number: ")) |
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.
1 2 3 4 5 6 7 |
def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True |
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.
1 2 3 4 |
if is_prime(number): print(f"{number} is a prime number.") else: print(f"{number} is not a prime number.") |
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True number = int(input("Enter a number: ")) if is_prime(number): print(f"{number} is a prime number.") else: print(f"{number} is not a prime number.") |
Sample Output:
Enter a number: 13 13 is a prime number.
Enter a number: 20 20 is not a prime number.
Conclusion
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.