Python condenses if / else on one line?

Possible duplicate:
Python Terminal Operator
Including a simple if-then statement on a single line

Is there a way to compress an if / else statement into a single line in Python? I often see all kinds of shortcuts and suspect that it may apply here.

+56
python
Jul 17 '12 at 19:13
source share
4 answers

An example Python method for executing triple expressions:

i = 5 if a > 7 else 0 

means

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

This is really useful when using lists or sometimes in return statements, otherwise I'm not sure if this helps in creating readable code.

The readability issue has been discussed in detail in this recent SO question better than using the if-else statement in python .

It also contains various other smart (and somewhat confusing) ways to accomplish the same task. It is worth reading only based on these posts.

+78
Jul 17 '12 at 19:15
source share

Python if can be used as a ternary operator :

 >>> 'true' if True else 'false' 'true' >>> 'true' if False else 'false' 'false' 
+40
Jul 17 '12 at 19:15
source share

Only for use as a value:

 x = 3 if a==2 else 0 

or

 return 3 if a==2 else 0 
+13
Jul 17 '12 at 19:14
source share

There is a conditional expression:

 a if cond else b 

but it is an expression, not a statement.

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

 if something: somefunc() else: otherfunc() 

but this is discouraged as a formatting issue.

+8
Jul 17 '12 at 19:16
source share



All Articles