How to judge prime numbers in Python
Python how to judge prime numbers, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this can learn, I hope you can gain something.
code implementation
#User inputs a number num = int(input("Please enter a number: "))#Prime greater than 1if num > 1: #View factors for i in range(2, num): if (num % i) == 0: print(num, "not prime") print(i, "multiplied by", num // i, "yes", num) break else: print(num, "is prime")#If the number entered is less than or equal to 1, it is not prime else: print(num, "not prime")
Code Run Results:
Please enter a number: 55
55 is not a prime.
5 times 11 is 55.
program analysis
#The Python program above checks whether the number entered by the user is prime
Lines 4 and 14 are a pair, lines 6 and 11 are a pair.
The execution order of for else is as follows: when the iteration object completes all iterations and the iteration object is empty at this time, if there is an else clause, the else clause will be executed, and if there is no else clause, the subsequent code will continue to be executed; if the iteration object exits the iteration prematurely for some reason (such as with the break keyword), the else clause will not be executed, and the program will directly skip the else clause and continue to execute the subsequent code.
Program line 2: prompt the user to enter a number, the user input number assigned to num
Line 4 of the program: judge whether the number input by the user is greater than 1 through if, if greater than 1, continue to execute the statements after for, otherwise the program executes line 14, and then line 15, the output is not prime
Line 6 of the program: for i in range(2,num), this statement identifies i in turn from 2 to num-1 loop integer
Line 7 of the program: judge by if (num % i) == 0, if num can be divided by any number from 2 to num-1, then num is not a prime, otherwise it is a prime
Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.