📜  python turnary - Javascript (1)

📅  最后修改于: 2023-12-03 14:46:05.485000             🧑  作者: Mango

Python Turnary - Javascript

If you're familiar with Javascript, you might have heard of the "ternary operator". This is a conditional operator that is often used to make code more concise by allowing you to write a quick ternary expression instead of a longer if-else statement.

In Python, there is no ternary operator per se, but there is a shorthand way of writing if-else statements that is often referred to as a "turnary" (a play on the word "ternary"). In this article, we'll explore the differences between ternaries in Javascript and turnaries in Python.

Turnary in Python

The syntax for a turnary in Python looks like this:

value_if_true if condition else value_if_false

where value_if_true is the value that is returned if the condition is true, and value_if_false is the value that is returned if the condition is false.

For example, let's say we have a variable x and we want to set its value to 1 if a condition is true, and to 0 otherwise. We could accomplish this with a turnary expression like so:

x = 1 if condition else 0

This is equivalent to the following if-else statement:

if condition:
    x = 1
else:
    x = 0
Ternary in Javascript

The syntax for a ternary expression in Javascript is similar to that of a turnary in Python:

condition ? value_if_true : value_if_false

In this case, condition is the condition that is evaluated, and value_if_true is the value that is returned if condition is true. value_if_false is the value that is returned if condition is false.

For example, let's say we have a variable x and we want to set its value to 1 if a condition is true, and to 0 otherwise. We could accomplish this with a ternary expression like this:

x = condition ? 1 : 0;

This is equivalent to the following if-else statement:

if (condition) {
    x = 1;
} else {
    x = 0;
}
Conclusion

While the syntax for ternaries in Javascript and turnaries in Python are similar, there are some important differences to keep in mind. For example, in Python, you can assign the result of a turnary expression directly to a variable, while in Javascript, you need to use an explicit assignment statement.

Regardless of the syntax differences, both ternaries and turnaries are useful for writing more concise and readable code, and are a valuable tool in any programmer's toolbox.