Python Ternary Operator with example

when it comes to learning to code Python, you'll soon discover that mastering the fundamentals is essential. One fundamental tool that can greatly enhance your Python coding skills is the ternary operator.

The ternary operator is a valuable tool to have in your programming arsenal. It allows you to write conditional statements in a single line, making your code more compact and elegant. In this blog post, we will explore the Python ternary operator and provide examples of how to use it effectively.


what is the Ternary Operator?



The ternary operator in Python is a concise way to write simple conditional expressions. It is also known as the conditional operator or the ternary conditional operator. The syntax of the ternary operator is as follows:



<expression_if_true> if <condition> else <expression_if_false>


Here's how it works: If the condition is true, the expression before the 'if' keyword is evaluated and returned; otherwise, the expression after the 'else' keyword is evaluated and returned. It's a easy and compact way to replace simple 'if-else' statements.


Examples of Python Ternary Operator



Let's dive into some practical examples to see how the Python ternary operator can simplify your code as you learn to code Python basics effectively.


Assigning a Value Based on a Condition




# Using a ternary operator to assign a value based on a condition

age = 12
message = "You are eligble for govt group exam" if age < 30 else "You are not eligble for govt group exam"
print(message)  # Output: You are not eligble for govt group exam


In this example, we assign the value of 'message' based on the condition 'age < 30'. If the condition is true, the first expression ("You are eligble for govt exam") is assigned to 'message'. Otherwise, the second expression ("You are not eligble for govt exam") is assigned.


Returning Values from a Function



You can use the ternary operator to return values from functions based on conditions.



# Returning a value from a function using a ternary operator
def get_discount(purchase):
    return 0.2 if purchase < 1000 else 0.1

print(get_discount(800))  # Output: 0.2
print(get_discount(1100))  # Output: 0.1


In this example, the get_discount function returns a discount rate based on the Purchase passed as an argument.


List Comprehension



The ternary operator is often used in list comprehensions to conditionally transform elements in a list.



# Using a ternary operator in list comprehension
numbers = [1, 2, 3, 4, 5]
squared = [x**2 if x % 2 == 0 else x for x in numbers]
print(squared)  # Output: [1, 4, 3, 16, 5]


Here, we square the even numbers in the numbers list while leaving the odd numbers unchanged.


Dictionary Initialization



You can also use the ternary operator when initializing dictionary values conditionally.



# Initializing dictionary values using a ternary operator
age = 25
user_info = {"status": "application accept" if age < 30 else "application not accepted for age above 30"}
print(user_info)  # Output: {'status': 'application accept'}


In this case, the user_info dictionary is populated based on the age of the user.


When to Use the Ternary Operator



The ternary operator is most suitable for simple, one-liner conditional expressions. While it can make your code more concise and readable when you learn to code basics effectively and it's essential to maintain code clarity. Avoid nesting ternary operators or using them for complex logic, as it can harm readability.


The Python ternary operator is a powerful tool for writing concise and readable code when dealing with straightforward conditional expressions. It allows you to streamline assignments, function returns, list comprehensions, and dictionary initialization. By understanding how to use the ternary operator effectively, you can enhance the elegance and readability of your Python code.


Previous Post Next Post