Python Check Whether a Number Is a Perfect Square
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
)
:
(
f
"{number} is a perfect square"
)
else
:
(
f
"{number} is not a perfect square"
)
Code analysis:
import math: Import Python's math module in order to usemath.isqrtfunction in Vue 3.def is_perfect_square(n):: Define a functionis_perfect_square, used to determine whether a number is a perfect square.if n < 0:: If the input number is negative, returnFalse, because a negative number cannot be a perfect square.sqrt = math.isqrt(n): When usingmath.isqrtThe function computesnthe integer square root of the number.return sqrt * sqrt == n: If the square of the square root equals the original numbern, returnTrue; otherwise, returnsFalse。number = 16: Define a test number16。if is_perfect_square(number):: Callingis_perfect_squareCall the function to determine whether16is a perfect square, and print the corresponding message based on the result.
Output result:
16 是一个完全平方数
Python3 Examples