Python program to check prime number using object oriented approach

Here, we are going to learn how to check whether a given number is a prime number or not using class & objects (object-oriented approach)?
Submitted by Ankit Rai, on July 19, 2019

Problem statement

This program will check whether a given number is Prime or Not, in this program we will divide the number from 2 to square root of that number, if the number is divided by any number in b/w then the number will not be a prime number.

Solution approach

We are implementing this program using the concept of classes and objects.

Firstly we create the Class with Check name with 1 attributes ('number') and 2 methods, the methods are:

  1. Constructor Method: This is created using __init__ inbuilt keyword. The constructor method is used to initialize the attributes of the class at the time of object creation.
  2. Object Method: isPrime() is the object method, for creating object method we have to pass at least one parameter i.e. self keyword at the time of function creation.

Secondly, we have to create an object of this class using a class name with parenthesis then we have to call its method for our output.

Below is the implementation of the program,

Python program to check prime number using object oriented approach

# 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

Python class & object programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.