Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Number Is a Perfect Square

Python Check Whether a Number Is a Perfect Square

Document Object Reference Manual Python3 Examples

A perfect square is an integer that can be expressed as the square of another integer. For example, 1, 4, 9, 16 and so on are perfect squares. We can determine whether a number is a perfect square using a mathematical approach.

Example

import

math

def

is_perfect_square

(

n

)

:

   

if

n

<

0

:

       

return

False

    sqrt

=

math

.

isqrt

(

n

)

   

return

sqrt * sqrt

==

n

Testing

number

=

16

if

is_perfect_square

(

number

)

:

   

print

(

f

"{number} is a perfect square"

)

else

:

   

print

(

f

"{number} is not a perfect square"

)

Code analysis:

  1. import math: Import Python's math module in order to use math.isqrt function in Vue 3.
  2. def is_perfect_square(n):: Define a function is_perfect_square, used to determine whether a number is a perfect square.
  3. if n < 0:: If the input number is negative, return False, because a negative number cannot be a perfect square.
  4. sqrt = math.isqrt(n): When using math.isqrt The function computes n the integer square root of the number.
  5. return sqrt * sqrt == n: If the square of the square root equals the original number n, return True; otherwise, returns False。
  6. number = 16: Define a test number 16。
  7. if is_perfect_square(number):: Calling is_perfect_square Call the function to determine whether 16 is a perfect square, and print the corresponding message based on the result.

Output result:

16 是一个完全平方数

Document Object Reference Manual Python3 Examples