Python program to check prime number using the object-oriented approach

This program will check whether a given number is Prime or Not, in this program we will separate the number from 2 to square base of that number, in the event that the number is isolated by any number in b/w then the number won’t be a prime number.

We are executing this program utilizing the idea of classes and objects.

Right off the bat we make the Class with Check name with 1 trait (‘number’) and 2 methods, the methods are:

Constructor Method: This is made utilizing init inbuilt watchword. The constructor method is utilized to introduce the properties of the class at the hour of object creation.

Object Method: isPrime() is the object method, for making object method we need to go at any rate one parameter for example self catchphrase at the hour of capacity creation.

Besides, we need to make an object of this class utilizing a class name with enclosure then we need to call its method for our yield.

The following is the usage of the program,

Python code to check whether a given number is prime or not

# Define a class for Checking prime number
class Check :
    
    # Constructor
    def __init__(self,number) :
        self.num = number
       
    # define a method for checking number is prime or not 
    def isPrime(self) :
        
        for i in range(2, int(num ** (1/2)) + 1) :
            
            # if any number is divisible by i 
            # then number is not prime
            # so return False
            if num % i == 0 :
                return False
        
        # if number is prime then return True
        return True


# Main code 
if __name__ == "__main__" :
    
    # input number
    num = 11
    
    # make an object of Check class
    check_prime = Check(num)
    
    # method calling
    print(check_prime.isPrime())
    
    num = 14
    check_prime = Check(num)
    print(check_prime.isPrime())        

Output

True
False

Leave a Comment

error: Alert: Content is protected!!