Python logical operation stumbling

Python bool

As a premise, in Python, the bool value is True for anything that is not 0 or empty.

bool(0) # False

bool(0.1) # True

bool("") # False

bool([""]) # True

On the contrary, True and False can be operated in the same way as 1 and 0.


True*1 # 1

False*1 # 0

True+0 # 1

True+True # 2

Logical operation

Although not limited to Python, and and or are short-circuit evaluated on both sides.

True and False # True

print("a") or print("b")
# a
# b

1 and print("b") # b

And the logical operation of Python ** The result is not limited to bool. ** **


100 and 200 # 200

200 and 100 # 100

100 or 200 # 100

200 or 100 # 200

If you use &, | instead of and, or, it becomes a bit operation.

True & False # False

True & 1 # 1

True & 2 # 0

123 & 125 # 121

Recommended Posts

Python logical operation stumbling
[python] vector operation
Python OS operation
[Python] Matrix operation
[Python] Operation of enumerate
Python directory operation summary
Python decorator operation memo
[python] Array slice operation
S3 operation with python boto3
Python pywin32 (win32com) Excel operation memorandum
[Python] Operation memo of pandas DataFrame
[Python] The stumbling block of import
[python] week1-3: Number type and operation
Basic Python operation 2nd: Function (argument)
[Automation with python! ] Part 2: File operation
[Python] File operation using if statement
Mouse operation using Windows API in Python
Python basic operation 1st: List comprehension notation
Python + Selenium Frequently used operation method summary
[Python beginner memo] Python character string, path operation
[Introduction to Udemy Python3 + Application] 17. List operation
Python basic operation 3rd: Object-oriented and class
Python data structure and operation (Python learning memo ③)