Entries Tagged 'Python' ↓

Ternary operator in Python

Here’s how you translate the following C code

int max(int a, int b)
{
    return (a > b ? a : b);
}

to Python:

def max(a, b):
    return a if a > b else b

The general syntax is:

TRUEVAL if CONDEXPR else FALSEVAL

Note: I’m not 100% sure, but I think that only works starting from Python 2.5.