Friday, January 10, 2025
HomeComputer ScienceTernary Operator in Python

Ternary Operator in Python

The ternary operator in Python is a concise way to write an if-else statement in a single line. It allows for conditional assignment or decision-making in a more readable format.

Syntax:

python
value_if_true if condition else value_if_false

Key Points:

  1. Condition: Evaluates to True or False.
  2. value_if_true: The result when the condition is True.
  3. value_if_false: The result when the condition is False.

Examples:

1. Basic Usage

python
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult

2. Nested Ternary Operator

python
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # Output: B

3. Using with Function Calls

python
num = 10
result = (lambda x: x ** 2)(num) if num > 5 else (lambda x: x ** 3)(num)
print(result) # Output: 100

4. Inline Assignment

python
a, b = 5, 10
maximum = a if a > b else b
print(maximum) # Output: 10

Use Cases:

  1. Assigning values based on conditions.
  2. Simplifying small conditional statements for readability.
  3. Reducing code lines in straightforward decisions.
See also  What is a Router in a Computer Network?

Caution:

  • Avoid overusing or nesting ternary operators excessively, as it can reduce code readability.
  • Use only when the logic is simple and clear.

Equivalent if-else Statement:

Ternary Operator:

python
status = "Adult" if age >= 18 else "Minor"

Equivalent if-else:

python
if age >= 18:
status = "Adult"
else:
status = "Minor"
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

HTML Background Images

LMFAO Full Form

Manual Testing

Recent Comments

0
Would love your thoughts, please comment.x
()
x