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?
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With