How to Use Ternary Operator in Python: Simple Syntax & Examples
In Python, the
ternary operator is written as value_if_true if condition else value_if_false. It lets you choose between two values in a single line based on a condition.Syntax
The ternary operator in Python has three parts:
- condition: The test that decides which value to pick.
- value_if_true: The result if the condition is true.
- value_if_false: The result if the condition is false.
The format is: value_if_true if condition else value_if_false.
python
result = 'Yes' if 5 > 3 else 'No'
Example
This example shows how to use the ternary operator to check if a number is even or odd and print the result.
python
number = 4 result = 'Even' if number % 2 == 0 else 'Odd' print(result)
Output
Even
Common Pitfalls
Common mistakes include reversing the order of if and else parts or forgetting the else clause, which causes syntax errors.
Wrong example (will cause error):
result = 'Yes' else 'No' if 5 > 3
Correct example:
result = 'Yes' if 5 > 3 else 'No'
Quick Reference
Use the ternary operator for simple conditional assignments to keep code concise and readable. Always include else to avoid errors.
| Part | Description |
|---|---|
| condition | The test expression that evaluates to True or False |
| value_if_true | Value returned if condition is True |
| value_if_false | Value returned if condition is False |
Key Takeaways
The ternary operator format is: value_if_true if condition else value_if_false.
It lets you write simple if-else decisions in one line.
Always include the else part to avoid syntax errors.
Use it for clear, concise conditional assignments.
Do not reverse the order of if and else parts.