In python ternary operator is used to return a value based on the result of a binary condition. first It takes the binary value(condition) as an input, so it looks similar to an “if-else” condition block, and replace the multiple lines of if-else, to reduce the complexity.
Syntax of Simple Method
we will compare this with a if-else through a piece of code
x, y = 4,3
if x>y :
print ("x")
else :
print ("y")
output :
x
Now we will see same thing through the ternary operator
x, y = 4,3
print("x" if x>y else "y")
output :
x
Using Ternary and Dictionary
Now we will see the use of this operator directly in ternary and dictionary.
15
output :
15 15 15
Lets see this approach separately
In Tuple
a, b = random(), random()
(b, a) [a>b]
output :
0.5497848117028667
In Dictionary
a, b = random(), random()
{False: f"b:{b}", True: f"a:{a}"}[a>b]
output :
'a:0.8089581560973976'
Nested Ternary Operator
output :
b is greater than a
In this article i have explained about Ternary Operator.
Next Article : Any and All in Python
Recommended Post :
#python online
#python programming
#python list
#learn python
#python requests
#introduction to data science in python
#free python tutorial
#learn python basics
#python study
#python and ai
#python computer science
#learn python step by step
#best course to learn python
#python programming
#python list
#learn python
#python requests
#introduction to data science in python
#free python tutorial
#learn python basics
#python study
#python and ai
#python computer science
#learn python step by step
#best course to learn python
#ternary operator
#conditional operator
#ternary operator in python
2 Comments
After waiting for long .Valued content.
ReplyDeleteMore contents are on the way
DeleteIf you have any doubt, Please let me know.