06 September 2012

Operadores ternarios en Python



Aprendiendo Python una de las primeras cosas interesantes con las que me encontré es con operadores que toman 3 parámetros. Veamos (en inglés) un extracto de un tutorial en PDF:


The basic form of the operator is 
expression if condition else expression 

Python evaluates the condition – in the middle – first. If the condition is True, then the left-hand expression is evaluated, and that’s the value of the operation. If the condition is False, then the right-hand expression is evaluated, and that’s the value of the operation. Note that the condition is always evaluated. Only one of the other two expressions is evaluated, making this a kind of short-cut operator like and and or.
Here are a couple of examples.
average = sum/count if count != 0 else None
oddSum = oddSum + ( n if n % 2 == 1 else 0 )
The intent is to have an English-like reading of the statement. “The average is the sum divided by the count if the count is non-zero; else the average is None”.


Es una construcción algo rara pero simpática.

No comments :

Post a Comment

Comparte tu código...