How to Write a Python One-Line If Statement?

Estimated read time 1 min read

In Python, you can write a one-line if statement using the ternary conditional operator. The syntax for a one-line if statement is as follows:

value_if_true if condition else value_if_false

Here’s an example:

x = 10

# One-line if statement
message = "Positive" if x > 0 else "Negative or zero"


In this example, the condition x > 0 is evaluated. If the condition is true, the value "Positive" is assigned to the variable message. Otherwise, the value "Negative or zero" is assigned.

The result will be printed as "Positive" because the value of x is greater than zero.

You can also nest multiple one-line if statements using this syntax. However, be cautious about maintaining code readability. If the condition and expressions become more complex, it’s generally recommended to use multiple lines with a standard if-else statement for better clarity.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply