Startec
Startec

Reputation: 13206

Python, one line if, else or statement?

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

Answers (2)

Óscar López
Óscar López

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 orexpression 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

Bill Lynch
Bill Lynch

Reputation: 81926

There's two problems.

  1. What should that code return if it isn't 0 or 1?
  2. Your conditional is parsed as: value is not (1 or 0)
  3. You really shouldn't compare numbers using 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

Related Questions