W3docs

Putting a simple if-then-else statement on one line

In Python, you can put a simple if-then-else statement on one line using the ternary operator, which is represented by the "?" symbol.

In Python, you can put a simple if-then-else statement on one line using a conditional expression. The general format is:

Putting a simple if-then-else statement on one line in Python

x = 0 if 2 == 3 else 1
print(x)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

For example:

Another example of putting a simple if-then-else statement on one line in Python

x = 5
print("x is greater than 3") if x > 3 else print("x is not greater than 3")

This will print "x is greater than 3" to the console, because the condition (x > 3) is true.

Note: Using conditional expressions for side effects (like print) is valid but generally discouraged in Python. Prefer them for assigning values to variables.