Friday, January 17, 2025
HomeProgrammingWhat Is Ternary Operator in Python?

What Is Ternary Operator in Python?

The ternary operator in Python is a shorthand way of writing an if-else statement in a single line. It allows you to evaluate a condition and return one of two values based on whether the condition is True or False.

The syntax for the ternary operator is:

value_if_true if condition else value_if_false

Example:

x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result)  # Output: Even

Explanation:

  • x % 2 == 0 is the condition being evaluated.
  • If the condition is True, the result will be "Even".
  • If the condition is False, the result will be "Odd".

This allows for more concise code when you need to make simple conditional decisions.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

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

Most Popular

Recent Comments

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