This lesson is in the early stages of development (Alpha version)

Calculating in Spyder

Overview

Teaching: 5 min
Exercises: 5 min
Questions
  • How do we process mathematical operations in Spyder?

Objectives
  • Become familiar with mathematical operators and in-built functions in Spyder.

  • Become confident using the console to run mathematical operations.

  • Understand the order of operations.

Dipping our toes

We have covered some relatively dry theory so let’s take some small steps and start interacting with Python. From the console we can start exploring calculation. Write in the following commands:

10  5 #(subtraction) 
5
10 + 5 #(addition) 
15
10 * 5 #(multiplication) 
50
10 / 5 #(division) 
2
5 ** 2 #(exponentiation) 
25
10 % 3 #(modulus)  
1

Note: anything following a ‘#’ is considered a comment. Comments are not read by Python they are just used to inform users.

Order of operations

Question: Before you enter the next calculation, take a second and consider what answer would you be expecting?

6 + 9 / 3 
9

If the answer was not what you were expecting you will need to become clear on order of operations in Python.

Remember PE(DM)(AS)

* Operators with same precedent are calculated left to right.

This tells you what order mathematical operations will be performed and ensures consistency during evaluation.

To make this concept clearer, try:

(6 + 9) / 3 
5

Using brackets we have manipulated the order of operations to perform the addition before the division. Be conscious of how you structure your mathematical operations to ensure the desired results but also readability of your code.

Mathematical Functions

Combining the math package and build in functions from Python you have a good range of mathematical functions. If you need a fairly common operation there is a good chance it already exists in a package. Let’s look at a few examples, try:

import math 
math.sqrt(9) 
3
abs(-5) 
5
round(3.4) 
3
math.sin(1)
0.8414709848078965

There are a whole range of in-built functions and additional functions available from packages. It is awlays good practice to perform a google search to discover if the function you want already exists.

Key Points

  • PEDMAS

  • Use mathematical functions, you don’t need to reinvent the wheel.