How to condense if/else into one line in Python?

ID : 20378

viewed : 14

Tags : pythonpython

Top 5 Answer for How to condense if/else into one line in Python?

vote vote

95

An example of Python's way of doing "ternary" expressions:

i = 5 if a > 7 else 0 

translates into

if a > 7:    i = 5 else:    i = 0 

This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.

The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.

It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.

vote vote

84

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false' 
vote vote

76

Only for using as a value:

x = 3 if a==2 else 0 

or

return 3 if a==2 else 0 
vote vote

64

There is the conditional expression:

a if cond else b 

but this is an expression, not a statement.

In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:

if something: somefunc() else: otherfunc() 

but this is discouraged as a matter of formatting-style.

vote vote

50

If you want to avoid the --force option (which is always a better approach), I suggest making sure that you have stopped running the project, as this is usually the main reason for locking the files in almost 90% of the cases I have seen

I suggest the following steps in this order:

1- In Angular stopping ng s and in React stopping npm start usually solves this issue because usually this error happens if a development server is running the project as it locks some files & then npm can't update them thus throwing this error

2- If the above doesn't work, then try closing the code editor that has the workspace opened in it (maybe it was locking some files or something)

So try closing the code editor & running:

npm install 

3- If still it doesn't work, then maybe you can try the --force option

npm install --force 

Top 3 video Explaining How to condense if/else into one line in Python?

Related QUESTION?