Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment with "or" in python [closed]

Is it considered bad style to assign values to variables like this?

x = "foobar" or None y = some_variable or None 

In the above example, x gets the value 'foobar'.

like image 311
TheOne Avatar asked Jan 05 '12 18:01

TheOne


People also ask

What does an XY or Z assignment do in Python?

The base case, x or y returns x if bool(x) evaluates True , else it evaluates y , (see the docs for reference). Therefore, a series of or expressions has the effect of returning the first item that evaluates True , or the last item.

How does assignment work in Python?

The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.

Which of the following is an assignment operator in Python a == b === C >>> D?

1 Answer. Assignment operators: In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also be given as a, b = 5, 10 that assigns the value 5 and 10 on the right to the variables a and b respectively.

What does |= mean in Python?

|= on Booleans The Python |= operator when applied to two Boolean values A and B performs the logical OR operation A | B and assigns the result to the first operand A . As a result, operand A is False if both A and B are False and True otherwise. What is this?


2 Answers

No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.

like image 167
tback Avatar answered Oct 02 '22 14:10

tback


The primary danger of doing something like this is the possibility that (in the second case) some_variable is False but not None (the integer 0, for instance) and you don't want to end up with y equal to None in that case.

like image 33
Free Monica Cellio Avatar answered Oct 02 '22 13:10

Free Monica Cellio