Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quirky output python

Tags:

python

Please explain below, I think it should have printed True or False since these are boolean expressions. And why it's printing 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
like image 391
garg10may Avatar asked Dec 18 '14 06:12

garg10may


1 Answers

Why you think the result must 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 evaluated and the resulting value is returned.

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.

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.

like image 148
Mazdak Avatar answered Oct 24 '22 17:10

Mazdak