Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one line if else condition in python

def sum10(a, b):
    if sum([a, b]) % 10 == 0: return True; return False

print sum10(7, 3)
print sum10(-13, -17)
print sum10(3, 8)

the result is:

True
True
None

not what I expected:

True
True
False

any idea?

like image 222
mko Avatar asked Oct 30 '12 07:10

mko


4 Answers

Your code

def sum10(a, b):
    if sum([a, b]) % 10 == 0: return True; return False

is equivalent to

def sum10(a, b):
    if sum([a, b]) % 10 == 0: 
        return True; return False

so return False is never evaluated.


Some (of the probably endless) alternatives:

    if sum([a, b]) % 10 == 0: 
        return True
    return False

or

    return sum([a, b]) % 10 == 0

or

    return True if sum([a, b]) % 10 == 0 else False

or

    return False if (a+b) % 10 else True

or (the most readable IMHO)

    return not (a + b) % 10
like image 145
sloth Avatar answered Nov 14 '22 23:11

sloth


This is what you want.

def sum10(a, b):
    return sum([a, b]) % 10 == 0

Also the ternary If in Python works like this

<True Statment> if <Conditional Expression> else <False Statement>

eg

True if sum([a,b]) % 10 == 0 else False

Might i also recommend using the plus operator?

True if (a+b) % 10 == 0 else False
like image 31
st0le Avatar answered Nov 14 '22 23:11

st0le


If you want to have if-else one liners, they should be written like this:

return True if sum([a, b]) % 10 == 0 else False

Note the absence of two points in that one liner.

like image 2
alestanis Avatar answered Nov 14 '22 23:11

alestanis


I think that the return False is never executed due to it is into the if, not outside it.

So, when you take a true in the if condition, you are executing return True, but never the second statement.

like image 1
Amedio Avatar answered Nov 14 '22 23:11

Amedio