w3resource

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.

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))

Sample Output:

False
True
True

Flowchart:

Python Flowchart: Check if a number is a perfect square

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to check if a given positive integer is a power of four.
Next: Write a Python program to check if an integer is the power of another integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/challenges/1/python-challenges-1-exercise-4.php