10

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?

Mickey Mahoney
  • 361
  • 1
  • 4
  • 15

2 Answers2

18

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

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
TerryA
  • 58,805
  • 11
  • 114
  • 143