Python Program to Check if a Number Is a Perfect Square
Beginner · Numbers
A perfect square is a whole number that is the square of another whole number, like 49 = 7 x 7 or 144 = 12 x 12. This program checks whether a number is a perfect square using the whole-number part of its square root.
Program
144 is a perfect square: 12 x 12 = 144
How it works
math.isqrt()gives the square root rounded down to a whole number: 12 for 144, and 12 for 150 as well.- Squaring that root again gives back the number only when the number is a perfect square.
- For other numbers the program shows the perfect squares on either side, like 144 and 169 for 150.
math.isqrt()works only with whole numbers, so it is exact even for huge numbers, where decimal square roots can be rounded wrongly.
Other ways to write it
Using math.sqrt() and is_integer()
16 is a perfect square of 4 20 is not a perfect square 81 is a perfect square of 9 99 is not a perfect square 100 is a perfect square of 10
This is the common textbook method, and it is fine for ordinary numbers; is_integer() checks that the decimal root has nothing after the point.
Perfect squares in a range
Perfect squares from 1 to 100: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Instead of testing every number, this squares 1, 2, 3 and so on until the square passes the end, which is much quicker.
Try it yourself
Change the program to also say whether the number is a perfect cube, like 27 or 64.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises