There is, in Python it is known as Conditional Expression.
<expressao1> if <condicao> else <expressao2>
First, the condition is assessed (rather than 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 does not work in the same way 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 value returned.
Based on your example:
x = 10
print (x % 2 == 0 and "par" or "impar")
According to the PEP 308, Conditional Expressions, the reason the syntax has not been 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 two-point already has many uses in Python (although in fact it would not be ambiguous, because the point of
question requires the corresponding two-point); for persons other than
use languages derived from C, it is difficult to understand.
Obs: BDFL (Benevolent Dictator For Life): Guido van Rossum, creator of Python.
Remembering that this operator is not called ternary but yes conditional. It turns out that it is usually the only ternary operator (i.e., it receives three operands) of the languages in which it appears, so the strong association.
– Pablo Almeida