Reputation: 13206
I am well aware that you can do a one line if else
statement in Python, but I am wondering if it is possible to add an or
to that. For some reason this does not work, even though it reads like it should. Is there any way to do this:
def write(value):
return 'That is not a good value' if value is not 1 or 0 #SyntaxError: invalid syntax
EDIT
So that this function would check if the passed in value was the integer 0 or 1, return 'That is not a good value'
if it is not, or not return anything if it is. I.E.
write(1) #Nothing
write(2) # That is not a good value
Upvotes: 0
Views: 900
Reputation: 236004
Try this:
'That is not a good value' if value not in (0, 1) else None
In the above, we can use the in
membership operator to test the equivalent of an or
expression with two or more conditions. Notice that a conditional expression must have an else
part (see the documentation). If you don't want to return "anything" you still have to return something. For instance, the empty string ''
or None
.
Upvotes: 6
Reputation: 81926
There's two problems.
value is not (1 or 0)
is
. Use ==
or !=
.Let's fix it.
def write(value):
return 'That is not a good value' if value != 1 and value != 0 else 'Great value!'
Or, using a set for clarity:
def write(value):
return 'That is not a good value' if value not in {0, 1} else 'Great value!'
And, we can see this now working here:
>>> def write(value):
... return 'That is not a good value' if value not in {0, 1} else 'Great value!'
...
>>> write(0)
'Great value!'
>>> write(1)
'Great value!'
>>> write(2)
'That is not a good value'
Upvotes: 3