Python's Assignment Operator: Write Robust Assignments β Real Python
Python 3 and assignment operators (= + vs +=)
compiler construction - assign operator to variable in python? - Stack Overflow
Just noticed the 'augmented assignment operator' isn't really an 'assignment operator'
Videos
I came across something I don't fully understand. It seems the = + operators and += do different things.
>>> x = [1, 2, 3] >>> y = x >>> y [1, 2, 3]
Variables x and y point to the same list. If use append (say x.append(7)) on either, then the append is seen by both as the data/list is modified in place. That I get. But if I use + instead, I apparently create a new list:
>>> x = x + [7] >>> x [1, 2, 3, 7] >>> y [1, 2, 3]
OK. But += is the shorthand for the first statement, so I would expect the same behavior, but I don't get it.
>>> y = x >>> x [1, 2, 3, 7] >>> y [1, 2, 3, 7] >>> x += [9] >>> x [1, 2, 3, 7, 9] >>> y [1, 2, 3, 7, 9]
Obviously = + and += are different. Can anyone enlighten me?
You can use the operator module and a dictionary:
Copyimport operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}
op_char = input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)
The operator module http://docs.python.org/library/operator.html exposes functions corresponding to practically all Python operators. You can map operator symbols to those functions to retrieve the proper function, then assign it to your op variable and compute op(a, b).