Quirky output python

Please explain below, I think it should have printed True or False, as these are logical expressions. And why does it print 2 1 and then 1 2

print 1 and 2 print 2 and 1 print 1 or 2 print 2 or 1 

output:

 2 1 1 2 
+6
source share
1 answer

Why do you think the result should be a boolean type?

from python wiki:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise y is calculated and the result is returned .

An expression x or y first evaluates x; if x is true, its value is returned; otherwise y is calculated and the result is returned .

Note that neither , nor , nor or limit the value and type, they return to False and True, but rather return the last evaluated argument. This is sometimes useful, for example, if s is a string that should be replaced with a default value, if it is empty, the expression s or 'foo' gives the desired value. Since in any case there is no need to invent a value, it does not deign to return a value of the same type as its argument, so, for example, not 'foo' gives the value False, not '' .

+5
source

Source: https://habr.com/ru/post/979829/


All Articles