Python or and and operator trap

Usually in a programming languageorWhenand (Or||When&&Similar expressions such as)Is(Item 2)It means a logical operation. That is, the value returned by ʻor or ʻand is a bool value (True / False). In C-speaking languages, True / False is sometimes substituted by 1/0, but anyway, the logical operations or and and return the values corresponding to the logical values. However, in Python, ʻor and ʻand do not always return logical values. In Python, the expressions x and y are equivalent to:

if not bool(x):  #If the logical value of x is False
    return x  #Return x itself instead of False without seeing y
else:  #If the logical value of x is True
    return y  # bool(y)Not return y itself

Similarly, the expression x or y is equivalent to:

if bool(x):  #If the logical value of x is True
    return x  #Return x itself instead of True without seeing y
else:  #If the logical value of x is False
    return y  # bool(y)Not return y itself

In Python, noting that a string of length 0 has a Boolean value of False and a string of length 1 or greater has a Boolean value of True, we can summarize it as follows:

'123' or '456'  -> '123'  # bool('123')Is True, so the lvalue'123'Return
'123' or ''     -> '123'  # bool('123')Is True, so the lvalue'123'Return
''    or '456'  -> '456'  # bool('')Is False, so the rvalue'456'Return
''    or ''     -> ''     # bool('')Is False, so the rvalue''Return
'123' and '456' -> '456'  # bool('123')Is True, so the rvalue'456'Return
'123' and ''    -> ''     # bool('123')Is True, so the rvalue''Return
''    and '456' -> ''     # bool('')Is False, so the lvalue''Return
''    and ''    -> ''     # bool('')Is False, so the lvalue''Return

In the above example, ** True / False is not returned at all, even though it is the result of ʻor and ʻand **. If you want to ensure that the value returned by the binary logical operators (or and and) in Python is always the logical value True / False,bool (x) or bool (y)orbool Must be (x) and bool (y)(althoughbool (x or y),bool (x and y)is fine). Normally, you don't pass any value other than the logical value True / False as x or y, but it is sometimes forgotten becausebool (x)is evaluated automatically. The reason why this is happening is that it is often said that the handling of None is convenient. In Python, the logical value of None is False (bool (None)-> False), so the following code

#I don't know if x contains None
if x is None:
    x = '456'
# x = '456'I can write if x is None, but I personally don't like it

Can be replaced by ** x = x or '456' **. However, it is not ** equivalent **. The behavior when the empty string '' and the empty list [] are stored in x is different. If x contains'' or [], then both x is None andbool (x)are False. Therefore, in the case of code using ʻis None, xis not reassigned, In the case of code usingx or '456',' 456'is reassigned tox`.

Wait, what happens to ʻif x or y:`?

If ʻordoes not return a logical value, did it happen that usingx or y in ʻif worked? No, it wasn't a coincidence, it was inevitably successful. In Python, the truth value of the conditional expression of ʻif is determined without permission. In other words, the same thing as ʻif bool (x or y): is done without permission.

Recommended Posts

Python or and and operator trap
Python bitwise operator and OR
[Python] Boolean operator (or / and) does not return Boolean value
[Python] return A [or / and] B
[Python] Use and and or when creating variables
Connect a lot of Python or and and
Python 3 operator memo
Ternary operator (Python)
Non-logical operator usage of or in python
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
[python] Compress and decompress
Python> list> extend () or + =
Python default argument trap
Batch design and python
Python iterators and generators
Python from or import
python autotest or sniffer
Python packages and modules
Vue-Cli and Python integration
Ruby, Python and map
python input and output
Python3, venv and Ansible
Memorandum @ Python OR Seminar
Python asyncio and ContextVar
Python operator overload precedence
[Python] Chapter 05-01 Control syntax (comparison operator and conditional branching)
Python notes using perl-ternary operator
Encryption and decryption with Python
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python indentation and string format
Python real division (/) and integer division (//)
Python 3.4 or later standard pip
Å (Ongustromu) and NFC @ Python
Understand Python packages and modules
# 2 [python3] Separation and comment out
Python shallow copy and deep copy
Python and ruby slice memo
Python installation and basic grammar
List concatenation method in python, difference between list.extend () and “+” operator
I compared Java and Python!
Python shallow and deep copy
About Python, len () and randint ()
About Python datetime and timezone
Install Python 3.7 and Django 3.0 (CentOS)
Python environment construction and TensorFlow
Python class variables and instance variables
Ruby and Python syntax ~ branch ~
[Python] Python and security-① What is Python?
Memorandum @ Python OR Seminar: Pulp
Stack and Queue in Python
Fibonacci and prime implementations (python)
Python basics: conditions and iterations
Python debug and test module
Python list and tuples and commas
Python variables and object IDs
Memorandum @ Python OR Seminar: Pandas
Python list comprehensions and generators
About Python and regular expressions