Python Determine if a Number is Prime

Document 对象参考手册Python3 Examples

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")

Code analysis:

  1. is_primeThe function accepts an integernas a parameter.
  2. First checknwhether it is less than or equal to 1. If so, returnFalse, because prime numbers must be greater than 1.
  3. Use aforloop to iterate from 2 tonthe square root ofint(n**0.5) + 1), checknwhether it can be divided by these numbers.
  4. If during the loop it is found thatncan be divided by a certain number, then returnFalse, indicating thatnis not a prime number.
  5. If after the loop ends no number that dividesnis found, then returnTrue, indicating thatnis a prime number.
  6. Finally, test the function and output the result.

Output result:

29 是质数

Document 对象参考手册Python3 Examples

Other extensions