A natural number greater than 1, except 1 and itself, cannot be divisible by other natural numbers (prime numbers) (2, 3, 5, 7, etc.), in other words, the number has no other factor other than 1 and itself.
First, let's take the first traditional judgment:
def handlernum (num):
# Prime number greater than 1
if num > 1:
# See if there are other factors
for I in range (2, num//2+1):
if (num% i) = = 0:
print (num, "not prime number")
Break
Else:
print (num, "is prime")
# If the number entered is less than or equal to 1, not prime
Else:
print (num, "not prime number")
if __name__ = = ' __main__ ':
# User enters a number
num = Int (input ("Please enter a number:"))
# Call Function processing method
handlernum (num)
in fact, the else and if in the above loop are not paired, but with for side, Of course, the for and else collocation is not uncommon, and slowly experience, the meaning of this code is that when the for in the conditions are not satisfied, will be executed else inside the code. The above is we follow the traditional thinking to solve problems, in fact, there is a faster, more simple way to solve problems, that is, the use of real or false to judge.
#处理函数
def isprime (num):
#根据质数的定义, it must be greater than 0
if num = = 1:
return False
#循环需要判断的次数
for I in range (2, num//2 + 1):
#如果该数有其他的因子返回False, that is, not prime.
if num% i = = 0:
return False
return True
If __name__ = = ' __main__ ':
#输入一个数字
num = eval (input ("Please enter a number to determine if it is prime:"))
#调用方法 (returns False if the prime number is true), prints the result
print (IsPrime (num))
The two methods are roughly the same, but this gives us a new way to solve the problem.
Source: http://www.cnblogs.com/KBe24Love/p/7750418.html
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Python determines whether it is a prime or prime number