1.2. Basic arithmetic operations#
We will begin with using Python to perform basic arithmetic operations since these form the fundamentals of computer programming (it is useful to think of your computer as a very powerful calculator). The arithmetic operators used to perform the basic operations are shown in the table below.
Operation |
Description |
Python syntax |
---|---|---|
\(x + y\) |
addition |
|
\(x - y\) |
subtraction |
|
\(x \times y\) |
scalar multiplication |
|
\(x \div y\) |
scalar division |
|
\(x^y\) |
exponentiation (power) |
|
\(x \operatorname{mod} y\) |
modulo (remainder) |
|
\(\lfloor x \div y \rfloor\) |
integer division |
|
Lets use Python to perform the following calculations. In the console window in the bottom right-hand corner of the Spyder window enter the following commands, pressing the Enter key after each one.
3 + 4
4 - 7
5 * 3
2 / 9
2 ** 5
23 % 4
11 // 3
Your console should look like the following.
In [1]: 3 + 4
Out[1]: 7
In [2]: 4 - 7
Out[2]: -3
In [3]: 5 * 3
Out[3]: 15
In [4]: 2 / 9
Out[4]: 0.2222222222222222
In [5]: 2 ** 5
Out[5]: 32
In [6]: 23 % 4
Out[6]: 3
In [7]: 11 // 3
Out[7]: 3
Most of this should be fairly self explanatory. Don’t worry if the numbers in the square brackets do not match what you see in your console.
Note
Note that \(2 \div 9 = 0.\dot{2}\) and Python has outputted the result using 16 decimal places. So this is an approximation of the actual value. Its important to realise that when we perform calculations on a computer, the results that are returned are approximations of the actual values.
1.2.1. Order of precedence of operations#
Python follows the standard rules for order of operations, i.e., BIDMAS: Brackets > Indices (powers) > Division, Multiplication > Addition, Subtraction. Brackets should be used to override this where necessary.
For example, lets calculate the value of \(\dfrac{1}{2+3}\). Enter the following in to the console and press enter.
In [8]: 1 / (2 + 3)
Out[8]: 0.2
Which is the correct result. What if we forget to include the brackets in the calculation. Enter the following into the console and press enter.
In [9]: 1 / 2 + 3
Out[9]: 3.5
Which is obviously incorrect. What Python has done here is calculate \(1 \div 2\) and then add 3 to the result. Care should be taken when dealing with arithmetic expressions that use multiple operators.
1.2.2. Exercise#
Use the console to calculate:
\(2 - (3 + 6)\)
\(2(5 - 8(3 + 6))\)
\(2(2 - 2(3 - 6 + 5(4 - 7)))\)
\(\dfrac{2(5 - 4(3 + 8))}{3(4 - (3 - 5))}\)
\(\dfrac{2(4^5)}{81 - 5^2}\)
The remainder when 14151 is divided by 571
The number of times 1111 can be divided by 14