What is the sympy.isprime() method in Python?

What is the sympy library?

sympy is library that is used for symbolic mathematics.

pip can be used to install sympy. Refer to the following command:

pip install sympy

The isprime method

The isprime method is used to determine whether the given number is a prime number or not. This method is intended to be used for integers. Any floating-point numbers (limited precision numbers) will result in False. Negative numbers are not considered prime numbers.

Syntax

sympy.isprime(n)

Parameter value

  • n: This is the number that needs to be tested.

Return value

The isprime method returns True if the given positive integer is a prime number. Otherwise, it returns False.

Code example

import sympy
num = 19
print("sympy.isprime(%s) = %s" % (num, sympy.isprime(num)))
num = 19.00
print("sympy.isprime(%s) = %s" % (num, sympy.isprime(num)))
num = -3
print("sympy.isprime(%s) = %s" % (num, sympy.isprime(num)))

Code explanation

  • Line 1: We import the sympy module.
  • Lines 3, 7, and 11: We define different integer values for num.
  • Lines 5, 9, and 14: We check whether num is a prime number or not by using the isprime method.

The output indicates that the isprime method returns False for floating-point numbers and negative numbers.

Free Resources