Im trying to check is the number passed is a valid perfect square by
return True if(math.sqrt(num)%2 == 0 or \
(math.sqrt(num)+1) % 2 == 0 ) else False
I want to know if I could write this better by breaking the if statement into two parts like
return True if(math.sqrt(num)%2 == 0)
elif ((math.sqrt(num)+1) % 2 == 0 )
else False
Could someone help me with how to use elif here or if there is a better approach.
Thank you.
6 Answers 6
No need to use if statements at all
return math.sqrt(num) % 2 == 0 or (math.sqrt(num)+1) % 2 == 0
4 Comments
return math.sqrt(num) % 1 == 0Simple one-liner with readability in mind.
def check(num):
return True if math.sqrt(num) % 2 == 0 or (math.sqrt(num)+1) % 2 == 0 else False
Result
>>> check(25)
True
>>> check(23)
False
2 Comments
First of all, there is no elif in the ternary operator. Second, your elif doesn't specify a return value (one reason it was left out of the ternary expression). Third, your check for the root being an integer is susceptible to round-off error. Instead, try rounding teh root to an integer, square that, and compare against the original value.
Comments
Just answering your question on how to use elif and do it in more than a single line by breaking the if statement. I assume you put these in a function. There could be better ways though as pointed out in other answers
def check_sqrt(num):
if math.sqrt(num)%2 == 0:
return True
elif (math.sqrt(num)+1) % 2 == 0:
return True
else:
return False
print (check_sqrt(23))
> False
print (check_sqrt(25))
> True
Comments
You should always write clearer code that everyone could understand. And you should make it a habit.
if math.sqrt(num)%2 == 0:
return True
if (math.sqrt(num)+1) % 2 == 0:
return True
return False
Comments
A cleaner version with Python 3.8+ would be:
import math
def is_square(number):
return math.isqrt(number) ** 2 == number if number >= 0 else False
As an example:
is_square(0)
True
is_square(4)
True
is_square(1)
True
is_square(3)
False
is_square(-4)
False
is_square(3.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in is_square
TypeError: 'float' object cannot be interpreted as an integer
return (math.sqrt(num)%2 == 0 or (math.sqrt(num)+1) % 2 == 0)?return (math.sqrt(num)%2 == 0 or (math.sqrt(num)+1) % 2 == 0)but i want to break this as I don't have to compute the or case if the first one is true.1 + math.factorial(25)a perfect square even though it is manifestly not.def f(x): print(x); return x;f(True) or f(False);.Falsewon't be printed.orshort circuits.