You seem to have 2 main misunderstandings:
The ==
is used to compare objects, not to assign. I believe you meant to assign s
with the value of math.sqrt(x)
. This is done by s = math.sqrt(x)
.
Even with the above change, you can't put that assignment inside the if
statement. The if
condition can contain expressions, not statements. Assignments are statements.
To fix that, all you need to do is first assign s
separatly:
import math
def perfsq(x):
s = math.sqrt(x)
if s * s == x:
print('yes')
Now your problem is that you become dependant on float precision. sqrt
returns a float, so doing operations on floats (such as s * s
) is risky. As an example, using the above function, running perfsq(35)
will actually print 'yes'
!!!
To avoid these precision issues, it is enough to check if the square root of a number is an int to begin with. So your code can be greatly simplified to:
import math
def perfsq(x):
if math.sqrt(x).is_integer():
print('yes')
This is using the float.is_integer()
method, based on the fact that math.sqrt
always returns a float.