Numeric calculations

Let’s get started with programming by doing something very familiar to us all… simple mathematical calculations. While I promise I won’t get too mathy on you, I will say that mathematical calculations are an essential part of successful programming so being comfortable with the basics is a good idea.

Let’s use Python as a calculator! Try the following commands. Hopefully they are all quite intuitive as to what they will do.

``````print( 2 + 2 )
print( 1.5 + 2.25 )
print( 7 – 2 )
print( 3 * 4 )
print( 10 / 2 )
``````

If you want to use powers/exponents, use the double star symbol. Try these:

``````print( 4 ** 2 )         # What is 4 to the power of 2? (ie: 4 squared?)
print( 4 ** 3 )         # What is 4 to the power of 3? (ie: 4 cubed?)
``````

Finally there are two different types of division you need to know. Compare the different results of these?

``````print(13 / 5)
print(13 // 5)
print(13 % 5)
``````

What are these doing?

• The first one, `13 / 5`, is the classic division we get using a calculator. 13 divided by 5 is 2.6. This is known as “floating point division”.
• The second one, `13 // 5`, is the division you learnt in primary school. Think of it as asking “how many times does 5 go into 13?” The answer, of course, is 2. This is known as “integer division”.
• The third one, `13 % 5`, is the companion question to the second one: “If 13 goes into 5 twice, how much is left over?” 5 goes into 13 twice which makes 10 with 3 left over. So 13 % 5 will tell us 3. This is known as the “modulus” or the remainder.