pass equivalent in one line if statements in Python

Question:

if number == 1:
    action = 0 
else:     
    pass

What would be the equivalent one-liner here?

action = 0 if number == 1 else pass

This raises an error, obviously. But I can’t use else 0, since 0 is a valid action.
Currently, I’m using else None which does work. But is there a ‘right’ way to use the pass statement?

action = 0 if number == 1 else pass

Raises an exception

action = 0 if number == 1 else 0

doesn’t work in my particular code, since 0 is a valid action

action = 0 if number == 1 else None

is my current workaround

Asked By: Chris Hänßler

||

Answers:

Everything to the right of action = is an expression. Expressions need to generate a value; if action is defined before that line, you could do this:

action = 0 if number == 1 else action

which will leave action set to its previous value, or if it is not defined, well, starting a line with action = will set it to a value, therefore you can’t just leave it undefined when number != 1. In that case, the only possibility is to avoid starting with an assignment, and do for example:

if number == 1: action = 0

You don’t even need an else clause or a new line actually.

Answered By: Pedro Gimeno
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.