The Problem

Python is sorely missing an if statement that:

In C and its derivitives,

predicate ? A : B 

This is extremely useful in programming and helps avoid copy and paste assignments. This is an example of poor code, because the assignment logic "x=" is copied and pasted, violating the software maintainbility and readability principle of OnceAndOnlyOnce:

if test:

Accepted Solution

This is now part of Python 2.5:

A if predicate else B

which would convert the above snippet to:

x = sin(cos(x)) if test else cos(sin(x))


Please see and google for discussions about the ternary operator (if you haven't yet).

IfStatementWithValue (last edited 2009-03-30 21:57:55 by dhcp128-33-22-52)

Unable to edit the page? See the FrontPage for instructions.