Python Determine if a Number is Prime
A prime number is a natural number greater than 1 that can only be divided by 1 and itself. We can write a Python function to determine whether a number is a prime number.
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 prime numbers must be greater than 1. - Use a
forloop to iterate from 2 tonthe square root ofint(n**0.5) + 1), checknwhether it can be divided by these numbers. - If during the loop it is found that
ncan be divided by a certain number, then returnFalse, indicating thatnis not a prime number. - If after the loop ends no number that divides
nis found, then returnTrue, indicating thatnis a prime number. - Finally, test the function and output the result.
Output result:
29 是质数Other extensions
Python3 Examples