There is, in Python 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 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 why the <condicao> ? <expressao1> : <expressao2>
syntax used in many languages derived from C is not implemented:
(In free translation)
Eric Raymond until implemented this.
The BDFL rejected this for several reasons: the colon already has many uses in Python (although, in fact, it would not be ambiguous, because the
question requires the corresponding colon); for people who do not
use languages derived from C, is difficult to understand.
BDFL (Benevolent Dictator For Life): Guido van Rossum, creator of Python