Q:

Python program to check prime number using object oriented approach

belongs to collection: Python class & object programs

0

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.

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 MethodisPrime() 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to count number of objects created... >>
<< Python program to illustrate constructor inheritan...