Python Check Whether a Number Is Prime
A prime number is a natural number greater than 1 that is divisible only by 1 and itself. We can write a 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
)
:
(
f
"{number} is a prime number"
)
else
:
(
f
"{number} is not a prime number"
)
Code analysis:
is_primeThe function takes an integernas its argument.- First check whether
nCheck whether it is less than or equal to 1; if so, returnFalse, because a prime number must be greater than 1. - Use a
forThe loop iterates from 2 tonthe square root ofint(n**0.5) + 1), checkingnwhether it is divisible by any of these numbers. - If during the loop we find that
nis divisible by one of them, returnFalse, meaningnis not a prime number. - If after the loop no number that divides
nis found, returnTrue, meaningnis a prime number. - Finally, test the function and print the result.
Output result:
29 是质数
Python3 Examples