Sayan Ghosh
Sayan Ghosh

Reputation: 11

In python why this statement is giving false:- print(3 < (2 or 10))

In python why this statement is giving false:- print(3 < (2 or 10)) Shouldn't it give true? Please explain

Upvotes: 1

Views: 640

Answers (5)

user28243313
user28243313

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

Vishal Pandey
Vishal Pandey

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

lucidbrot
lucidbrot

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 evaluates x; if x 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

Stef
Stef

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

wozverine
wozverine

Reputation: 34

  1. print(2 or 10) prints 2
  2. print(10 or 2) prints 10
  • Therefore, print(3 < (2 or 10)) means print(3 < 2) which is False

Upvotes: 1

Related Questions