I know logically and
is used for booleans evaluating to true if both the conditions are true, but I have a problem with the following statement:
print "ashish" and "sahil"
it prints out "sahil"?
another example:
return s[0] == s[-1] and checker(s[1:-1])
(taken from recursive function for palindrome string
checking
please explain it and other ways and is oveloaded ,especially what the second statement do.
This feature in Python, that allows same operator to have different meaning according to the context is called operator overloading.
It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading .
Python gives us the ability to modify the operation of an operator when used for specific operands. Every time we use an operator, Python internally invokes a magic method. In the case of +, Python invokes the __add__ method. We can redefine this method in our object’s class to create a custom operation for the + operator.
Now let's try the addition operation again: What actually happens is that, when you use p1 + p2, Python calls p1.__add__ (p2) which in turn is Point.__add__ (p1,p2). After this, the addition operation is carried out the way we specified.
and
is not overloaded.
In your code, "ashish"
is a truthy value (because non-empty strings are truthy), so it evaluates "sahil"
. As "sahil"
is also a truthy value, "sahil"
is returned to the print statement and is then printed.
x and y
basically means:
return
y
, unlessx
is False-ish - in such case returnx
Here is a list of possible combinations:
>>> from itertools import combinations
>>> items = [True, False, 0, 1, 2, '', 'yes', 'no']
>>> for a, b in combinations(items, 2):
print '%r and %r => %r' % (a, b, a and b)
True and False => False
True and 0 => 0
True and 1 => 1
True and 2 => 2
True and '' => ''
True and 'yes' => 'yes'
True and 'no' => 'no'
False and 0 => False
False and 1 => False
False and 2 => False
False and '' => False
False and 'yes' => False
False and 'no' => False
0 and 1 => 0
0 and 2 => 0
0 and '' => 0
0 and 'yes' => 0
0 and 'no' => 0
1 and 2 => 2
1 and '' => ''
1 and 'yes' => 'yes'
1 and 'no' => 'no'
2 and '' => ''
2 and 'yes' => 'yes'
2 and 'no' => 'no'
'' and 'yes' => ''
'' and 'no' => ''
'yes' and 'no' => 'no'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With