Ternary operator:
- The ternary operator is defined as the operator that evaluates the conditions to find the final result.
- It evaluates more than one expression.
- A single line code is written according to the condition.
syntax: x= first value if condition else second value.
In this syntax, if the first value satisfies the condition then it returns the x value, if the first value doesn't satisfy the condition then it goes to the else part and checks the second condition.
Example: x=20 if 5<10 else 30 we get the result as 20.
Because here condition 5<10 is grue so it returns the x value as 10.
- There is another syntax for the ternary operator when there are more than 2 conditions i.e;
- syntax: x= first value if condition 1 else second value if condition 2 else third value.
Example: x=1 if 20>30 else 2 if 50>60 else 10.
The result is 10.
- In the ternary operator, we can perform a nested loop also.
- We can reduce the length of the code by using this ternary operator, in this operator we write a code in a single line.
- So time is saved and less complexity in the code.
#write a python program for integers using the ternary operator.
- a=8
- b=9
- max= b if b>a else a.
- print(max)
output: 9
No comments