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

To determine whether a number is a perfect square, we can use a mathematical approach. 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 4 squared.

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, which takes an integer n as its argument.
  3. if n < 0:: Check whether n Check whether it is negative, 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: Check whether the square of the square root is equal to n, if so, then n is a perfect square.
  6. number = 16: Define a test number, 16.
  7. if is_perfect_square(number):: Calling is_perfect_square Call the function to determine whether number is a perfect square and print the result.

Output result:

16 是完全平方数

Document Object Reference Manual Python3 Examples