GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Wiki
  • PSF Wiki
  • Jython Wiki
  • Python Wiki
  • Archive

This view

  • Original page
  • New address

GeezerVison is showing wiki.python.org — If Statement with Value

View as Markdown

If Statement with Value¶

Legacy Wiki Page

This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org.

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

Previous
Idea Repository
Next
Image Magick
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.