OneCompiler

Python Ternary operator explained

286


In this post, we will learn about the ternary operator in Python.

What is the ternary operator

  • These are conditional expressions that evaluate something based on a condition.
  • These work similar to an if...else statement.

Syntax

[on_true_statements] if [expression] else [on_false] 

Example

Consider the below example.

Without ternary operator

n = int(input())

if n>0:
  print(n, "is greater than 0")
  
elif n<0:
  print(n, "is less than 0")

This is what we do generally. We can simplify the expression with the help of a ternary operator.

With ternary operator

n = int(input())

print(n, "is greater than 0") if n>0 else  print(n, "is less than 0")

Check Output Here