Write a python program to check prime number using object oriented approach


This Python program defines a class PrimeChecker that can be used to check whether a given number is prime or not. Here's an explanation of how the program works:

  • The PrimeChecker class is defined, which takes an integer num as a parameter when an instance of the class is created.
  • The __init__ method is the constructor for the class and initializes the instance variable self.num with the value passed to it.
  • The is_prime method is used to determine whether the number stored in self.num is prime or not. It follows these steps:
    • If the number is less than or equal to 1, it returns False, as prime numbers are defined as positive integers greater than 1.
    • If the number is equal to 2, it returns True, as 2 is the only even prime number.
    • If the number is even (i.e., divisible by 2), it returns False since prime numbers (other than 2) are always odd.
    • It then checks for divisibility of the number from 3 up to the square root of the number. It does this in a loop with a step of 2 to check only odd numbers, as even numbers greater than 2 cannot be prime. If it finds any divisor in this range, it returns False, indicating that the number is not prime.
    • If none of the above conditions are met, it returns True, indicating that the number is prime.
  • The program then takes user input for a number by using input() and converts it to an integer using int(). This number is stored in the num variable.
  • An instance of the PrimeChecker class is created with the user's input, and it is assigned to the checker variable.
  • The is_prime method of the checker instance is called. If the method returns True, it means that the number is prime, and a message stating that the number is prime is printed. If the method returns False, it means the number is not prime, and a corresponding message is printed.

Source Code

class PrimeChecker:
    def __init__(self, num):
        self.num = num
 
    def is_prime(self):
        if self.num <= 1:
            return False
        if self.num == 2:
            return True
        if self.num % 2 == 0:
            return False
 
        # Check for divisibility from 3 to the square root of the number
        for i in range(3, int(self.num**0.5) + 1, 2):
            if self.num % i == 0:
                return False
 
        return True
 
num = int(input("Enter a Number : "))
 
checker = PrimeChecker(num)# Create an instance of PrimeChecker
 
if checker.is_prime():
    print(f"{num} is a Prime Number")
else:
    print(f"{num} is not a Prime Number")

Output

Enter a Number : 71
71 is a Prime Number

Example Programs