Perfect square in Python
In this post, you will learn how to find the perfect square using the Python programming language.
A perfect square is a number that is generated by multiplying two equal integers by each other. Or, a perfect square is a number, from a given number system, that can be expressed as the square of a number from the same number system. 16 is a perfect square because 42 is 16. 25 is also a perfect square because 52 is 25.
In Python programming, there are different ways of determining if a number is perfect or not. Here, we have mentioned most of them.
Python program to check a number is perfect square
In the given Python program, first we import the math library into our program, then we take the input from the user and convert it to an integer. The math.sqrt() method is used to calculate the square root of a number. The result is stored in the root variable. Next, we check whether the integer value of the square of the root+0.5 is equal to the number itself. If it evaluates to true, then the number is a perfect square; otherwise, it is not.
import math
# Taking the number input from user
num = int(input("Enter the Number: "))
root = math.sqrt(num)
if int(root + 0.5) ** 2 == num:
print(num, "is a perfect square.")
else:
print(num, "is not a perfect square.")
Enter the Number: 25
25 is a perfect square.
Enter the Number: 30
30 is not a perfect square.
Enter the Number: 64
64 is a perfect square.
Python program to check a number is perfect square without finding square root
In the given Python program, we check if a number is perfect square without finding the square root.
# Python program to check if a number is
# perfect square without finding square root
def chkPerfectSquare(n) :
i = 1
while(i * i<= n):
if ((n % i == 0) and (n / i == i)):
return True
i = i + 1
return False
# Driver code
if __name__ == "__main__" :
num = int(input("Enter the Number: "))
if (chkPerfectSquare(num)):
print(num, "is a perfect square.")
else :
print(num, "is not a perfect square.")
Output of the above code:
Enter the Number: 25
25 is a perfect square.
Enter the Number: 81
81 is a perfect square.
Enter the Number: 35
35 is not a perfect square.
Related Articles
Convert Python list to numpy arrayConvert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary