It would be wise to write like boolean and "A" or "B" [Python] [But]

This is a memorandum (I was studying Click) because I saw it for the first time while studying the tutorial code.

Conditional branching using Boolean operator

Since the Boolean operator in Python returns the value of the comparison, not the Boolean value,

>>> def test(flag=True):
...     print 'flag: %s' % (flag and 'on' or 'off')
... 

If you do it

>>> test(True)
flag: on
>>> test(False)
flag: off

It looks like. Note that ʻand and ʻor here are Boolean operators, not comparison operators.

As you can see in Python library reference, Boolean operator section, the operators ʻand, orandnot` are evaluated in ascending order of priority as shown in the table below.

True if
operation result
x or y y if x is false, x otherwise
x and y x if x is false, y otherwise
not x x is false, False otherwise

Therefore, non-empty strings were always evaluated as True, so

If flag is True: (Because the left term is True) -> 'on' or 'off' (Because the string'on'is True) -> 'on'

If flag is False: (Because the left term is False) -> False or 'off' (Because the left term is False) -> 'off'

It was.

It was refreshing to know what was happening. It looks refreshing and may look smart.

But ...

However, it is a different matter if I am asked if I will write like this in the future. I would honestly write this.

>>> def test(flag=True):
...    print 'flag: %s' % ('on' if flag else 'off')

By the way, this is not a comprehension, it seems to be a ternary operator implemented from version 2.5, but it still looks like Python, so this is better.

Also, in the first example, there is a restriction that the part of the character string'on'must contain something that becomes True every time. I think that it is safe to write using the ternary operator because it can be a fatal bug in some cases that the evaluation of what is assigned is restricted.

reference -Today's Python: About Boolean Operations:

Recommended Posts

It would be wise to write like boolean and "A" or "B" [Python] [But]
[Python] return A [or / and] B
Let's write a Python program and run it
[Python] Concatenate a List containing numbers and write it to an output file.
How to write a metaclass that supports both python2 and python3
Recursively get the Excel list in a specific folder with python and write it to Excel.
Python a + = b and a = a + b are different
・ <Slack> Write a function to notify Slack so that it can be quoted at any time (Python)
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
How to input a character string in Python and output it as it is or in the opposite direction.
[Python] Create a linebot to write a name and age on an image
Connect a lot of Python or and and
Compress python data and write to sqlite
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
I thought it would be slow to use a for statement in NumPy, but that wasn't the case.
Atcoder Beginner Contest A, B Input summary Python that tends to be a problem
Reinforcement learning 35 python Local development, paste a link to myModule and import it.
I want to write an element to a file with numpy and check it.
C language to see and remember Part 3 Call C language from Python (argument) c = a + b
Install the python library when you're not a sudoer (or if you don't want new users to be Sudoer, but you don't mind having the Python Library installed as you like)
Would you like to make a Twitter resume?
Make a chatbot and practice to be popular.
Why does Python have to write a colon?
python memo-"if not A and B" was "if (not A) and B"
[Go] How to write or call a function
I want to write to a file with Python
A module that makes it easier to write Perl-like filter programs in Python fileinput
Created a Python library to write complex comprehensions and reduce in an easy-to-read manner
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
I want to write a triple loop and conditional branch in one line in python
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Looking at the difference between the fucking big Rashomon, it turned out to be a messy and fucking big literature like a parent's death.
I don't like to be frustrated with the release of Pokemon Go, so I made a script to detect the release and tweet it
[Python] Boolean operator (or / and) does not return Boolean value
Python that I would like to recommend to programming beginners
I want to write in Python! (2) Let's write a test
How to write a list / dictionary type of Python3
It's not easy to write Python, it's easy to write numpy and scipy
Write tests in Python to profile and check coverage
[Python] How to write a docstring that conforms to PEP8
[Python] A memo to write CSV vertically with Pandas
A program to write Lattice Hinge with Rhinoceros with Python
Write code to Unit Test a Python web app
I wrote python3.4 in .envrc with direnv and allowed it, but I got a syntax error
It is blocked by Proxy, a connection error occurs in Python or pip, and it is retried.
A story that makes it easy to estimate the living area using Elasticsearch and Python
I made a server with Python socket and ssl and tried to access it from a browser
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
An easy way to view the time taken in Python and a smarter way to improve it
It may be a problem to use Japanese for folder names and notebook names in Databricks
[Python] A program to find the number of apples and oranges that can be harvested