Unlock the Power of Python Ternary Operators
Tags: python, programming, algorithms, tutorial
Published: 2021-10-15 03:05:10

**Hello, my viking warriors!**,  Welcome back to my humble post once again! Today, we're diving into an intriguing Python statement that can lighten our code and make our lives easier as developers. 

For those of you hailing from languages like C++, Java, and C#, and even JavaScript with its modern EcmaScript features, the term ternary operators might sound like our everyday hot cup of coffee. Wondering if this nifty tool exists in Python? Yes, indeed! Python wouldn't be the same without it. Thank you, Guido van Rossum, for not letting this magnificent statement slide!

#### What is a ternary operator, anyways?
The ternary operator is a concise way of writing conditional statements in Python. As the name suggests, this Python operator consists of three operands.

**How does a ternary operator work?**
There are three operands in the ternary operator. If the condition of the first operand is met and returns true, the second operand expression is executed. Otherwise, the third operand expression is called.

These three operands include:

- **condition:** A boolean expression that evaluates to either true or false.
- **true_val:** A value to be assigned if the expression is evaluated to true.
- **false_val:** A value to be assigned if the expression is evaluated to false.
```python
bool_value = true_val if condition else false_val
```
The variable **bool_value** on the left-hand side of the = (assignment) operator will be assigned to:

- **true_val** if the booleanExpression evaluates to true.
- **false_val** if the booleanExpression evaluates to false.

Let's take a look at some examples of how to put these bad boys into real world action when using python, shall we? 

### Regular if-else statement
We'll start with the regular conditional statement structure that we're all used to as developers:

```python
# using regular if then conditional statement
response = ""
n1 = int(input("Please Enter a Number: "))
if(n1%2 == 0):
  response = "Even"
else:
  response = "Odd"
print(response)
```

There is absolutely nothing wrong with using this structure. However, we can go a bit more Pythonista and apply some sleek touches to the code as follows:
```python
# using the ternary operator
n2 = int(input("Please Enter a Number: "))
print("Even" if n2 % 2 == 0 else "Odd")
```
Doesn't that look cleaner and cooler? The Pythonista way is awesome! Let's try another example:
```python
# another good example for the ternary operator
ask_developer = input("Do you love Python? (y/n): ").lower()
loves_python = True if ask_developer == "y" else False
print("You're the Coolest, dude!" if loves_python else "You should learn Python!")
```
Another example involves the use of tuples. This might sound complex, but it's pretty straightforward:
__Syntax:__ *(if_test_is_false, if_test_is_true)[test]*

```python
# ternary combined with tuples to check both scenarios easier
dev_response = input("Do you love Python? (y/n): ").lower()
python_lover = True if dev_response == "y" else False
fav_lang = ("JavaScript", "Python")[python_lover]
print(
    f"You're a Python zealot, dude!"
    if (python_lover == True)
    else f"You probably love frigging {fav_lang}!"
)
```
Not too hard, right? Let's try the shorthand ternary statement:
```python
# ShortHand Ternary
api_response = None
print(api_response or "No data returned")
```
Still not clear? Let's involve some functions now:
```python
# Apply this principle to a function
def my_function(real_name, optional_display_name=None):
    optional_display_name = optional_display_name or real_name
    print(optional_display_name)

# This one should return Alvison Lucas
my_function("Alvison Lucas")

# This one should return Liam Andre  
my_function("Declan Jaleel", "Liam Andre")
```
***

####Final Source Code
Here's the complete source code for you to test out and play with. Leave your comments with other approaches or better solutions, so we can update the post if needed. Thank you so much for reading this article, folks!
```python
# ---------------------------------------------------------
# Python Ternary Operators - Some basic examples
# var = true_val if condition else false_val
# Made with ❤️ in Python by Alvison Hunter | May 19th, 2024
# ---------------------------------------------------------

# using regular if-else conditional statement
response = ""
n1 = int(input("Please Enter a Number: "))
if n1 % 2 == 0:
    response = "Even"
else:
    response = "Odd"
print(response)
rd = input("Hit << Enter >> to continue")

# using the ternary operator
n2 = int(input("Please Enter a Number: "))
print("Even" if n2 % 2 == 0 else "Odd")

# another example for the ternary operator
ask_developer = input("Do you love Python? (y/n): ").lower()
loves_python = True if ask_developer == "y" else False
print("You're the coolest, dude!" if loves_python else "You should learn Python!")

# another example involving tuples
dev_response = input("Do you love Python? (y/n): ").lower()
python_lover = True if dev_response == "y" else False
fav_lang = ("JavaScript", "Python")[python_lover]
print(
    f"You're a Python zealot, dude!"
    if python_lover
    else f"You probably love {fav_lang}!"
)

# ShortHand Ternary
api_response = None
print(api_response or "No data returned")

# Apply this principle to a function
def my_function(real_name, optional_display_name=None):
    optional_display_name = optional_display_name or real_name
    print(optional_display_name)

# This one should return Alvison Lucas
my_function("Alvison Lucas")

# This one should return Liam Andre  
my_function("Declan Jaleel", "Liam Andre")
```
***
Thanks for reading this article! I hope you enjoyed it as much as I did writing it. Until next time, dear readers!

❤️ Enjoyed the article? Your feedback fuels more content.
💬 Share your thoughts in a comment.
🔖 No time to read now? Well, Bookmark for later.
🔗 If it helped, pass it on, dude!