Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is there an equivalent of C's "?:" ternary operator in Python?
Yes, Python has an equivalent to C's ternary operator ?:. Python's conditional expression provides a concise way to choose between two values based on a condition.
C Language Ternary Operator
First, let's see how C's ternary operator works ?
#include <stdio.h>
int main() {
int x = 10;
int y;
y = (x == 1) ? 20 : 30;
printf("Value of y = %d\n", y);
y = (x == 10) ? 20 : 30;
printf("Value of y = %d\n", y);
}
Value of y = 30 Value of y = 20
Python's Conditional Expression
Python introduced its conditional expression syntax in version 2.5. The syntax is more readable than C's ternary operator ?
Syntax
[on_true] if [condition] else [on_false]
Example ? Finding Minimum Value
Here's how to find the smaller of two numbers using Python's conditional expression ?
x = 20
y = 10
minimum = x if x < y else y
print("Minimum value:", minimum)
Minimum value: 10
Example ? Finding Maximum Value
Similarly, we can find the larger value ?
x = 50
y = 10
maximum = x if x > y else y
print("Maximum value:", maximum)
Maximum value: 50
Pre-Python 2.5 Workaround
Before Python 2.5, developers used logical operators as a workaround ?
[condition] and [on_true] or [on_false]
However, this approach had a critical flaw: it failed when on_true evaluated to a falsy value (like 0, "", None, etc.).
Practical Examples
Age Category Classification
age = 17
category = "Adult" if age >= 18 else "Minor"
print(f"Age category: {category}")
Age category: Minor
Grade Assignment
score = 85
grade = "Pass" if score >= 60 else "Fail"
print(f"Result: {grade}")
Result: Pass
Comparison
| Language | Syntax | Example |
|---|---|---|
| C | condition ? true_val : false_val |
y = (x > 5) ? 10 : 20; |
| Python | true_val if condition else false_val |
y = 10 if x > 5 else 20 |
Conclusion
Python's conditional expression value_if_true if condition else value_if_false is the equivalent of C's ternary operator. It provides a clean, readable way to assign values based on conditions and avoids the pitfalls of earlier workarounds.
