Be sure to do all exercises and run all completed code cells.

If anything goes wrong, restart the kernel (in the menubar, select Kernel\(\rightarrow\)Restart) and then run all cells (in the menubar, select Cell\(\rightarrow\)Run All).


Python Basics

In this section we introduce how we can use Python for basic calculations. From this you might think that programming is similar to using an advanced calculator. It is certainly true that you can use Python in this way. However, we will see later on that computer programming allows us to do much more than simple numerical calculations. From now on, whenever you reach for a calculator (or a spreadsheet program), you should immediately think of using Python instead.

Numbers

Integers (int)

Whole numbers or integers can be entered directly. You can use a minus sign for negative numbers.

0
1
-1
314159
-200
  • Enter each number individually below and press the >Run button (or Ctrl+Return)

42

In mathematics or finance we sometimes use commas or spaces in large numbers such as \(10\,000\,000\). This is not allowed in Python. Putting a space in a number will result in a syntax error (try this). Digits separated by commas will be interpreted as separate numbers.

If you make a script containing the numbers and execute this script, you will see no output other than the last number.

  • Click on the cell below and then press >Run (or hold down Ctrl and press Return)

0
1
-1
314159
-200
  • Jupyter notebooks always display the result of the (only) last line automatically

You have to use the print function to print (display) any other output.

# script to print some integers
print(0)
print(1)
print(-1)
print(314159)
print(-200)
  • note also the hash symbol # is used to leave a helpful “comment” in the code script. Any text following it on the same line is ignored by the Python interpreter.

Floating point numbers (float)

Python can also work with numbers with a decimal point.

1.2
-3.4
0.0005
33.98

These are called floating point numbers in Python.

Arithmetic

The following examples show how to do addition, subtraction, multiplication, division and exponentiation. The comments starting with # are for your information only and are ignored by the Python interpreter.

