CodingBison

Python supports a host of basic operations, both arithmetic and non-arithmetic.

The basic arithmetic operations are addition using "+", subtraction using "-", multiplication using "*", division using "/", modulo using "%" etc. We begin by providing an example that demonstrates the usage of basic arithmetic operations. This example computes sum and product of two variables.

 var1 = 100
 var2 = 1

 varSum = var1 + var2
 varProduct = var1 * var2

 print("Variables are " + str(var1) + " and " + str(var2))
 print("Sum is " + str(varSum) + ", Product is " + str(varProduct))

Now, let us run the above example program. We store it in a file, say "operation1.py" and run it using "python3". As expected, the output prints the value of these two variables along with their sum and the product.

 [user@codingbison]$ python3 operation1.py 
 Variables are 100 and 1
 Sum is 101, Product is 100
 [user@codingbison]$ 

The above program assigns values to variables as "var1 = 100". An assignment operation takes the value on the right side (e.g. 100) and stores it in the variable (e.g. var1) on the left side. For such assignment operations, ordering is important. We must keep the variable (referred to as lvalue) on the left and keep the value (literal or yet another variable holding a value) on the right. Assigning in the opposite manner ("100 = var1") would simply be an error!

The next set of basic arithmetic operators are compound assignment operators: "+=", "-=", "*=", "/=", and "%=". These operators are used when we need to update the value of a variable. Thus, to increase varNum by 10, we could simply write "varNum += 10", instead of "varNum = varNum + 10". Similarly, to multiply var with 10, we could simply write "varNum *= 10", instead of "varNum = varNum * 10". Same rule applies to other operations. Note that Python does not support increment/decrement operators "++" and "--".

The next examples shows the usage of compound operators.

 varNum = 10
 varNum += 2
 print("varNum is " + str(varNum))

 varNum = 10
 varNum -= 2
 print("varNum is " + str(varNum))

 varNum = 10
 varNum *= 2
 print("varNum is " + str(varNum))

 varNum = 10
 varNum /= 2
 print("varNum is " + str(varNum))

Next, we show the output when we run the above example.

 [user@codingbison]$ python3 operation2.py 
 varNum is 12
 varNum is 8
 varNum is 20
 varNum is 5.0
 [user@codingbison]$ 

Operator Precedence

When there are several operations, it is possible that an expression containing more than two of these operations can appear ambiguous. As an example, with expression, "varNum = 6 * 2 + 3", it is not clear if we first multiply 6 by 2 and then add 3 (so that varNum becomes 15) or first add 2 to 3 and then multiply with 6 (so that varNum becomes 30).

To handle such ambiguous cases, Python maintains a precedence order for various operators. The following table list various operators from top to bottom, in descending precedence; thus, operators at the top have higher precedence that those that are below it. Also, operators present in a row have same precedence. For a comprehensive list, please refer to http://docs.python.org/reference/expressions.html .


Table: Python Operator Precedence
OperatorDescription
{}Dictionary
[]List
()Parentheses and Tuple
seq[i]indexing for sequences
~xBitwise Negation
/, %, *, //Division, Modulo, Multiplication, and Floor
+, -Addition and Subtraction
==Equality
!=Inequality
x in seqPresence in a sequence
x not in seqAbsence in a sequence
x1 & x2Bitwise AND
x1 ^ x2Bitwise XOR
x1 | x2Bitwise OR
not xLogical negation
x1 and x2Logical AND
x1 or x2Logical OR

With this rule in place, if an expression has both "+" and "*", then Python uses the precedence list to run "*" first and then run "+" next. This provided list contains some of the common Python operators; the list is certainly not complete. Please note that some of the rows in the table have multiple operators -- for such rows, the precedence can be considered same for all of them.

Let us revisit our earlier expression of "varNum = 6 * 2 + 3"! As per the precedence list, "*" has a higher precedence over "+". So, Python first multiples 6 and 2 (which becomes 12) and then adds 3 to the result. Thus, the value of varNum would be 15 and not 30.

In the above list, parentheses has a higher precedence than other operators and hence, where ever there is less clarity, we can simply use parentheses to avoid ambiguity. Using parentheses also improves readability of the code. Thus, in our earlier program, if we wish to do addition first, followed by multiplication, then we can clearly specify it as "varNum = 6 * (2 + 3)". Else, if we intend to multiply 6 and 2 first and then add 3 to the result, then we can clearly specify it as "varNum = (6 * 2) + 3". It is a good programming practice to use parentheses richly and thereby, avoid ambiguities.





comments powered by Disqus