- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python CGI Programming
- Python Network Programming
- Python Send E-mail
- Python Multi-threading
- Python XML Processing
- Python MySQL Database
- Python GUI Programming
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
Python Ternary Operator
In this tutorial, you'll learn all about Ternary operator along with its example. This tutorial deals with simple ternary operator as well as nested ternary operator.
What is Ternary Operator in Python ?
Ternary operator in Python is basically a short-cut version of if-else statement. That is, using ternary operator, we can write at least 4 lines of code (using if-else) in only one line (using ternary operator).
Ternary Operator Syntax
The syntax to use ternary operator in Python is little different from other programming languages, but is more clear and understandable just like normal English. Here is its syntax.
x if expression else y
This is like normal English we use, that is evaluate x if expression evaluates to be true, otherwise (else) evaluate y. Therefore above syntax can also be written like:
on_true if expression else on_false
For example:
print("10") if val==10 else print("Not 10")
The above code prints 10 on output, if the value of variable val is equal to 10, otherwise prints Not 10.
How Multiple Lines of Code can be Replaced with 1 Line ?
Of course, this can be done using ternary operator. Here is a code of multiple lines, that is going to replace with single line using ternary operator:
num = 10 if num > 20: print("Greater than 20") else: print("Less than 20")
The output produced by above Python program is:
The above program can be replaced using Ternary operator like shown in the program given below:
num = 10 print("Greater than 20") if num > 20 else print("Less than 20")
As you can see, 4-lines of code gets replaced with single line. Now you can understand, how useful ternary operator is.
Python Ternary Operator Examples
I know, until now, you understand about ternary operator. But let me so you some more varieties of ternary operator in Python. This helps you to understand it more clearly.
print("Which website, you like most ? ", end="") web = input() print("\nNice") if web=="codescracker" else print("\nOps!")
Here is the initial sample output produced by above Python program on ternary operator:
Now supply the input say codescracker and press ENTER
key to see the output like shown in the snapshot
given below:
Here is another ternary operator example program, that shows the most common use of Python ternary operator:
print("Enter any two Numbers: ") num_one = int(input()) num_two = int(input()) largest = num_one if num_one > num_two else num_two print("The largest number is:", largest)
Here is its sample run with user input 10 and 20:
Nested Ternary Operator
Ternary operator inside another ternary operator is known as nested ternary operator. This is not limited to use only one ternary operator inside another. You can nest multiple ternary operators in one single line of code of course.
Nested Ternary Operator Syntax
The syntax to use nested ternary operator is:
(on_true if expression else on_false) if expression else (on_true if expression else on_false)
Don't worry (if not getting idea about its working), follow the example given below and its brief step by step description. You will understand about its working.
Nested Ternary Operator Example
The famous example of using nested ternary operator is to find largest/smallest of three numbers. This time, I'm going to create a program using nested ternary operator that find and prints largest of three given numbers:
print("Enter any three Numbers: ") a = int(input()) b = int(input()) c = int(input()) largest = (a if a > c else c) if a > b else (b if b > c else c) print("\nLargest =", largest)
Here is its sample run with user inputs 10, 30, and 20:
Let's briefly explain the nested ternary operator from above program. I'm sure, after reading all the lines given below, that explains about the nested ternary operator carefully, you'll get complete understanding about the both ternary and nested ternary operator. Now from above program, the following code:
(a if a > c else c) if a > b else (b if b > c else c)
gets evaluated in a way that:
- First,
a > b
gets evaluated. - Now whether the left ternary operator statement gets evaluated or the right one gets evaluated, is totally depends on the boolean result of the expression a > b
- That is, if it evaluates to be true, then the left one gets evaluated
- Otherwise the right ternary operator statement gets evaluated
- Since with sample run provided above, the expression a > b or 10 > 30 evaluates to be False
- Therefore the right ternary operator statement gets evaluated, and the left one gets skipped
- The right ternary operator statement is,
(b if b > c else c)
- In this statement again, if the expression
b > c
evaluates to be true, therefore b will be the final result of whole statement - Otherwise c will be the final result of whole statement
- But in this case, since the expression b > c or 30 > 20 evaluates to be true
- Therefore b will be the final result of whole statement
- And b's value, that is 30 gets initialized to variable named largest
- In this way, the nested ternary operator in Python works
Note - Just remember one thing, True for left, False for right. That is, if the expression evaluates to be True, then left one gets evaluated, otherwise right one gets evaluated.
« Previous Tutorial Next Tutorial »