Send
Close Add comments:
(status displays here)
Got it! This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website. Note: This appears on each machine/browser from which this site is accessed.
Python: Ternary operator
1. Python: Ternary operator
Let us review the Lua ternary operator in terms of the if-then-else expression.
2. C: Ternary operator
Some expressions involve unary operators such as arithmetic negation or logical negation.
Some expressions involve binary operators such as arithmetic addition, subtraction,e etc., or logical conjunction, disjunction, etc.
There is a common ternary operator "?" (question mark) that takes three operands. It is sometimes called a conditional expression (as contrasted with the "if then else") conditional control flow statement.
Here is the C code [#1]
3. Examples of input and output
Here are some examples of input and output for the above program code.
Here is an example input.
For the above example input, here is the expected output.
Here is an example input.
For the above example input, here is the expected output.
Here is an example input.
For the above example input, here is the expected output.
Here is the C code [#2]
4. Examples of input and output
Here are some examples of input and output for the above program code.
Here is an example input.
For the above example input, here is the expected output.
Here is an example input.
For the above example input, here is the expected output.
Here is an example input.
For the above example input, here is the expected output.
5. If-then-else expression
The ternary expression, or if-then-else expression, has the following general form.
condition ? then-expression : else-expression
Both then-expression and else-expression are required.
I prefer to usually use parentheses around the condition part of the conditional expression.
6. If-then-else statement
By contrast, the if-then-else statement has the following form.
if (condition) {
then-statements
}
else {
else-statements
}
The else-statements (and else-part) can be omitted if not needed.
Note: In the above example programs, the use of the ternary operator takes 5 lines (in the if-then-else statement) to one line (using the if-then-else expression).
7. Python
Python has a ternary operator or if-then-else expression.
Consider the following example program that computes and outputs the absolute value of the elements of the list using an if-then-else statement.
Here is the Python code [#1]
Here is the output of the Python code.
8. Ternary operator
Now consider the following example program that does the same thing but uses the ternary operator using an if-then-else expression.
Here is the Python code [#2]
Here is the output of the Python code.
9. End of page