Tuesday, January 21, 2025
HomeTechPython If Else in One Line

Python If Else in One Line

In Python, you can write an if-else statement in a single line using the ternary conditional operator. Here’s the general syntax:

value_if_true if condition else value_if_false
Example:
x = 10
result = "Positive" if x > 0 else "Negative"
print(result)

This checks if x is greater than 0 and assigns “Positive” to result if true, or “Negative” if false.

See also  Sorting an array of ASCII characters by brightness levels

Let me know if you’d like further examples!

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