Python's short-hand method for writing an if/else statement There are three components to the ternary operator: the expression/condition, the positive value, and the negative value. When the expression evaluates to true, the positive value is used—otherwise the negative value is used.
Else (Ternary Operator) There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line.
In computer programming languages operators are special symbols which represent computations, conditional matching etc. The values the operator uses are called operands. c = a + b Here a and b are called operands and '+' is an operator. Python supports following operators.
The ternary conditional operator is an easier way of writing an if-else statement. The ternary operator has three components: expression, positive value and negative value. In the standardized way of expressing the ternary operator, we use a question mark and a colon.
The most readable way is
x = 10 if a > b else 11
but you can use and
and or
, too:
x = a > b and 10 or 11
The "Zen of Python" says that "readability counts", though, so go for the first way.
Also, the and-or trick will fail if you put a variable instead of 10
and it evaluates to False
.
However, if more than the assignment depends on this condition, it will be more readable to write it as you have:
if A[i] > B[j]:
x = A[i]
i += 1
else:
x = A[j]
j += 1
unless you put i
and j
in a container. But if you show us why you need it, it may well turn out that you don't.
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With