1.5. Python as a calculator#
We can use Python to perform many numerical calculations for us.
Addition
print(2 + 5)
Subtraction
print(8 - 3)
Multiplication
print(2 * 4)
Division
print(100 / 2)
Modulus
This tells you the remainder. If you run the example below, dividing 5 by 2 gives a remainder of 1.
print(5 % 2)
Power
The first number is the base and the second number is the power. For example
you would read 4**2 as ‘4 to the power of 2’, i.e. \(4^2\), which is
16.
print(4**2)
1.5.1. Order of operations#
Python follows the stand standard order of mathematical operations, i.e. BODMAS: Brackets Orders Division Multiplication Addition Subtraction.
1.5.2. Float Point Representation#
Some decimal values cannot be represented exactly by a computer and sometimes arithmetic containing floating points numbers will contain errors. Here are some examples.
print(10/3)
3.3333333333333335
print(1.2 - 1.0)
0.19999999999999996
This is not a bug in the code that can be fixed - it is inherent to all programming languages. Remembering these issues will help you build code robust enough to handle the inaccuracies for floating point representations.
Note that some decimal values can be stored to a higher precision than other decimal values and the level of precision these values are stored at depends on how much memory is allocated to the variable in the computer. Double-precision float point numbers can store decimals to a greater precision than single-precision floating point numbers because double-precision floating points numbers have 64 bits of memory allocated to them compared to single-precision floating point numbers which only have 32 bits of memory.
Question 1
What is the output of the following code?
x = (6 + 4)/2
print(x)
Solution
5
The order of operations must be followed. 6 and 4 are added before the division since they are inside a set of brackets. This is equivalent to the mathematical expression \(\cfrac{6 + 4}{2} = 5\).
Removing the brackets results in the expression \(6 + \cfrac{4}{2}=8\).
Question 2
What is the output of the following code?
x = 6%3
print(x)
Solution
0
6 is divisible by 3, so the remainder is 0.
Question 3
What is the output of the following code?
x = 2**3
print(x)
Solution
8
2**3 should be interpreted as 2 to the power of 3, i.e. \(2^3 = 2 \times 2 \times 2 = 8\).
Code challenge: Calculations
Use Python to calculate the following.
\(124\ -\ 32\ \times8\)
\(5^2-7^3\)
\(\frac{6\times 14\ -\ 5^3}{2.8}\)
Solution
x = 124 - 32 * 8
print(x)
y = 5**2 - 7**3
print(y)
z = 5**2 - 7**3
print(z)