please explain this code in python. why it outputs 10 at both, print statements? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

please explain this code in python. why it outputs 10 at both, print statements?

# Python program to demonstrate ternary operator a, b = 10, 20 # Use tuple for selecting an item print( (b, a) [a < b] ) # Use Dictionary for selecting an item print({True: a, False: b} [a < b]) output: 10 10

6th Apr 2020, 1:28 PM
Sujithra
3 Answers
+ 3
a,b = 10,20 This means a = 10 b = 20 now print( (b,a) [a<b] ) (20,10) [10<20] Since the condition is true so it returns 1 (20,10) [1] 0 1 So index 1 is 10 Similarly print({True:a, False:b} [a<b]) Condition is still true here And the key True has value a Which is 10
6th Apr 2020, 1:31 PM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 1
Thank u fr ur clear explanation.. Utkarsh Sharma and visph .👍🏻
6th Apr 2020, 1:34 PM
Sujithra
+ 1
in the second case there is a key True in the dict, with the value of a (10) in the first case the tuple has two elements (b,a), in wich there's two indexes (0,1) for accessing the value. The trick is that under the hood, boolean value are 0 for False and 1 for True, so you print the value at index True == 1 (10)
6th Apr 2020, 1:34 PM
visph
visph - avatar