w3resource logo


Python Exercises

Python Challenges: Check if a number is a perfect square

Python Challenges - 1: Exercise-4 with Solution

Write a Python program to check if a number is a perfect square.

Input : 9
Output : True

Explanation :

Python: Find perfect square

Sample Solution :-

Python Code :

def is_perfect_square(n):
    x = n // 2
    y = set([x])
    while x * x != n:
        x = (x + (n // x)) // 2
        if x in y: return False
        y.add(x)
    return True

print(is_perfect_square(8))
print(is_perfect_square(9))
print(is_perfect_square(100))

Output :

False                                                                   
True                                                                    
True

Flowchart:

Python Flowchart: Check if a number is a perfect square

Python Code Editor:

def is_perfect_square(n):
    x = n // 2
    y = set([x])
    while x * x != n:
        x = (x + (n // x)) // 2
        if x in y: return False
        y.add(x)
    return True

print(is_perfect_square(8))
print(is_perfect_square(9))
print(is_perfect_square(100))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program