
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Is there an equivalent of C’s “?:” ternary operator in Python?
Yes, we can work around C Language’s ternary operator in Python as well i.e. a similar way do exist. Let us first see an example of C Language’s ternary operator −
Example
#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 ); }
Output
Value of y = 30 Value of y = 20
There are many operators in Python: Arithmetic, Assignment, Logical, Bitwise, Membership, Identity, etc. The task accomplished above by ternary in C language can be achieved by a logical operator.
Before Python 2.5, programmers worked around the following logical operator syntax to get the same work done. However this is considered incorrect and usage as it fails when on_safe is having a false Boolean −
[expression] and [on_true] or [on_false]
Therefore, after Python 2.5 the following form of ternary operator introduced to ease the task of programmers.
Syntax
Let us see the syntax −
[on_true] if [expression] else [on_false]
Example
Let us now see an example of implementing ternary operator in Python −
x = 20 y = 10 res = x if x < y else y print(res)
Output
10
Example
Here’s an example −
x = 50 y = 10 res = x if x > y else y print(res)
Output
50
- Related Articles
- Ternary Operator in Python?
- What is Python equivalent of the ! operator?
- How to overload python ternary operator?
- What is ternary operator in C#?
- What is a Ternary operator/conditional operator in C#?
- Ternary Operator in Java
- Ternary Operator in C#
- Does Python have a ternary conditional operator?
- What is a ternary operator (?:) in JavaScript?
- Changing ternary operator into non-ternary - JavaScript?
- Conditional ternary operator ( ?: ) in C++
- Ternary Operator in Dart Programming
- What is ternary operator (? X : Y) in C++?
- Java Ternary Operator Examples
- C/C++ Ternary Operator
