Basic if statement (ternary operator) info

Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, otherwise it evaluates the second expression.

Programming languages derived from C usually have following syntax:

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic, since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its own shortcut conditional expression:

It first evaluates the condition; if it returns True, expression1 will be evaluated to give the result, otherwise expression2. Evaluation is lazy, so only one expression will be executed.

Let's take a look at this example:

Ternary operators can be changed:

Conditions are evaluated from left to right, which is easy to double-check with something like the pprint module:

Alternatives to the ternary operator

For Python versions lower then 2.5, programmers developed several tricks that somehow emulate behavior of ternary conditional operator. They are generally discouraged, but it's good to know how they work:

The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:

Another approach using and/or statements:

Yes, most of the workarounds look ugly. Nevertheless, there are situations when it's better to use and or or logic than the ternary operator. For example, when your condition is the same as one of expressions, you probably want to avoid evaluating it twice:

Use Python magic carefully!

For more about using if statements on one line (ternary conditional operators), checkout PEP (Python Enhancement Proposal) 308.

  • Mike Gleen

    name = getname()
    print (name if name else ‘Anonymous’)
    # dull but understandable

  • Deepak

    All the information is understandable

    • Deepak

      Thanks if u have any query then visit the site

  • yoochan

    well, I find ternary operator more meaningful when dealing with return values, as you would use the C ternary operator :

    print(‘kid’ if age < 18 else 'adult')

    shorted, cleaner, better :)

  • m

    What about nesting a shorthand conditional statement in a shorthand for loop? Example:

    for species in (Life.Animalia.Chordata.Mammalia.Primates.Hominidae.Homo.getSpecies()): if species.getCranialCapacity() >700: pprint (species.getName())

    ok… that was’t a good example, but you get the question.

  • http://blog.aligoren.net Ali

    Gooood :) thank youuu :)