Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement to one line with return [duplicate]

I know that the 'one line if statement' question has been asked multiple times already but I couldn't figure out what's wrong with my code. I want to convert

def has_no_e(word):
    if 'e' not in word:
        return True

to a one line function like:

def hasNoE(word):
    return True if 'e' not in word

but I get a Syntax Error if I do so -why?

like image 288
Mickey Mahoney Avatar asked Jan 18 '17 15:01

Mickey Mahoney


2 Answers

I think because you do not specify the else part. You should write it as:

return True if 'e' not in word else None

This is because Python sees it as:

return <expr>

and you specify a ternary condition operator as <expr> which has syntax:

<expr1> if <condition> else <expr2>

So Python is looking for your else part.


Return False?

Perhaps you want to return False in case the test fails. In that case you could thus write it like:

return True if 'e' not in word else False

but this can be shortened in:

return 'e' not in word
like image 82
Willem Van Onsem Avatar answered Oct 20 '22 00:10

Willem Van Onsem


Ternary conditional statements require you to have an else in them as well. Thus, you must have:

def hasNoE(word):
    return True if 'e' not in word else False
like image 35
TerryA Avatar answered Oct 19 '22 23:10

TerryA