DEV Community

Cover image for Ternary Conditional Operators
Alexandre Bento Freire
Alexandre Bento Freire

Posted on

Ternary Conditional Operators

Python is one of the few popular modern languages that doesn't follow the traditional C-style syntax for ternary conditional operators. Instead of the standard format where the condition is followed by the true expression and then the false expression, Python places the true expression first, followed by the condition and the false expression.

However, not every language supports ternary conditional operators. For example, Go, a rapidly growing language in popularity, does not have a ternary operator. This absence reflects Go's design philosophy, which prefers simplicity and avoids operators that might reduce code readability.

The table below summarizes how different programming languages and language-like systems (such as SQL and Excel) handle ternary conditional operators or their equivalents.

Top comments (2)

Collapse
 
filipemartins profile image
Filipe Martins

// Ternary function that works like a ternary conditional operator
func Ternary(condition bool, trueVal, falseVal any) any {
if condition {
return trueVal
}
return falseVal
}

//use like this
evenOdd := Ternary(num%2 == 0, "Even", "Odd").(string)

Collapse
 
a-bentofreire profile image
Alexandre Bento Freire

The problem with this approach is that isn't short circuit and it will evaluate both trueVal and falseVal.
example:
x = 5
y = 0
y != 0 ? 1 : x/y
In this case it never raises and exception. but with Ternary it will raise an exception, depending on the language being used.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay