In programming, we frequently encounter situations where we want to change the value assigned to a variable based on a specific condition. Usually, we use if and else statements, but Python provides a syntax to write this concisely in a single line. While this is often called the “ternary operator” in other languages, Python’s official documentation refers to it as a “conditional expression.”
This article explains how to write conditional expressions and how to distinguish their use from standard if statements.
Basic Syntax of the Ternary Operator (Conditional Expression)
Python’s conditional expression follows a word order that reads naturally like an English sentence.
Syntax:
value_if_true if condition else value_if_false
If the condition is True, the value on the left is evaluated (adopted). If False, the value on the right (after else) is evaluated.
Specific Usage Examples
As an example, let’s create a program that determines shipping fees based on a user’s membership rank.
1. Writing with Standard if-else
First, let’s look at the traditional way of writing this.
member_rank = "Gold"
shipping_fee = 0
# If rank is Gold, shipping is free (0), otherwise 500
if member_rank == "Gold":
shipping_fee = 0
else:
shipping_fee = 500
print(f"Shipping Fee: {shipping_fee} yen")
This logic is correct, but it takes 4 lines of code just for a simple value assignment.
2. Writing with the Ternary Operator
Now, let’s rewrite the same logic using a conditional expression.
member_rank = "Gold"
# Writing if-else in one line
shipping_fee = 0 if member_rank == "Gold" else 500
print(f"Shipping Fee: {shipping_fee} yen")
Output:
Shipping Fee: 0 yen
It became very simple. The logic “The shipping fee is 0 if the rank is Gold, else it is 500″ is expressed in a single line.
Another Example: Even or Odd Check
Here is an example of switching strings based on a calculation result.
number = 15
# If the remainder of division by 2 is 0, it is "Even", otherwise "Odd"
result_type = "Even" if number % 2 == 0 else "Odd"
print(f"{number} is {result_type}")
Output:
15 is Odd
Note: Readability
While ternary operators are helpful for shortening code, overusing them can actually hurt readability. Specifically, putting a conditional expression inside another one (nesting) is not recommended.
# Not Recommended: Nested ternary operators (Very hard to read)
score = 75
grade = "A" if score >= 90 else "B" if score >= 70 else "C"
For complex branching like this, it is kinder to the reader to use the standard if ... elif ... else syntax.
Summary
- In Python, you can use the
value1 if condition else value2syntax to assign values based on conditions in one line. - This is called a “conditional expression” or “ternary operator.”
- Use it to simplify code for simple conditional assignments.
- For complex branching, stick to standard
ifstatements to maintain readability.
