Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to check if a number is a square in just 5 lines of Python!
For the video version of checking if a number is a square in Python:
So far, this series has covered a lot of posts using the random
library like the Random Number Generator, the Dice Roll Simulator, and the Password Generator. This is the first episode of Super Simple Python that is under 10 lines of code. We’re going to do this with the help of the math
library.
Check if a Number is Square
There are many ways to check if a number is a square in real life. What’s the easiest way? Take a square root and check if the square root is an integer or not. Luckily, we can just use the sqrt
function from the math
Python library to do that. We don’t even have to know how to do the actual math for this program.
We’ll start off our program by importing the math
library. The math
library is native to Python so we don’t have to install it. Next, let’s create a function to check if a number is a square or not. The function will take one parameter, num
, which we expect to be an integer. This is the cool part. We can handle all the logic in one line using the math
library. We use the sqrt
function to get the square root of the number, and then we call the is_integer()
function on that to check if the result is an integer. If the result is an integer, we return True. If it’s not, then we return False
by default. Note that we can also choose to use an else
statement to return False, but we don’t need to.
import math
def is_square(num: int):
if math.sqrt(num).is_integer():
return True
return False
print(is_square(20))
print(is_square(100))
print(is_square(625))
print(is_square(1337))
print(is_square(2025))
If we test the above numbers, 20, 100, 625, 1337, and 2025 we should get False, True, True, False, True as shown in the image below:
I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.
