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

python— editable, runs on the server
Info

Watch a video course: Python - The Practical Guide

For example:

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

python— editable, runs on the server

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.