About or & and operator [duplicate] - python

This question already has answers here:
Logical operators in Python [duplicate]
(4 answers)
Closed 4 years ago.
How the logical operators i.e;(or, and) works on the strings or numbers?
Example:
print(2 or 3)--> o/p: 2
print('two' or 'three')--> o/p: 'two'
I want to know how internally it works and reason behind the output's

or will "choose" the first thing if it is not False, else the second one:
print(2 or 3) # non-0 numbers are True
print('two' or 'three') # non empty strings are True
print(0 or 3) # 0 is False
print('' or 'three') # empty string is False
Output:
2
two
3
three
Certain "things" are considered False.
See and,or,not and Logical comparisons:
Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a bool() method that returns False or a len() method
that returns zero, when called with the object. [1] Here are most of
the built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)

Related

Understanding what if <list> does? [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 1 year ago.
I was going through the book "Deep Learning with Python" and came across the following:
def smooth_curve(points, factor=0.9):
smoothed_points = []
for point in points:
if smoothed_points:
previous = smoothed_points[-1]
smoothed_points.append(previous * factor + point * (1 - factor))
else:
smoothed_points.append(point)
return smoothed_points
smooth_mae_history = smooth_curve(average_mae_history[10:])
I've never seen this notation before, the 4th line of code "if smoothed_points". Smoothed_points is a list. I don't understand how lists can evaluate to either true or false in some orderly way.
Non-empty collections like lists are always considered True in Python.
From the documentation:
Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a __bool__() method that returns False or a __len__() method
that returns zero, when called with the object. Here are most of the
built-in objects considered false:
constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1) empty sequences and
collections: '', (), [], {}, set(), range(0)
You're right that this could seem a little weird in some circumstances:
if [False]:
print(True) # Prints True
It's a design decision, ensuring that (in your words) "lists can evaluate to either true or false in some orderly way". The orderly way the designers of Python have chosen is that empty objects are generally False and objects with stuff in them are generally True.

if decision with list variable [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 years ago.
In C/C++, true is standardized as 1, and false as 0. Although not a good practice,
if variable:
#do something
kind of decision making seems ok in python and it seems makes decision based on whether variable is None or is zero - if it is a number. Followings are reasonable.
a = 123123
if a:
print "if condition is true" # this prints
a = "a string"
if a:
print "if condition is true" # this prints
a = None
if a:
print "if condition is true" # this does not print
However, I wonder why it evaluates to false with an empty list, which is neither None, nor zero. What is the exact implementation of python if statement?
a = [] # a is not None
if a:
print "true" # this does not print
An if statement requires a bool. That means the the expression following the if is analyzed is a boolean context. Said differently it is converted to bool.
If a bool context, the following items evaluate to False (non exhaustive list):
None
numeric 0
empty list
empty string
empty dict
Non null numerics and non empty iterables eveluate to True
Lists are empty, so they're False, that's how python reacts, to know whether something is False so doesn't go trough, do:
>>> bool([])
False
>>>
So it is False.

Why does 'a' and 'b' equal 'b' in Python? [duplicate]

This question already has answers here:
How do "and" and "or" act with non-boolean values?
(8 answers)
How does the logical `and` operator work with integers? [duplicate]
(2 answers)
"4 and 5" is 5, while "4 or 5" is 4. Is there any reason? [duplicate]
(4 answers)
Closed 3 years ago.
What does 'a' and 'b' in Python mean and why does it equal 'b'? Why does it not equal 'a'?
>>> 'a' and 'b'
'b'
From the Pycharm docs:
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.
Because 'a' is not False 'b' is evaluated and returned.
Also nice to know. What is evaluated as True and what as False:
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.
Either 'a' or 'b' would be an acceptable answer to 'a' and 'b' (since both are truthy), but only False would be an acceptable answer to 'a' and False, just as only 0 would be an acceptable answer to 'a' and 0 (since the result of this evaluation must be false-y to be logically correct).
Having a short-circuiting boolean evaluation follow the right-hand path when the left-hand is true allows there to be a single rule that applies in all cases.

What are the true and false criteria for a python object? [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have seen the following cases:
>>> def func(a):
... if a:
... print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False
Why does this difference occur?
All objects1 in Python have a truth value:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.
All other values are considered true — so objects of many types are always true.
1 … unless they have a __bool__() method which raises an exception, or returns a value other than True or False. The former is unusual, but sometimes reasonable behaviour (for example, see the comment by user2357112 below); the latter is not.
When you type if a:, it is equivalent to if bool(a):. So it doesn't mean that a is True, only that a's representation as a boolean value is True.
Generally speaking bool is a subclass of int, where True == 1 and False == 0.

Strange conversion in Python logic expressions

I noticed a strange behavior of Python 2.7 logic expressions:
>>> 0 and False
0
>>> False and 0
False
>>> 1 and False
False
>>> False and 1
False
and with True in place of False
>>> 0 and True
0
>>> True and 0
0
>>> 1 and True
True
>>> True and 1
1
Are there any rules when Python convert logical statement to integer? Why does it show sometimes 0 insted of False and 1 insted of True?
What is more, why does it return this?
>>>"test" or "test"
'test'
Nothing is being converted; the Python boolean logic operators instead short circuit.
See the boolean operators documentation:
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.
Moreover, numbers that are equal to 0 are considered falsey, as are empty strings and containers. Quoting from the same document:
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).
Combining these two behaviours means that for 0 and False, the 0 is considered false and returned before evaluating the False expression. For the expression True and 0, True is evaluated and found to be a true value, so 0 is returned. As far as if and while and other boolean operators are concerned, that result, 0 is considered false as well.
You can use this to provide a default value for example:
foo = bar or 'default'
To really convert a non-boolean value into a boolean, use the bool() type; it uses the same rules as boolean expressions to determine the boolean value of the input:
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool([])
False
>>> bool(True and 0)
False
>>> bool(1)
True
To complete the picture, values that are not considered false in a boolean context are instead considered true, including any custom classes. You can change that by implementing a .__nonzero__() special method on your class. If no such method is defined, .__len__() is consulted as well. With either of these methods you can signal that your type is either numeric and should be considered True if non-zero, or it is a container and should be considered True if not empty (has a length over 0).
Python always return one of the operand objects
and returns the first "false" object or the final "true" object.
or returns the first "true" object or the final "false" object.
Note that all 0, 0.0, False, "" are regarded as "false".
>>> "a" and "b" and "c"
'c'
>>> "a" or "b" or "c"
'a'
That's because 0 is s falsy value itself.
>>> bool(0)
False
>>> bool(1)
True
0 and True is 0 because 0 is Falsy ,AND condition stops executing as soon as first falsy value is found and returns that value. If all values were True then the rightmost value is returned.
OR will keep on checking values until first True is not found otherwise it returns the last value.(righmtmost)
From the docs:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

Categories

Resources