Tuesday, November 5, 2019

Ternary Operator in Python

In Python there is no ternary operator in the form of (:?) as in programming languages like c, c++, Java. Python ternary operator is an if-else conditional expression written in a single line.

Form of Python ternary operator

Syntax for Python Ternary Operator is as given below-

[when_expr_true] if [conditional_expression] else [when_expr_false]

Initially conditional_expression is evaluated, if it is true then the ‘when_expr_true’ value is used, if false then ‘when_expr_false’ value is used.

Python ternary operator example

Let’s see an example to clarify the ternary operator usage. Here is a condition written using traditional if-else statement.

    if age > 18:
        msg = 'can vote'
    else:
        msg = "can't vote"
    print(msg)

Using ternary operator same condition can be written in one line as-

msg = 'can vote' if age > 18 else "can't vote"

As you can see using Python ternary operator you can test condition in a single line making the code concise and more readable. That’s the advantage of using ternary operator.

Nested Python ternary operator

Ternary operator can be nested too but beware that with nested ternary operators you lose the very advantage for which you tend to use ternary operator; readability.

For example following if-elif suite

  if a > b:
      print('a is greater than b')
  elif a < b:
      print('a is less than b')
  else:
      print('a and b are equal')

can be written using nested ternary operator-

msg = 'a is greater than b' if(a > b) else 'a is less than b' if(a < b) else 'a and b are equal'

Using ternary operator with tuple, dictionary

There is also a short form to be used with tuple and dictionary based on the fact that conditional_expression is evaluated first.

1. Consider the following example for tuple.

def display_msg(age):
    print('Age is', age)
    t = ("can't vote", "can vote")
    msg = t[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

As you can see false value is stored first in the tuple and then the true value. It is because of the fact that false = 0 and true = 1. Expression t[age > 18] evaluates to t[0] if expression is false and it evaluates to t[1] if expression is true.

2. For dictionary you can store key value pair for true and false.

def display_msg(age):
    print('Age is', age)
    d = {True: "can vote", False: "can't vote"}
    msg = d[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

That's all for this topic Ternary Operator in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python for Loop With Examples
  2. pass Statement in Python
  3. Python First Program - Hello World
  4. Class And Object in Python
  5. self in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Abstract Class in Python
  3. Strings in Python With Method Examples
  4. Python Program to Count Occurrences of Each Character in a String
  5. Transaction Management in Java-JDBC
  6. Java Stream flatMap() Method
  7. Marker Interface in Java
  8. How to Create PDF in Java Using OpenPDF

No comments:

Post a Comment