Is there a ternary operation in Python?


I tend to see several programming languages ​​where a ternary operation is almost always identical.

(x % 2 == 0) ? "par" : "impar"

However, when I tried to do this in Python, I got an error:

(x % 2 == 0) ? "par" : "impar"
SyntaxError: invalid syntax

if that doesn't work, then what would a ternary operation in Python look like?


It does exist, in Python it is known as Conditional Expression .

<expressao1> if <condicao> else <expressao2>

First, the condition is evaluated (instead of expressao1 ), if the condition is true, expressao1 is evaluated and its value is returned; otherwise, expressao2 is evaluated and its value returned.

Based on your example, the code looks like this:

x = 10
print ("par" if x % 2 == 0 else "impar")

An alternative with Boolean operators and and or :

<condicao> and <expressao1> or <expressao2>

However, it doesn't work the same as a Conditional Expression, if the condition is true, expressao1 is evaluated and its value returned; if expressao1 is false, expressao2 is evaluated and its returned value.

Based on your example:

x = 10
print (x % 2 == 0 and "par" or "impar")

According to PEP 308 , Conditional Expressions , the reason why the syntax <condicao> ? <expressao1> : <expressao2> was not implemented <condicao> ? <expressao1> : <expressao2> used in many languages ​​derived from C is:

(in free translation)

Eric Raymond even implemented this.

The BDFL rejected this for several reasons: the colon already has many uses in Python (although it would actually be unambiguous, because the question mark requires the corresponding colon); for people who don't use C-derived languages, it's hard to understand.

Note: BDFL (Benevolent Dictator For Life): Guido van Rossum, creator of Python.

Scroll to Top