Python Check if a Number is a Perfect Square

Document 对象参考手册Python3 Examples

To determine whether a number is a perfect square, we can use mathematical methods. A perfect square is a number that can be expressed as the square of an integer. For example, 16 is a perfect square because it is the square of 4.

Example

import math

def is_perfect_square(n):
    if n < 0:
        return False
    sqrt = math.isqrt(n)
    return sqrt * sqrt == n

# Test
number = 16
if is_perfect_square(number):
    print(f"{number} is a perfect square")
else:
    print(f"{number} is not a perfect square")

Code explanation:

  1. import math: Import Python's math module so as to usemath.isqrtthe function.
  2. def is_perfect_square(n):: Define a functionis_perfect_square, which accepts an integernas a parameter.
  3. if n < 0:: Checknwhether it is negative, because a negative number cannot be a perfect square.
  4. sqrt = math.isqrt(n): Usemath.isqrtthe function to calculatenthe integer square root of
  5. return sqrt * sqrt == n: Check whether the square of the square root equalsn; if so, thennit is a perfect square.
  6. number = 16: Define a test number 16.
  7. if is_perfect_square(number):: Callis_perfect_squarethe function to determine whethernumberit is a perfect square, and output the result.

Output result:

16 是完全平方数

Document 对象参考手册Python3 Examples

Other Extensions