Python return elif statement

Viewed 5900

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.

5 Answers

No need to use if statements at all

return math.sqrt(num) % 2 == 0 or (math.sqrt(num)+1) % 2 == 0 

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.

Simple 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

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  

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
Related