Reputation: 11
In python why this statement is giving false:- print(3 < (2 or 10)) Shouldn't it give true? Please explain
Upvotes: 1
Views: 640
Reputation: 1
python starts from left so here 3 is not greater than 2 which is why it is showing as false. I hope you understand.
Upvotes: -2
Reputation: 359
Python always iterate from left --> right so when program see that there is first value is something and then there is or statement then it stops iterating and take the value which was first. In Your case it itrate first 2 or 10
and take 2 and 3 is greater than 2 . So here your statement is false.
Upvotes: -1
Reputation: 6251
Playing around with it in the shell might already make it clear what is happening:
>>> 3 < (2 or 10)
False
>>> (2 or 10)
2
>>> (0 or 10)
10
>>> (1 or 10)
1
Of course, if (2 or 10)
is equal to 2
, then 3
is not smaller.
See also in the docs:
The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
Integers are usually True
, except for 0
and None
. That can be found here:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__()
method.
Upvotes: 2
Reputation: 30639
(2 or 10)
is 2
as evaluation stops (shortcuts) as soon as the result is clear. And 3 < 2
is false.
Upvotes: 2
Reputation: 34
print(2 or 10)
prints 2
print(10 or 2)
prints 10
print(3 < (2 or 10))
means print(3 < 2)
which is False
Upvotes: 1