HomePythonPython Program to Check Prime Number

Python Program to Check Prime Number

In this Python program, we will create a Python script to check whether a given number is prime or not. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.

Problem Statement

Given an input number, we need to determine whether it is a prime number or not.

Python Program to Check Prime Number

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


# Main program
number = int(input("Enter a number: "))

if is_prime(number):
    print(number, "is a prime number.")
else:
    print(number, "is not a prime number.")

How it works

  1. The program defines a function is_prime(num) that takes a number as input and checks if it is prime or not.
  2. If the given number num is less than or equal to 1, the function returns False as numbers less than or equal to 1 are not prime.
  3. The function then loops from 2 to the square root of num (inclusive) and checks if num is divisible by any of these numbers.
  4. If num is divisible by any number in the range, it is not a prime number, and the function returns False.
  5. If no factors are found, the function returns True, indicating that the number is prime.
  6. In the main program, the user is prompted to enter a number. The input is stored in the number variable.
  7. The program then calls the is_prime function with the number as an argument.
  8. If the returned value is True, it means the number is prime, and a corresponding message is printed.
  9. If the returned value is False, it means the number is not prime, and a different message is printed.

Input / output

Python Program to Check Prime Number

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...