Using Python to Determine Whether a Number is Prime
A prime number is a natural number greater than 1 that is only divisible by 1 and itself. We can determine whether a number is prime by writing a simple Python function.
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 function
number = 29
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Test 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:
is_primeThe function accepts an integernas a parameter.- First, check
nwhether it is less than or equal to 1; if so, returnFalse, because a prime number must be greater than 1. - Use a
forloop that iterates from 2 tonthe square root of (int(n**0.5) + 1), checknwhether it is divisible by these numbers. - If
nit is divisible by any one of these numbers, then returnFalse, indicatingnit is not a prime number. - If after the loop ends, no number that can divide it
nis found, then returnTrue, indicatingnit is a prime number. - Finally, test the function and output the result.
Output result:
29 是质数Other Extensions
Python3 Examples