Ternary

Ternary Operator

The ternary operator or conditional operator, is a simplified method for performing a basic if-else statement in a single line of code. The syntax typically follows the pattern: condition ? expression_if_true : expression_if_false. This allows for more concise and readable code when you need to assign a value based on a condition.

Python Example

# Using the ternary operator to assign a message based on age
age = 20
message = "Adult" if age >= 18 else "Minor"
print(message)

C# Example

// Using the ternary operator to decide if a number is odd or even
int number = 5;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(result);

Last updated

Was this helpful?