Python’s if then else in one line is written as a conditional expression: value_if_true if condition else value_if_false. It provides a concise way to choose between two values based on a condition, making it useful for simple assignments, return values, messages, and expressions where a full if statement would be unnecessarily long.
Introduction
Python does not use the word then in its conditional syntax. Instead, it uses a compact form called a conditional expression, which is often described as Python’s equivalent of a ternary operator Turns out it matters..
The basic structure is:
result = value_if_true if condition else value_if_false
For example:
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
Output:
adult
In this example, Python checks whether age >= 18 is true. Because of that, if it is, "adult" is assigned to status. Otherwise, "minor" is assigned.
This one-line form is especially helpful when the condition and both possible outcomes are short and easy to understand.
Basic Syntax of Python If Then Else in One Line
The standard syntax is:
expression_if_true if condition else expression_if_false
The order — worth paying attention to. Unlike some programming languages that place the condition first, Python places the selected values around the condition.
Example
temperature = 28
weather = "hot" if temperature > 25 else "cool"
print(weather)
Output:
hot
The expression can be read as:
Assign
"hot"iftemperature > 25; otherwise, assign"cool".
Another Example
score = 72
result = "passed" if score >= 60 else "failed"
print(result)
Output:
passed
Conditional expressions can be used anywhere Python expects an expression, including:
- Variable assignments
- Function return values
- Function arguments
- List comprehensions
- Dictionary values
- Formatted strings