python3 determines whether the input number is a prime number

First, we need to define what is a prime number?

  Primes: also known prime number, means greater than a natural number 1, in addition to 1 and the number itself, the other can not be a natural number divisible (also defined as only a factor of two the number of the number itself).

  For example: In addition to 5 --- 5 except be 1 or an integer, the third can no longer find a natural number divisible up. So 5 is a prime number.

So, how to judge if the program it is not a prime number?

Realization of ideas:

1  need to enter a number assigned to it is determined and Number
 2 determine the number of symbols does not meet the "Number> 1 " rule, if it does not meet the end of the cycle, go to meet the test if not a prime number is
 3  , if to be Number 1 any positive integer between one can determine not to be divisible by a prime number, to the end of cycle
 4 if all positive integers between 1 and are not divisible number, it is a prime number, to the end of the cycle

With the idea, let's look at how to achieve specific:

Number The = int (INPUT ( " Enter a number: " ))          # enter a positive integer, and assigned to the Number The 
IF Number The>. 1:                                  # whether positive integer determines whether the input is greater than. 1 
    for I in Range (2, Number The):                   # cyclic taken 2 to number-1 positive integer i 
        IF number% i == 0:                     # the number of i modulo, if the remainder is 0, it may be divisible 
            Print ( " digital% s is not prime " % number)
             BREAK                               # is not a prime number, the loop ends 
    the else :
         Print ( " digital% s is a prime number "Number The%)            # otherwise, it is a prime number, print the results 
the else :
     Print ( " digital input is less than 1, not legal " )

For this code, there is a place to note:

  and if there is no else it is a pair, but side by side, and for, and for else got together, make up a pair of our common or if ... else ... if ... elif ... else and so on, but in fact can be and for else with the emergence, in this code, when a next iteration of the results of the remainder is 0, break into force, that the cycle is over. Lose it all, it is the third point of the top ideas.

Finally, look at the results of different situations:

Please enter a number: 17 
numeral 17 is a prime number 

, enter a number: -10 
entering numbers smaller than 1, not legal 

enter a digit: . 9 
9 are not prime numbers

 

 

Guess you like

Origin www.cnblogs.com/Zhan-W/p/11519708.html