Saim Abdullah Ch Saim Abdullah Ch - 12 days ago 9
Python Question

How to write Python if else in single line?

category.is_parent = True if self.request.get('parentKey') is not None else category.is_parent = False


Above is the code in which I am trying to write a if else in a single line and it is giving me this syntax error

SyntaxError: can't assign to conditional expression"


But if I write it in following way it works fine

if self.request.get('parentKey') is not None:
category.is_parent = True
else:
category.is_parent = False

Answer

Try this:

category.is_parent = True if self.request.get('parentKey') else False

To check against None:

category.is_parent = True if self.request.get('parentKey') is not None else False