Ternary Operator in Python

Hello, my viking warriors!, Welcome to my humble post once again! Today we are going to talk about an interesting statement in Python that can make our code lighter and our lives easier when it comes to coding.

Perhaps for some of you folks coming from languages such as C++, java and C#, and even JavaScript with some of the modern EcmaScript features, the term ternary operators might sound like our everyday hot cup of coffee. If you were wondering if this exist in Python, let me tell you YES, they are also part of the python world. We wouldn't dare to believe that Van Rossum would let this magnificent statement slide, would we?

What is a ternary operator, anyways?

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

How does a ternary operator works?

There are 3 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 in a ternary operator 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.
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

First, we will start with the regular conditional statement structure that we are all used to as developers:

# 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 type of structure, however, we could go a bit more pythonista and apply some touches to the code as follows:

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

That looks cleaner, and cooler, Pythonista way is awesome! Let's go ahead and try this approach with another example:

# 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 more obscure and not widely used example involves the use of tuples. I know, right? That sounds a bit more complex and less effective than the last one: Well, it is not and you will see it in the following sample code:
Syntax: (if_test_is_false, if_test_is_true)[test]

# 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}!"
)

It wasn't that hard after all, was it? Well, if we need to go simple and plain again, let's try the shorthand ternary statement instead, shall we, folks?

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

Not clear enough? Don't worry, we can even try it in another way by involving some functions on it, I can see you're getting itchy feet for this already so let's do it!

# Apply this principle to a function, shall we
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

Now that we have fractionated all of these solutions, let's put together a final source code fo you guys to test it out and play with it. Please leave your comments with some other approaches or better solutions, to update the post if needed. Thank you so much for reading us, folks!

# -------------------------------------------------------------------
# Ternary Operators in Python 3 - several cases & scenarios examples
# var = true_val if condition else false_val
# Made with ❀️ in Python 3 by Alvison Hunter - October 14th, 2021
# -------------------------------------------------------------------

# 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)
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 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 more obscure and not widely used example involves tuples.
# Here is some sample code: (if_test_is_false, if_test_is_true)[test]
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}!"
)


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

# Apply this principle to a function, shall we
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")

❀️ If you enjoyed this article, that motivates to write more!
πŸ¦„ If you truly consider this article helped you wholly!
πŸ”– If you need to check back on this article later on.
πŸ€” Please leave your comment, your opinion very important.

24