Check Perfect Square

Check whether a number is a perfect square.

PythonBeginner
Python
# Program to check if a number is a perfect square

import math

num = int(input("Enter a non-negative integer: "))

if num < 0:
    print("Negative numbers cannot be perfect squares in real numbers.")
else:
    root = int(math.sqrt(num))
    if root * root == num:
        print(num, "is a perfect square")
    else:
        print(num, "is not a perfect square")

Output

Enter a non-negative integer: 16
16 is a perfect square

We take the integer square root and square it back. If root * root equals the original number, it is a perfect square.