+ 2

Conditional expression/Ternary Operator help please

a = 7 b = 1 if a >= 5 else 42 print(b) a = 4 print(b) OUTPUT: >>> 1 1 >>> WHY is the 2nd line of OUTPUT equal to 1 instead of 42? Thanks

1st Sep 2016, 8:30 AM
Krishna Limani
Krishna Limani - avatar
3 odpowiedzi
+ 6
You have to repeat the check: b was checked only once, right after a was assigned 7. There is no check after a was changed, and b stayed the same.
31st May 2017, 9:57 PM
Nikola Jovanovic
Nikola Jovanovic - avatar
+ 3
because you have to reassign b value once more after reassigning a. b was calculated before and stays the same until you assign something new to it. apply the same ternary operator after reassigning a and before printing b
1st Sep 2016, 8:40 AM
Demeth
Demeth - avatar
+ 2
I think we are just printing b with out considering ternary operator in the second line I think if we use b=1 if a>=5 else 42 after a=4 it would print 7
11th May 2017, 1:52 AM
sandeep
sandeep - avatar