Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

python Ternary operator

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
Because here condition 5

  • 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.

  1. a=8
  2. b=9
  3. max= b if b>a else a.
  4. print(max)
output: 9





This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

python Ternary operator

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×