In this tutorial, we will learn about ternary operator in Python. In Python, the ternary operator provides a concise way to write conditional expressions. It allows you to evaluate a condition and return different values based on the result of that condition. The ternary operator is often referred to as the “conditional expression” because it evaluates the condition and chooses between two possible expressions.
It consists of three components: the condition, the value to be returned if the condition is true, and the value to be returned if the condition is false. The operator evaluates the condition and chooses the appropriate value based on the result.
The condition is any expression that evaluates to either true or false. It can involve comparisons, logical operators, or any other expression that yields a Boolean result. If the condition is true, the value specified before the “if” keyword is returned. If the condition is false, the value specified after the “else” keyword is returned.
The ternary operator is particularly useful when you want to assign a value to a variable based on a condition without writing an entire if-else statement. It helps to reduce the number of lines of code and enhances code readability.
The ternary operator provides a powerful tool to write conditional expressions in a compact and readable manner. It can be a valuable addition to your Python coding toolkit, allowing you to handle conditional scenarios efficiently and effectively.
Ternary Operator Syntax
value_if_true if condition else value_if_false
value_if_true
: This is the value that will be returned if the condition evaluates to true. It can be any valid expression or variable.condition
: This is the expression that is evaluated for its truthiness. If the condition is true, the value before the “if” keyword is chosen.value_if_false
: This is the value that will be returned if the condition evaluates to false. It can also be any valid expression or variable and comes after the “else” keyword.
The ternary operator allows for a concise way of expressing conditional logic in a single line of code. It is commonly used for assigning values to variables based on a condition, simplifying the code and enhancing readability.
Example:
Let’s consider an example to understand its usage better. Suppose we want to assign a maximum of two numbers, a
and b
, to a variable max_num
. We can use the ternary operator to accomplish this in a concise manner:
a = 10
b = 5
max_num = a if a > b else b
In the example above, the ternary operator evaluates the condition a > b
. If the condition is true (which it is in this case since a
is greater than b
), the value of a
is assigned to max_num
. If the condition is false, the value of b
is assigned.
Example:
Here’s a Python program that utilizes the ternary operator to determine if a number is even or odd:
def check_even_odd(num):
result = "Even" if num % 2 == 0 else "Odd"
return result
# Example usage
number = 7
result = check_even_odd(number)
print("The number", number, "is", result)
number = 12
result = check_even_odd(number)
print("The number", number, "is", result)
Output:
The number 7 is Odd
The number 12 is Even
In this program, the check_even_odd
function takes a number as input and uses the ternary operator to determine if it is even or odd. The condition num % 2 == 0
checks if the number is divisible by 2 without a remainder. If the condition is true, this operator returns the string “Even”; otherwise, it returns the string “Odd”.
The program demonstrates the usage of this operator to determine the parity of two different numbers. The output confirms whether each number is even or odd based on the result returned by this operator.
Python Ternary Operator Using Tuples, Dictionary and Lamba Function
Now that we have an understanding of how the ternary operator works in Python, let’s explore its application with tuples, dictionaries, and lambda functions. However, before we delve into those examples, let’s start with a simple program that finds the greatest of two numbers. This program will provide us with a clear picture of our objective and set the foundation for applying the ternary method in conjunction with Python’s tuples, dictionaries, and lambda functions.
Ternary Operator Using Tuples
Certainly! Here’s a unique Python program that demonstrates the usage of the ternary operator with tuples and provides the corresponding output:
# Ternary Operator with Tuples Example
# Input numbers
num1 = 10
num2 = 5
# Using ternary operator with tuples
result = (num1 if num1 > num2 else num2)
# Output
print("The greatest number is:", result)
Output:
The greatest number is: 10
In this program, we have two input numbers: num1
and num2
. We use the ternary operator (num1 if num1 > num2 else num2)
to find the greatest number between num1
and num2
.
The ternary operator evaluates the condition num1 > num2
. If the condition is true, it returns num1
; otherwise, it returns num2
.
In this case, num1
is greater than num2
, so the output displays “The greatest number is: 10”.
Ternary Operator Using Dictionary
Here’s a unique Python program that demonstrates the use of the ternary operator with a dictionary to determine the status of a student based on their exam score:
# Ternary Operator with Dictionary Example
# Define a dictionary with score thresholds and corresponding status
score_thresholds = {
90: "Excellent",
80: "Very Good",
70: "Good",
60: "Average",
0: "Fail"
}
# Get the student's exam score
score = int(input("Enter the exam score: "))
# Determine the status using the ternary operator
status = score_thresholds[max(filter(lambda x: x <= score, score_thresholds.keys()))]
# Print the result
print("Student Status:", status)
Output:
Enter the exam score: 85
Student Status: Very Good
In this program, we have a dictionary called score_thresholds
that contains the score thresholds as keys and the corresponding status as values. This operator is used to determine the status based on the student’s exam score.
We take input from the user for the exam score using the input()
function and convert it to an integer. The ternary operator expression score_thresholds[max(filter(lambda x: x <= score, score_thresholds.keys()))]
finds the maximum threshold from the keys of the score_thresholds
dictionary that is less than or equal to the student’s score. It then retrieves the corresponding status value.
Finally, the program prints the determined status using the print()
function. In the provided example, an exam score of 85 results in the status “Very Good.”
Ternary Operator Using Lamba Function
Here’s a unique Python program that demonstrates the use of this operator with a lambda function:
# Ternary Operator with Lambda Function
# Define the lambda function
greatest = lambda a, b: a if a > b else b
# Take user input
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Find the greatest number using the ternary operator with the lambda function
result = greatest(num1, num2)
# Output the result
print("The greatest number is:", result)
Output:
Enter the first number: 10
Enter the second number: 5
The greatest number is: 10
In this program, we define a lambda function called greatest
that takes two arguments, a
and b
. The lambda function uses the ternary operator to compare the values of a
and b
. If a
is greater than b
, it returns a
; otherwise, it returns b
.
The program then prompts the user to enter two numbers. These numbers are stored in the variables num1
and num2
.
Next, we call the greatest
lambda function with num1
and num2
as arguments. The operator within the lambda function determines the greatest number among the two inputs.
Finally, the program outputs the result, displaying the greatest number.
We can try running the program and entering different numbers to see the output change accordingly.