Ternary Operator in Python
Last Updated :
18 Dec, 2024
The ternary operator in Python allows us to perform conditional checks and assign values or perform operations on a single line. It is also known as a conditional expression because it evaluates a condition and returns one value if the condition is True and another if it is False.
Basic Example of Ternary Operator
The simplest way to use a Python ternary operator is when we have a simple if else condition – either of the two conditions is True and the other is False.
Let’s start with a simple example to determine whether a number is even or odd:
Python
n = 5
res = "Even" if n % 2 == 0 else "Odd"
print(res)
The ternary operator can be used in various ways. Let us see a few different examples to use Ternary Operators in Python:
Ternary Operator in Nested If else
The ternary operator can also be used in Python nested if-else statement. We can nest ternary operators to evaluate multiple conditions in a single line.
Syntax: value_if_true if condition else value_if_false
Example:
Python
n = -5
res = "Positive" if n > 0 else "Negative" if n < 0 else "Zero"
print(res)
Explanation:
- First, it checks if num > 0. If True, it returns “Positive”.
- If False, it checks if num < 0. If True, it returns “Negative”.
- If both conditions fail, it defaults to “Zero”.
Ternary Operator using Tuple
The ternary operator can also be written by using Python tuples. The tuple indexing method is an alternative to the ternary operator.
Syntax: (condition_is_false, condition_is_true)[condition]
Example:
Python
n = 7
res = ("Odd", "Even")[n % 2 == 0]
print(res)
Explanation:
- The condition num % 2 == 0 evaluates to False (index 0), so it selects “Odd”.
Ternary Operator using Dictionary
A dictionary can be used to map conditions to values, providing a way to use a ternary operator with more complex conditions.
Syntax: condition_dict = {True: value_if_true, False: value_if_false}
Example:
Python
a = 10
b = 20
max = {True: a, False: b}[a > b]
print(max)
Explanation: This uses a dictionary where the key is True or False based on the condition a > b. The corresponding value (a or b) is then selected.
Ternary Operator using Python Lambda
Lambdas can be used in conjunction with the ternary operator for inline conditional logic.
Syntax: lambda x: value_if_true if condition else value_if_false
Example:
Python
a = 10
b = 20
max = (lambda x, y: x if x > y else y)(a, b)
print(max)
Explanation: This defines an anonymous function (lambda) that takes two arguments and returns the larger one using the ternary operator. It is then called with a and b.
Ternary Operator with Print Function
The ternary operator can also be directly used with the Python print statement. Its syntax is a s follows:
Syntax: print(value_if_true if condition else value_if_false)
Example: In this example, we are finding the minimum number among two numbers using Python ternary operator with print statement.
Python
a = 10
b = 20
print("a is greater" if a > b else "b is greater")
Explanation: This checks if a is greater than b. If true, it prints “a is greater”; otherwise, it prints “b is greater”.
Limitations of Python Ternary Operator
While the ternary operator is concise, it should be used with caution:
- It can reduce readability if overused or used in complex conditions.
- It’s limited to simple, single-line expressions.
Similar Reads
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes int
4 min read
Python Arithmetic Operators
Python Arithmetic Operators
Python operators are fundamental for performing mathematical calculations. Arithmetic operators are symbols used to perform mathematical operations on numerical values. Arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). OperatorDescriptionS
5 min read
Difference between / vs. // operator in Python
In this article, we will see the difference between the / vs // operator in Python Python Division OperatorThe division operator '/ ' performs standard division, which can result in a floating-point number. However, if both the dividend and divisor are integers, Python will perform integer division
2 min read
Python - Star or Asterisk operator ( * )
The asterisk (*) operator in Python is a versatile tool used in various contexts. It is commonly used for multiplication, unpacking iterables, defining variable-length arguments in functions, and more. Uses of the asterisk ( * ) operator in PythonMultiplicationIn Multiplication, we multiply two numb
3 min read
What does the Double Star operator mean in Python?
The ** (double star)operator in Python is used for exponentiation. It raises the number on the left to the power of the number on the right. For example: 2 ** 3 returns 8 (since 2³ = 8)It is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python and is also known as Power Operator. Pr
2 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. There are two types of division operators: Float divisionInteger division( Floor division)When an in
5 min read
Modulo operator (%) in Python
Modulo operator (%) in Python gives the remainder when one number is divided by another. Python allows both integers and floats as operands, unlike some other languages. It follows the Euclidean division rule, meaning the remainder always has the same sign as the divisor. It is used in finding even/
4 min read