Python determines whether the instance is a prime number or a prime number. python Prime Number
A natural number greater than 1 cannot be divisible by other natural numbers (prime numbers) except 1 and itself (2, 3, 5, 7, etc ), in other words, this number has no other factors except 1 and itself.
First, let's start with the traditional judgment ideas:
Def handlerNum (num): # prime number greater than 1 if num> 1: # check whether there are other factors for I in range (2, num // 2 + 1 ): if (num % I) = 0: print (num, "not a prime number") break else: print (num, "is a prime number ") # if the input number is less than or equal to 1, it is not a prime number. else: print (num, "not a prime number") if _ name _ = '_ main __': # enter a number num = int (input ("enter a number:") # Call the function processing method handlerNum (num)
In fact, the else and if in the above loop are not in pairs, but are side by side with for. Of course, it is not uncommon for the combination of for and else. It will be realized slowly. The meaning of this Code is, when none of the conditions in for are met, the code in else is executed. The above is how we solve the problem according to the traditional ideas. In fact, there is a faster and simpler way to solve the problem, that is, to use the true or false to judge.
# Handler function def IsPrime (num): # according to the definition of the prime number, it must be greater than 0 if num = 1: return False # number of cycles to be judged for I in range (2, num // 2 + 1): # if the number has other factors, False is returned, that is, if num % I = 0: return False return Trueif _ name _ = '_ main _': # enter a number num = eval (input ("enter a number to determine whether it is a prime number: ") # Call the method (if it is a prime number, return True; otherwise, return False), print the result print (IsPrime (num ))
These two methods are similar in general, but they provide us with a new way to solve the problem in the future.
The Python example above to determine whether it is a prime number or a prime number is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.