简体   繁体   中英

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

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.

(2 or 10) is 2 as evaluation stops ( shortcuts ) as soon as the result is clear. And 3 < 2 is false.

  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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM