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(true_value) if (condition) print(false_value)
Example: In this example, we are finding the minimum number among two numbers using Python ternary operator with print statement.
a = 10
b = 20
# ternary operator with print statement
print(a,"is minimum") if (a < b) else print(b,"is minimum")
Output:
10 is minimum
Ternary Operator in Python
In Python, Ternary Operator determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code.
It’s convenient when we want to avoid writing multiple lines for a simple if-else condition. Like in simple if-else, the first option, the true_value will be executed when the condition provided in the expression is True. If the condition returns False, then false_value will be executed.
Syntax: true_value if condition else false_value
The ternary operator can be used in various ways. Let us see a few different examples to use Ternary Operators in Python:
Table of Content
- Python Ternary If Else
- Ternary Operator in Nested If else
- Ternary Operator using Python Tuple
- Ternary Operator using Python Dictionary
- Ternary Operator using Python Lambda
- Ternary Operator with Print Function
- Limitations of Python Ternary Operator