Using Python to Determine Whether a Number is Prime

Document 对象参考手册Python3 Examples

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

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 a prime number must be greater than 1.
  3. Use aforloop that iterates from 2 tonthe square root of (int(n**0.5) + 1), checknwhether it is divisible by these numbers.
  4. Ifnit is divisible by any one of these numbers, then returnFalse, indicatingnit is not a prime number.
  5. If after the loop ends, no number that can divide itnis found, then returnTrue, indicatingnit is a prime number.
  6. Finally, test the function and output the result.

Output result:

29 是质数

Document 对象参考手册Python3 Examples

Other Extensions