catmum
catmum

Reputation: 35

How to return exact value of square root in python?

If I input 25, answer should be 5 as integer. If I input 24 answer should be 4.898989486 float. Is this possible to do in python?

Context-: I need to write a code to find next perfect square.

import math

def find_next_square(sq):
    # Return the next square if sq is a square, -1 otherwise
    sq2=math.sqrt(sq)
    xyz=isinstance(sq2, int)
    if (xyz==True):
        print("Is perfect square")
        nextsq=sq+1
        print("Next perfect square=",nextsq**2)
    else:
        print("Not perfect square")
        return -1

n=int(input("Enter an integer"))
find_next_square(n)

Here is the code. For 25, this returns, sq2=5.0 hence it returns Not perfect square. I need a way to make this return perfect square.

Desired behaviour-:

If I put 25 as n. It should return it as perfect square and return 36.

Specific problem-:

Problem here is

import math

sq=25
sq2=math.sqrt(sq)
print(sq2)
xyz=isinstance(sq2, int)
print(xyz)

Even for sq=25, it will return it as float. That math.sqrt() function. It changes the whole game for me.

Shortest code necessary to reproduce the problem-:

import math

sq=24
sq2=math.sqrt(sq)
print(sq2)
xyz=isinstance(sq2, int)
print(xyz)

Upvotes: 0

Views: 550

Answers (1)

Ratery
Ratery

Reputation: 2917

import math

ans = math.sqrt(int(input()))  # calculate an answer
print(int(ans) if ans.is_integer() else ans)  # convert answer to int if we can do it

Upvotes: 1

Related Questions