0
What is the reason behind the output of statement?
print('a' or 'b') Output=a
2 Respuestas
+ 2
Read full answer... I might go off topic below! And I might be wrong.
I think because or operator is mainly used for condition so in if condition it might be like.
if 'a' or 'b' in list:
Print("present")
In above statement, if a is not present in list, it will check b.
BUT if condition is satisfied with 'a' then 'b' will be skipped. AND it will prioritise the first condition (here 'a')
Similarly in print('a' or 'b')
No particular condition is given so both are taken as True. So it will prioritise what is written first and print it. For example--
print('a' or 'b')
Output = 'a'
print('b' or 'a')
Output = 'b'
It will print what you have written first if condition is true(Or no condition is given).
0
Logical operators and & or won't convert their result into booleans, but instead they are using a certain logic:
A and B:
A if not A else B
A or B:
A if A else B
You also need to know that any values can be used as booleans. You might already know that 0 equals False and 1 equals True, similarly empty strings equal False and non-empty strings equal True.
Because 'a' & 'b' are both non-empty strings 'a' or 'b' evalueates to:
'a' if 'a' else 'b'
Because the 'a' (middle) equals True, the first operand 'a' is chosen.
Result: 'a'