Ternary operators are a shorthand way of writing an if-else
statement. They are also known as the conditional operator. Ternary operators are used to assign a value to a variable based on a condition.
Syntax of Ternary Operators
variable = value_if_true if condition else value_if_false
Example of Ternary Operators
x = 5
y = 3
result = 'x is greater than y' if x > y else 'x is less than or equal to y'
print(result) # Output: 'x is greater than y'
In the above example, the ternary operator is used to check if x
is greater than y
, if the condition is true, the value 'x is greater than y'
is assigned to the variable result
, otherwise, the value 'x is less than or equal to y'
is assigned to the variable result
.
Another example
x = 5
y = 3
result = x if x > y else y
print(result) # Output: 5
In this example, the ternary operator is used to compare x
and y
, and the greater value is assigned to the variable result
.
It is important to note that the Ternary operator should be used only when the if-else
statement is simple and easy to read. When the if-else
statement becomes complex, it's better to use if-else
statement instead of Ternary operator.
In summary, Ternary operators are a shorthand way of writing an if-else
statement, they are used to assign a value to a variable based on a condition. They are useful when the if-else
statement is simple and easy to read.