Question: What is a ternary operator in Python? Explain with example.
Answer: A ternary operator in Python is a shorthand way to perform a simple conditional operation, allowing you to return one of two values based on a condition. It's often used to replace a simple if-else
statement with a more concise expression.
Syntax: value_if_true if condition else value_if_false
Explanation
- condition: The expression that is evaluated to either True or False.
- value_if_true: The value that is returned if the condition is True.
- value_if_false: The value that is returned if the condition is False.
Python Example:
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
#Output: Adult
In the above example:
- The condition
age >= 18
is evaluated. - If the condition is
True
,status
is set to"Adult"
. - If the condition is
False
,status
is set to"Minor"
.
Use Cases: The ternary operator is typically used for:
- Conditionally assigning values to variables.
- Simplifying simple
if-else
statements into one-liners. - Making code more concise when the conditional logic is straightforward.