Is there a ternary operation in Python?

12

I often 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, it gave me an error:

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

If that does not work, then what would a ternary operation be in Python?

    
asked by anonymous 26.10.2016 / 18:35

4 answers

15

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

    
26.10.2016 / 18:37
7

In Pyhton, the if can be used both as a statement , and as an operator in different contexts. As operator gives to do so:

print(1 if True else 2)

In your example:

x = randint(0,9)
print ("par" if x % 2 == 0 else "impar")

See running on ideone .

It takes the first value if the condition is true, if the condition is false it takes what is in else . Generally speaking the conditional expression (I do not like the term ternary) looks like this:

valorVerdadeito if condicao else valorFalso
    
26.10.2016 / 18:38
3

Yes, in ternary operation you use if and else normally.

y = "par" if x % 2 == 0 else "impar"
    
26.10.2016 / 18:39
3

The Python language has its own syntax for ternary operation. What differs from most that use the well-known syntax ( condição ? verdadeiro : false ).

Your expression with if and else "normal" would look like:

if x % 2 == 0:
    print "Par"
else:
    print "Ímpar"

Moving to Python's ternary operation, it would look like:

print "Par" if x % 2 == 0 else "Ímpar"

See working at Ideone .

    
26.10.2016 / 18:40