Differences between revisions 2 and 5 (spanning 3 versions)
Revision 2 as of 2005-01-20 15:36:04
Size: 911
Editor: 207
Comment:
Revision 5 as of 2009-03-30 21:57:55
Size: 964
Editor: dhcp128-33-22-52
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[TableOfContents]] <<TableOfContents>>
Line 22: Line 22:
See also SwitchStatement = Accepted Solution =
Line 24: Line 24:
= Current Python Idioms = This is now part of Python 2.5:
Line 26: Line 26:
There are a few ways in Python do achieve the evaluation only of the statement used when the predicate is true: {{{
A if predicate else B
}}}
Line 28: Line 30:
which would convert the above snippet to:
Line 29: Line 32:
{{{
x = sin(cos(x)) if test else cos(sin(x))
}}}
Line 30: Line 36:
= Proposed Solutions = = Discussion =
Line 32: Line 38:
= If always returns a value =
{{{
x = if test:
    A()
 else:
     B()
}}}
Please see http://python.org/peps/pep-0308.html and google for discussions about the ternary operator (if you haven't yet).

The Problem

Python is sorely missing an if statement that:

  • computes and takes the value of A if and only if the predicate is true
  • computes and takes the value of B if and only if the predicate is false

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:
   x=sin(cos(x))
else:
   x=cos(sin(x))

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

Discussion

Please see http://python.org/peps/pep-0308.html 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.