Ternary Operator in Python
• What is Python Ternary Operator?
• In the Python programming language, the Ternary Operator is a
condition expression that allows developers to evaluate
statements.
• The Ternary Operators perform an action based on whether the
statement is True or False.
• As a result, these operators are shorter than a standard if-else
statement.
• Syntax of Python Ternary Operator with Example
• Python’s ternary operators, as the name implies, require three
operands to function.
• The Python ternary statement has the following syntax:
• <variable> = <true_value> if <condition> else <false_value>
• The three operands are as follows:
• 1. condition: A Boolean expression must be evaluated to determine whether it is true or
false.
• 2. true_value: A value assigned if the condition is true.
• 3. false_value: A value to be assigned if the condition is false.
• Ternary Operators are commonly used to determine the value of a variable. If the condition
is True, the variable takes on the value “true value,” else it takes on the value “false value.”
• Example for Ternary Operator Implementation
• Let’s return to the earlier-mentioned example, where we wish to
provide a consumer at the medical store a discount if they are 65
or older.
• Customers who are not 65 or older are not eligible for a
discount.
• Code and Output for if-else Implementation
• To grasp the difference between the Python ternary operator
and the if-else statement approach, let’s start with the if-else
statement.
• # Taking input of your age
• a = int(input("Enter Your Age : "))
• #if condition to check if age>=65 or not
• if(a>=65):
• print("\nYay! 30% Discount!")
• #if age<65
• else:
• print("\nSorry! No Discount!")
• Output if 67 is the input:
• Enter Your Age : 67Yay! 30% Discount!
• Code and Output for Ternary Operator Implementation
We can now use the syntax of the ternary expression to make
this program much more compact.
• # Taking input of your age
• a = int(input("Enter Your Age : "))
• # <result if cond. is T> if <cond.> else <result if cond. is F>
• result = "30% Discount!" if (a>=65) else " No Discount!"
• print(result)
• Here is a simple and easy Python program that uses the ternary
operator method to find the smaller of two values.
• # Take input of two numbers
• a = int(input())
• b = int(input())
• # check which is smaller
• result = a if a<b else b
• print("Smaller Number is: ",result)