python判断素数程序_使用面向对象方法检查素数的Python程序
python判斷素數(shù)程序
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.
該程序?qū)z查給定數(shù)字是否為質(zhì)數(shù) ,在此程序中,我們將數(shù)字從2除以該數(shù)的平方根,如果該數(shù)字除以b / w中的任何數(shù)字,則該數(shù)字將不是質(zhì)數(shù)數(shù)。
We are implementing this program using the concept of classes and objects.
我們正在使用類和對象的概念來實現(xiàn)該程序。
Firstly we create the Class with Check name with 1 attributes ('number') and 2 methods, the methods are:
首先,我們使用Check名稱創(chuàng)建具有1個屬性( 'number' )和2個方法的Class,這些方法是:
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.
構(gòu)造方法 :這是使用__init__內(nèi)置關(guān)鍵字創(chuàng)建的。 構(gòu)造函數(shù)方法用于在創(chuàng)建對象時初始化類的屬性。
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.
對象方法 : isPrime()是對象方法,要創(chuàng)建對象方法,我們必須在函數(shù)創(chuàng)建時傳遞至少一個參數(shù),即self關(guān)鍵字。
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.
其次,我們必須使用帶有括號的類名來創(chuàng)建此類的對象,然后必須為其輸出調(diào)用其方法。
Below is the implementation of the program,
下面是該程序的實現(xiàn),
Python代碼檢查給定數(shù)字是否為質(zhì)數(shù) (Python code to check whether a given number is prime or not)
# Define a class for Checking prime number class Check :# Constructordef __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 Falseif num % i == 0 :return False# if number is prime then return Truereturn True# Main code if __name__ == "__main__" :# input numbernum = 11# make an object of Check classcheck_prime = Check(num)# method callingprint(check_prime.isPrime())num = 14check_prime = Check(num)print(check_prime.isPrime())Output
輸出量
True False翻譯自: https://www.includehelp.com/python/program-to-check-prime-number-using-object-oriented-approach.aspx
python判斷素數(shù)程序
總結(jié)
以上是生活随笔為你收集整理的python判断素数程序_使用面向对象方法检查素数的Python程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java PipedOutputStre
- 下一篇: Java ProcessBuilder