Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Use Python to Check Whether a Number Is Prime

Use Python to Check Whether a Number Is Prime

Document Object Reference Manual Python3 Examples

A prime number is a natural number greater than 1 that is divisible only by 1 and itself. We can write a simple Python function to determine whether a number is prime.

Example

def

is_prime

(

n

)

:

   

if

n

<=

1

:

       

return

False

   

for

i

in

range

(

2

,

int

(

n**

0.5

)

1

)

:

       

if

n % i

==

0

:

           

return

False

   

return

True

Test the function

number

=

29

if

is_prime

(

number

)

:

   

print

(

f

"{number} is a prime number"

)

else

:

   

print

(

f

"{number} is not a prime number"

)

Code analysis:

  1. is_prime The function takes an integer n as its argument.
  2. First check whether n Check whether it is less than or equal to 1; if so, return False, because a prime number must be greater than 1.
  3. Use a for The loop iterates from 2 up to n the square root ofint(n**0.5) + 1), checking n whether it is divisible by any of these numbers.
  4. If both the n is divisible by any of these numbers, return False, meaning n is not a prime number.
  5. If after the loop no number that divides n is found, return True, meaning n is a prime number.
  6. Finally, test the function and print the result.

Output result:

29 是质数

Document Object Reference Manual Python3 Examples