How to write Python if else in single line?
Question:
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
Answers:
Try this:
category.is_parent = True if self.request.get('parentKey') else False
To check only against None
:
category.is_parent = True if self.request.get('parentKey') is not None else False
You can write:
category.is_parent = True if self.request.get('parentKey') is not None else False
Or even simpler in this case:
category.is_parent = self.request.get('parentKey') is not None
You can write this with a one liner but using the [][] python conditional syntax. Like so:
category.is_parent = [False,True][self.request.get('parentKey') is not None
The first element in the first array is the result for the else part of the condition and the second element is the result when the condition in the second array evaluates to True.
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
Try this:
category.is_parent = True if self.request.get('parentKey') else False
To check only against None
:
category.is_parent = True if self.request.get('parentKey') is not None else False
You can write:
category.is_parent = True if self.request.get('parentKey') is not None else False
Or even simpler in this case:
category.is_parent = self.request.get('parentKey') is not None
You can write this with a one liner but using the [][] python conditional syntax. Like so:
category.is_parent = [False,True][self.request.get('parentKey') is not None
The first element in the first array is the result for the else part of the condition and the second element is the result when the condition in the second array evaluates to True.