+ 1

Python help

Hello, I'm facing doubts regarding 2 small code blocks. Please, can you explain the 2 codes ? 1/ x=1 for i in range(5): x=0 x=x+1 print(x) 2/ a=7 b=a>5 and 'a' or 'b' print(b) For the 1st one, the output is 1 and whatever the value set up for x and whatever the value in range(). For th 2nd one, the result is a. Thank you very much BR

18th Feb 2019, 3:51 PM
Fabien
Fabien - avatar
5 Answers
+ 6
a > 5 is True, 'a' is also True (because every non-empty expression evaluates to True in Python). So, in "a > 5 and 'a'", both expressions are True. If you compare two (or more) expressions with "and" and all of them evaluate to True, the last of the expressions is returned. That's why a > 5 and 'a' evaluates to 'a' (the "or 'b'" part doesn't matter. It would only be checked if the first part were not True).
18th Feb 2019, 4:33 PM
Anna
Anna - avatar
+ 5
Seniru Pasan That's one of Python's peculiarities. It will always return the value of the last element that evaluates to True. Not sure why it was implemented that way, I agree that it's something you wouldn't really expect to happen 🤔 You can use bool() though to get either True or False: bool(a > 5 and 'a' or 'b') # True
18th Feb 2019, 4:38 PM
Anna
Anna - avatar
+ 3
1 question... Even though the output is likely to become 5 it is not. Look at the x=0 initialization in the loop. It will assign x to 0 each time it loop over. so at the end of the loop x = 1 Therefore print(x) will output 1 2nd I m not sure about this thing. This makes me remind of of luas ternary operators. Not going to answer this because I m not rlly sure. Sorry
18th Feb 2019, 4:00 PM
Seniru
Seniru - avatar
+ 2
Thank you Seniru for your explananation regarding the 1st one. I get it !
18th Feb 2019, 4:03 PM
Fabien
Fabien - avatar
+ 2
Anna but how it return a character. I thought this will give a boolean value in python
18th Feb 2019, 4:35 PM
Seniru
Seniru - avatar