# python arithmetic
9+16      # addition
25-9      # subtraction
4*5       # multiplication
9/4      # division
9//4       # integer division
print(1/7)
print(1.0//7)

Exercises: Use Python to perform the following calculations.

\(\displaystyle \frac{7}{6}\)

# YOUR CODE HERE

\(\displaystyle \frac{7}{2} + \frac{3}{8} - \frac{9}{10}\)

# YOUR CODE HERE

Exponentiation

Exponents use the ** operator in Python:

e.g. \(x^p\) is entered as x**p

Exercise: Calculate the following:

\(\sqrt{20}\)

(think about another way to represent square root as a power)

# YOUR CODE HERE

Result: 4.47213595499958

Click here to see solution

Combining arithmetic operations in one expression

The order in which the calculations are carried out is the standard BODMAS rule:

  1. Brackets (parentheses),

  2. Orders (roots and powers/exponentiation),

  3. Multiplication

  4. Division / Multiplication,

  5. Addition / Subtraction.

  • Combinations of addition and subtraction are carried out from left to right.

    • This means that 1 - 2 + 3 is equivalent to (1 - 2) + 3 and not 1 - (2 + 3). calculations.

  • The same holds for combinations of multiplication and division.

    • For example, 6/2*3 is equivalent to (6/2)*3 and not 6/(2*3). Note that the use of spaces does not influence the order of calculations, e.g. 6 / 2*3 is equal to (6/2)*3.

The order of operations can be changed by using parentheses (). Only parentheses (round brackets) can be used. Square brackets [] and braces (curly brackets) {} have a special meaning in Python and cannot be used to change the order of operations.

Calculate the following:

\(\displaystyle \frac{4^4 2^{-8}}{8^2}\)

# YOUR CODE HERE

Expected result: 0.015625

Click here to see solution

Note that multiplication symbol * is always necessary. This is especially important once we start using variables and parentheses. In mathematics we often write: \(5 x = 5 \times x\) and \(5(3 + 4) = 5 \times (3 + 4)\), but we can not simplify in this way in Python.

The following will give an error:

5(3 + 4)

Correct the error above before moving on

Solution

# run this to see some more arithmetic operations
print(2+3*5)
print((2+3)*5)
print(-(9+4))
  • Note that it is not a good idea to use expressions like 3**2*2.

    • You should use parentheses to make it clear that you mean (3**2)*2 and not 3**(2*2).

Try these above examples in the cell below:

# YOUR CODE HERE
  • In certain cases you should use parentheses even though they are not strictly necessary.

    • For example an expressions like 2*3*4/7*8 would be clearer when written as (2*3*4/7)*8

  • Spaces around mathematical operations are allowed and it is recommended to use extra spaces to make mathematical expressions clearer. Beware that the extra spaces do not have any special meaning for Python.

# use of spaces
print(2 + 3*5)   # GOOD
print(2+3 * 5)   # BAD, this is equal to 2+(3*5) and NOT (2+3)*5

Exercise: Perform the following calculation:

\(\displaystyle\frac{852(53+27)-72(405)}{24}\)

# YOUR CODE HERE

Expected Result: 1625.0

Click here for solution

Arithmetic Involving Integers

When adding, subtracting or multiplying integers, the result will always be an integer. The same is true for exponentiation if the exponent is positive. For negative exponents the result will be a floating point number.

10**(-2)

The parentheses are not strictly necessary in this case, but it is a good habit to use them.

Mixing integers and floating point numbers in the same expression is allowed. Whenever integers and floating point numbers are combined in the same expression, the result will be a floating point number.

(1 + 0.4) * 5

A division involving two integers will always result in a float (rounded down) in Python 3 (this has changed from Python 2).

11/5

If you want the integer result, use the int() function (also see the // operator).

print(11/5)
print(int(11.0/5.0))
print(11//5)

The remainder after integer division can be found using the operation %

print(11 % 5)

Try some other examples here until you understand how this works:

# YOUR CODE HERE

Scientific/engineering notation

Very big or very small floating point numbers can be entered using scientific notation.
The number \(5.6 \times 10^{17}\) is typed as 5.6e17 (the letter e stands for exponent and means “times ten to the power”, not the number \(e\neq2.718\))

We can output several values at once by separating them with a comma. The values are separated by a single space in the output.

print(2e6, 1e-3, 5.6e17, 1.618e-20)

Converting the type of number

Integers and floating point numbers are different types of values in Python, and behave differently when doing mathematical calculations (see later).

Special in-built functions int() and float() can be used to convert between types.

  • A function is a key-word followed by round brackets (parentheses).

  • the input (called the “argument” ) to the function goes into the brackets.

  • the function gives (or “returns” ) an output:

Converting a float to an int:

int(4.9)

Converting an int to a float:

float(5)

Other useful functions

Some other functions come with basic Python that can be used on numbers.

The round() function takes a number and rounds it up or down, depending on certain rules (but the behaviour might not be as you expect from high school maths!):

print(round(4.49))
print(round(4.50))
print(round(4.51))
print(round(3.5))
  • Notice using the result of the round function as the input (argument) to the print function.

The abs() function is used for absolute values

abs(-10.0)

Using “libraries” to add new functionality to Python

Some features come with Python but are not available straight away, we need to add them at the top of a script.

Importing a whole library into Python

For example to use constants such as \(\pi\) or \(e\) we can import a “library” called math, using an import statement:

# how to import a library
import math

print(math.pi)
print(math.e)
  • Notice how the values of the constants pi and e are called from within the math library using the “dot” syntax. That is, the name of the loaded library, followed by a “.” and then the thing we want from within the library (with no spaces).

This “dot” method is used a lot in Python to access functions or variables within other so called “objects”.

Exercise: import the numbers \(e\) and \(\pi\) from the math library and use them to print the following examples:

  • \(e^2\)

  • \(3\left(\dfrac{\pi}{4}\right)\)

# YOUR CODE HERE

Result:
7.3890560989306495 2.356194490192345

Click here for solution

Calculate:

  • \(e^{-1}\)

# YOUR CODE HERE

Result: 0.36787944117144233

  • Compare this with engineering notation 1e-1, which means \(10^{-1}\)

1e-1

Importing particular objects from inside a library

Libraries such as math also contain mathematical functions such as sine, cosine or square root. These have names such as sin, cos and sqrt.

In this case we can load just the bits we need from math, instead of using the dot method (which also works).

from math import sin, cos, sqrt, pi

print(sqrt(2), sin(pi/2), cos(0))

Exercise:

Import the sine function and the constant \(\pi\) and calculate: \(\left(\sin\frac{\pi}{4}\right)^2\)

# YOUR CODE HERE

Result: 0.4999999999999999

Click here for solution

  • Note 1: the floating point precision in the last example is due to converting between a binary number in the computer’s memory to a decimal (0.5).

  • Note 2: angles are in radians so you need to convert using \(rads = \frac{degs}{180} \times \pi\)

    • there is also a “convenience function” deg2rad, which is in another library called numpy (Numerical Python) that also has its own versions of mathematical constants and functions:

from numpy import deg2rad, rad2deg

print(deg2rad(180))
print(rad2deg(3.1416/2))

Mixing multiple libraries:

import math, numpy

print(math.sin(90*math.pi/180), numpy.sin(numpy.deg2rad(90)))
  • Notice again how we can also put a function in the argument (input) to another function.

Importing libraries with a pseudonym

To make typing easier we can import a library and give it a nickname, using import as:

import numpy as np
from numpy import deg2rad as d2r

print(np.sin(d2r(90)))
  • If you want to know what functions are available you can either:

    1. search the internet (google: “python numpy functions”)

    2. start typing in an input window, press Tab and wait for the pop-up to appear

    #type the following in the box below and press the TAB button on your keyboard and wait a second...
    import numpy
    numpy.
    
    1. use the in-built dir function:

    import math
    dir(math)
    
    1. Use the in-built help function:

    import math
    help(math)
    

Try the examples above in the input In [ ] cell below:

# YOUR CODE HERE

You can also get help in Jupyter notebooks by typing the name of the library or function and a question mark:

import numpy

numpy?

1st Weekly Task! (1%)

The purpose of this task is to create and upload a plain Python (.py) script (not a Jupyter Notebook .ipynb file). It must print the exact string (including punctuation and uppercase) and also calculate something for the number, not just print it.

  1. Open a new notebook (or use Spyder or Jupyterlabs)

    • File > New Notebook > Python 3

    • Name it Task1 or something sensible by clicking on the Untitled tab next to the word Jupyterhub near the top left

  2. Using a single code block make a script that prints both

    • The exact text: Hello World!

      • Check uppercase letters and exclamation marks are correct - and don’t forget the quote marks!)

    • a calculation that results in the answer 42

      • I will check it’s the result of a calculation!

  3. Download using File > Download as > Python (.py) and save it somewhere sensible.

  4. Open Spyder from the Windows Start Menu and use the file menu to open the Task1.py file you just saved.

  5. Check it runs OK

  6. Submit the Task1.py file to moodle (and nothing else)!











Appendix: A note on floating point precision

The floating point numbers in Python have a precision of approximately 16 significant digits and this can cause rounding errors.

Mathematically, the result of the calculation \((1 + a) - 1\) is \(a\), no matter what the value of \(a\) is.

With finite precision the result can be less accurate for smaller the values of \(a\):

(1.0 + 1e-15) - 1.0

In the next example the number 0.1 + 0.2 should equal 0.3

0.1 + 0.2

The strange values that remain are a result of the numbers being stored in binary in the computer’s memory then converted back to decimal.

See https://floating-point-gui.de/basic/ for more information.