Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University
On successful completion of this pages readers will be able to:
Python is a multipurpose programming language that is widely used for scientific computation and data analysis. Python is becomming more popular in the workplace as well as academia so it is a good idea to learn it to enhance your skillset. This is the first in a series of Jupyter notebooks which will introduce you to Python and by working through the interactive examples and exercises you will develop your programming skills.
The guidance material that you are using now will to teach you how to program in Python using Jupyter notebooks. These are interactive documents which allow you to edit and run Python code within the document without having to leave the document and use another software package. Jupyter notebook files have the file extension .ipynb
and can be accessed and edited in a number of differents ways as explained below.
Python is an open source which means it is free to download and use. The easiest way to install Python onto your own machine is to install Anaconda which is a suite of scientific programming tools which is available for most operating systems and is free to download and use. Acaconda includes two programs which we can use to write Python programs: Jupyter Notebook and Spyder. These materials use Jupyter notebooks to teach Python but Spyder is also useful for writing longer programs.
To use these materials using Jupyter Notebook installed using Anaconda do the following
Note that Anaconda is already installed on PCs in the Faculty of Science and Engineering and on selected PCs in the library.
If you are unable to install Anaconda on the computer you are using you can open and run Jupyter notebook files through a web browser using Google Colab. To use these materials using Google Colab do the following:
These materials have a number of interactive examples and exercises for you to try out. The examples are designed to demonstrate how the various Python commands work and the exercises give you an opportunity to put into practice what you have learned.
Jupyter notebooks consist of a number of cells which can either be a text cell like this one which contains text or a code cell which contains Python code than can be executed. For example, enter the following commands into the code cell below.
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
86400
To execute the code in the above cell, select it with a click and then use the keyboard shortcut ctrl
and enter
keys pressed at the same time (for a full list of the keyboard shortcut commands go here) or click on the Run button. To edit the code, just click the on the cell and start editing.
For example, enter the following command in the code cell below and executre it.
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week
604800
Here we have computed the number of seconds in a day, stored it as a variable and returned the result. Variables that we have defined in one cell can be used in later code cells. Note that the code above uses the previously defined variable seconds_in_a_day
so the code cell where this is defined needs to have been executed prior to this one (variables are explained in more detail below).
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.
Operator | Explanation | Example | Python code | Output |
---|---|---|---|---|
$+$ | addition | $2+3$ | 2 + 3 |
5 |
$-$ | subtraction | $2-3$ | 2 - 3 |
-1 |
$\times$ | multiplication | $2\times 3$ | 2 * 3 |
6 |
$\div$ | division | $2 \div 3$ | 2 / 3 |
0.6666... |
$x^y$ | exponentiation | $2^3$ | 2 ** 3 |
8 |
$\text{mod}$ | modulo (remainder) | $2 \,\text{mod}\, 3$ | 2 % 3 |
2 |
$\lfloor x \div y \rfloor$ | floor division | $\lfloor 2 \div 3 \rfloor$ | 2 // 3 |
0 |
3 + 4
7
(ii) $4 - 7 = -3$
4 - 7
4 - 7
-3
(iii) $5 \times 3 = 15$
5 * 3
5 * 3
15
(iv) $\dfrac{2}{9} = 0.2222\ldots$
2 / 9
2 / 9
0.2222222222222222
(v) $2^5 = 32$
2 ** 5
2 ** 5
32
(vi) $23 \operatorname{mod} 4 = 3$ ($x \operatorname{mod} y$ means the remainder when $x$ is divided by $y$)
23 % 4
23 % 4
3
(vii) $\left\lfloor \dfrac{11}{3} \right\rfloor = 3$ ($\lfloor x \rfloor$ means $x$ rounded down to the integer below)
11 // 3
11 // 3
3
Python follows the standard rules for order of operations, i.e., BODMAS: Brackets > Orders (powers) > Division, Multiplication > Addition, Subtraction. Brackets should be used to override this where nececessary.
The command below calculates the value of the expression $\dfrac{1}{2+3}$. Enter it into the code cell below and execute it.
1 / (2 + 3)
1 / (2 + 3)
0.2
Omitting the brackets from this command results in the command below. Enter this into the code cell below and execute it.
1 / 2 + 3
1 / 2 + 3
3.5
This has calculated the value of $\dfrac{1}{2}+3$.
2 - (3 + 6)
-7
(b) $2(5-8(3+6))$;
2 * (5 - 8 * (3 + 6))
-134
(c) $2(2-2(3-6+5(4-7)))$;
2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
76
(d) $\dfrac{2(5-4(3+8)))}{3(4-(3-5))}$;
(2 * (5 - 4 * (3 + 8))) / (3 * (4 - (3 - 5)))
-4.333333333333333
(e) $\dfrac{2(4^5)}{81-5^2}$.
(2 * 4 ** 5) / (81 - 5 ** 2)
36.57142857142857
14151 % 571
447
1111 // 14
79
If we have an existing variable x
which is equal to some value then we can use a shorthand for applying the basic arithmetic operations to x
by writing the operator imediately before the =
symbol followed by a number (or variable), e.g.,
x += k
and similar for the other arithmetic operatiors shown in the table above.
Python is a very simple all purpose programming language designed to service the needs of a wide variety of users. As such it only has a small number of commands and functions built in, these known as intrinsic functions. The full list of intrinsic functions in Python can be found here. Fortunately there is a wide variety of libraries which are a collection of functions that we can import into our programs so that we can make use of the functions that have been written to perform certain tasks.
To import a library we use the following
import name_of_library
This will import the library called name_of_library
. We can now use a function from our imported library by prefixing the function name with name_of_library.
, for example
name_of_libary.name_of_function()
It is also possible to change the name that the library is known as in a program in the import statement which is useful in shortening the library name, for example
import library_with_a_very_long_name as library
library.name_of_function()
To calculate common mathematical functions such as square roots, logarithms, trigonometric functions etc., i.e., similar to the function buttons on a scientific calculator, we can import functions from the math library by executing the code cell below.
import math
Once a library has been imported we do not need to do it again.
Some of the most common math functions are listed in the table below.
Function | Explanation | Example | Python command | Output |
---|---|---|---|---|
$\pi$ | constant $\pi$ | $\pi$ | math.pi |
3.1415... |
$e$ | constant $e$ | $e$ | math.e |
2.7182... |
$\sqrt{x}$ | square root of $x$ | $\sqrt{9}$ | math.sqrt(9) |
3.0 |
$\sin(x)$ | sine of $x$ | $\sin(\pi)$ | math.sin(math.pi) |
1.2246e-16 (i.e., zero) |
$\cos(x)$ | cosine of $x$ | $\cos(0)$ | math.cos(0) |
1.0 |
$\tan(x)$ | tangent of $x$ | $\tan(1)$ | math.tan(1) |
1.5574... |
$\sin^{-1}(x)$ | arcsin (or inverse $\sin$) of $x$ | $\sin^{-1}(1)$ | math.asin(1) |
1.5707... |
$e^x$ | exponential function of $x$ | $e^{1}$ | math.exp(1) |
2.7182... |
$\ln(x)$ | natural logarithm of $x$ | $\ln(2)$ | math.log(2) |
0.6931... |
$\log_{a}(x)$ | logarithm of $x$ to the base $a$ | $\log_2(4)$ | math.log(4, 2) |
2.0 |
$x!$ | factorial of $x$ | $6!$ | math.factorial(6) |
720 |
$\lfloor x \rfloor$ | round $x$ to the integer below | $\lfloor 1.23 \rfloor$ | math.floor(1.23) |
1 |
$\lceil x \rceil$ | round $x$ to the integer above | $\lceil 1.23 \rceil$ | math.ceil(1.23) |
2 |
Note:
- Python assumes all angles are in radians.
- The inverse functions for the other trigonometric ratios are calculated similarly.
Using functions from the math library, evaluate the following:
(i) $\sqrt{9} = 3$
import math
math.sqrt(9)
import math
math.sqrt(9)
3.0
(ii) $\cos\left( \dfrac{\pi}{4} \right) = \dfrac{\sqrt{2}}{2} \approx 0.7071$
math.cos(math.pi / 4)
math.cos(math.pi / 4)
0.7071067811865476
(iii) $e^2 \approx 7.3891$
math.exp(2)
math.exp(2)
7.38905609893065
(iv) $4! = 24$
math.factorial(4)
math.factorial(4)
24
(a) $\sqrt{3^2 + 4^2}$ ;
math.sqrt(3 ** 2 + 4 ** 2)
5.0
(b) $\cos(\pi)$;
math.cos(math.pi)
-1.0
(c) $\sin^{-1}(1)$;
math.asin(1)
1.5707963267948966
(d) $\ln(e^2)$;
math.log(math.exp(2))
2.0
(e) $\log_{10}(1000000)$.
math.log10(1000000)
6.0
Variables are used to store information which can be retrieved elsewhere in a computer program. To define a variable in Python we use the equals sign =
. For example
a = value_of_a
You can also define multiple variables in one line using
a, b, c = value_of_a, value_of_b, value_of_c
which does the same as
a = value_of_a
b = value_of_b
c = value_of_c
Once a variable has been defined the information stored in it can be used in other commands in a program.
The commands below define the 3 variables x
, y
and z
and calculates their sum. Enter them into the code cell below and execute.
x = 1
y = 2.5
z = -3
x + y + z
x = 1
y = 2.5
z = -3
x + y + z
0.5
The commands below perform the same calculates as above but demonstrate how multiple variables can be defined in the same line. Enter them into the code cell below and execute.
x, y, z = 1, 2.5, -3
x + y + z
x, y, z = 1, 2.5, -3
x + y + z
0.5
A Python variable can have a short name (e.g., x
and y
) but sometimes it is advisable to use longer descriptive name so that your program is easier to understand (e.g., distance
, seconds_in_a_minute
). Variable names must adhere to the following rules:
age
, Age
and AGE
are three different variables)The command below attempts to define a variable that violates Python's variable name rules. Enter it into the command cell and execute it.
1st_variable = 2
first_variable = 2
Python has returned an error because the first character of this variable is a number. To overcome this we need to use a different variable name, edit the code cell above with the following command and execute it.
first_variable = 2
Python uses the following types of variables:
Type | Explanation | Example | Python command |
---|---|---|---|
integer numbers | wholes numbers including 0 and negative numbers | $-987$ | -987 |
floating point numbers | numbers expressed using an integer part and a fractional part separated by a decimal point |
$3.1416$ | 3.1415 |
floating point exponential numbers | numbers expressed in standard form $a \times 10^{b}$ | $2 \times 10^4$ | 2e4 |
complex numbers | numbers of the form $a + bi$ where $a$ and $b$ are a real numbers and $i=\sqrt{-1}$ is the imaginary number |
$2 + 3i$ | 2 + 3j |
Boolean | values which are either True or False | True | True |
string | sequences of letters, spaces and symbols | "hello world" | "hello world" |
Note:
- in Python the imaginary number is represented by
j
- single quotes can also be used for strings, e.g.,
'hello world'
When defining a variable, Python will automatically use the appropriate variable type depending on the value assigned.
a = 2
a
2
(ii) $b = 1.5$
b = 1.5
b
b = 1.5
b
1.5
(iii) $c = 5000000000 = 5 \times 10^9$
c = 5e9
c
c = 5e9
c
5000000000.0
(iv) $d = 2 + 3i$
d = 2 + 3j
d
d = 2 + 3j
d
(2+3j)
(v) $e = \text{True}$
e = True
e
e = True
e
True
(vi) $f = \text{"this is a string"}$
f = "this is a string"
f
f = "this is a string"
f
'this is a string'
We can determine what type a variable is using the type
command.
type(variable_name)
Determine the type of variable for each of the variables defined in example 6.
(i) a = 2
type(a)
type(a)
int
(ii) b = 1.5
type(b)
float
(iii) c = 5e9
type(c)
float
(iv) d = 2 + 3j
type(d)
complex
(v) e = True
type(e)
bool
(vi) f = "this is a string"
type(f)
str
We can convert some variables to a different type using the following commands.
Conversion | Python command | Output |
---|---|---|
floating point number to an integer | int(1.2) |
1 |
integer number to a floating point number | float(1) |
1.0 |
integer to a string | str(2) |
'2' |
int(2.5)
2
(ii) $3$ to a floating point number
float(3)
float(3)
3.0
(iii) $123$ to a string
str(123)
str(123)
'123'
C = 37
F = 9 / 5 * C + 32
F
98.60000000000001
side1, side2 = 2, 3
hypotenuse = math.sqrt(side1 ** 2 + side2 ** 2)
hypotenuse
3.605551275463989
adjacent, opposite = 4, 5
angle = math.atan(5 / 4)
angle
0.8960553845713439
It is good programming practice to format your code so that is can be easily read. Guidelines for formatting Python code can be found in the PEP style guide for Python code and this section covers some of the basics.
In a Python program spaces are ignored, however it is common practice to use spaces either side of the arithmetic operators so that it is more readable. It is also advisable to seperate blocks of code with a blank line.
The commands below perform the same operations. Enter them into the code cells below and execute them to check they return the same value.
1*2+3*4+5/6
1*2+3*4+5/6
14.833333333333334
1 * 2 + 3 * 4 + 5 / 6
1 * 2 + 3 * 4 + 5 / 6
14.833333333333334
A comment in a program is text that is ignored by Python when the code is executed and are useful to helping people understand the program. Comments in Python can be used in two ways:
# this is a comment
Here any text on the same line to the right of #
is ignored. These are useful for short comments. For longer comments that span multiple lines we can use """
to start and end a comment (single quotes can also be used).
"""this is a comment
that spans multiple
lines"""
The program in the code cell below makes use of comments. Enter is into the code cell below and execute it to check that it runs. Note how the lines of the program are spaced out to improve the readability of the code. Blank lines are also ignored by Python and can be used to improve the readability of a program.
"""This program calculates the
sum of two numbers"""
x = 4 # first number
y = 7 # second number
# Calculate the sum of the two numbers
x + y
"""This program calculates the
sum of two numbers"""
x = 4 # first number
y = 7 # second number
# Calculate the sum of the two numbers
x + y
11
To split a line of code we use the \
symbol. This is useful when a single line of code uses a lot of horizontal space.
The program in the code cell below uses the \
symbol to split one of the lines of code over two lines. Enter it into the codel cell below and execute it to check that it runs.
# Define the variables
x, y, z = 2, 3, 4
# The code below has been split over two lines
sum_xyz = x + y \
+ z
# Output the sum of x, y and z
sum_xyz
# Define the variables
x, y, z = 2, 3, 4
# The code below has been split over two lines
sum_xyz = x + y \
+ z
# Output the sum of x, y and z
sum_xyz
9
To output text or the value of a variable within a Python program we can use the print()
command.
print("some text")
print(x)
The commands in the code cells below show how the print
command is used to print character strings and numbers. Enter then into the code cells below and execute them to see the results.
(i) the character string "hello world"
print("hello world")
print("hello world")
hello world
(ii) the value of the variable $x=2$
x = 2
print(x)
x = 2
print(x)
2
(iii) the values of the two variables $b=3$ and $c = 4$
b, c = 3, 4
print(b, c)
b, c = 3, 4
print(b, c)
3 4
Sometimes it is desirable to be able to output text alongside numbers. This can be done by writing an f
before the string and then puting the variable name in curly brackets
print(f"the value of x is {x} and the value of y is {y}")
The two sets of curly braces {x}
and {y}
will be replaced with the values of x
and y
respectively.
The command in the code cell below uses a print
statement to combine the printing of text and numbers. Enter them into the cell cell below and execute it to see the output (if Python returns an error make sure you have executed the first two code cells in this notebook).
print(f"There are {seconds_in_a_day} seconds in a day and {seconds_in_a_week} seconds in a week.")
print(f"There are {seconds_in_a_day} seconds in a day and {seconds_in_a_week} seconds in a week.")
There are 86400 seconds in a day and 604800 seconds in a week.
Python will print floating point values using 16 decimal places by default. If we to control the number of decimal places and/or the number of character spaces used to print a value can use formatted output.
print(f"{x:a.bf}")
This will output the value of the floating point number x
using a
character spaces (including the decimal point) using b
decimal places.
The f
in the code above specifies the type of variable we are ouputted. The specifiers for the main variable types are given in the table below.
Variable type | Specifier | Example | Python code |
---|---|---|---|
integer number | d |
␣␣2 |
print(f"{2:3d}") |
floating point number | f |
␣␣3.142 |
print(f"{math.pi:7.3f}") |
exponential number | e |
␣␣1.23e+03 |
print(f"{1.23:10.2e}") |
character string | s |
␣␣hello world |
print(f"{"hello world":13s}") |
Note:
- here
␣
has been used to denote a blank space- if the number of character spaces is set to zero, Python will use the smallest number of spaces required to fit the number or string, e.g.,
print(f"{1.23456:0.2f}")
will return1.23
using 4 character spaces
The commands below show the use of formatted output. Enter them into the code cells below and execute them to see the result.
print(f"Then, shalt thou count to {3:10d}, no more, no less.")
print(f"Then, shalt thou count to {3:10d}, no more, no less.")
Then, shalt thou count to 3, no more, no less.
Here the integer 3 was printed using 10 character spaces so there are 9 empty spaces to the left of the 3.
print(f"The value of pi to 4 decimal places is {math.pi:6.4f}.")
print(f"The value of pi to 4 decimal places is {math.pi:6.4f}.")
The value of pi to 4 decimal places is 3.1416.
Here 6 character spaces were used to display $\pi$, 1 space for the 3
, 1 space for the decimal point and 4 spaces for the decimal places.
print(f"The speed of light is {2.9979e8:0.2e} m/s.")
print(f"The speed of light is {2.9979e8:10.2e} m/s.")
The speed of light is 3.00e+08 m/s.
Here the number $2.9979\times 10^{8}$ was printed to 2 decimal places using the minimum number of spaces required due to the 0 after the colon.
name = "Andrew Wiles"
year = 1995
print(f"Fermat's last theorem was proven by {name:20s} in {year}.")
name = "Andrew Wiles"
year = 1995
print(f"Fermat's last theorem was proven by {name:20s} in {year}.")
Fermat's last theorem was proven by Andrew Wiles in 1995.
Here the character string "Andrew Wiles"
was printed using 20 character spaces. Note that the unused spaces appear after the string.
It often takes a bit of trial and error to get the right spacings in your program. Don't be afraid to experiment with your code.
It is possible to print multiple lines with a single print statement using the command \n
which moves to the next line.
The command below uses a single print
statement to print text over multiple lines. Enter it into the code cell below and execute it to see the result.
print("This text \nis printed\n\non multiple lines \n\n\nusing a single print command.")
print("This text \nis printed\n\non multiple lines \n\n\nusing a single print command.")
This text is printed on multiple lines using a single print command.
By default Python moves to the next line on completion of a print command. To suppress this we can use the following
print("some text", end="")
The commands in the code cell below shows how the use of end=""
suppresses the carriage return. Enter them into the code cell below and execute it to see the result.
print("This text ", end="")
print("is printed on the ", end="")
print("same line using multiple print statements")
print("This text ", end="")
print("is printed on the ", end="")
print("same line using multiple print statements")
This text is printed on the same line using multiple print statements
The \
command can come in useful to split up a print
comand when you are printing long lines of text.
The command below shows have we can use the \
symbol to print long lines of text using a single print
command. Enter it into the code cell below execute it to see the result.
print("some text, " \
"some more text in the same print command.")
print("some text, " \
"some more text in the same print command.")
some text, some more text in the same print command.
print(f"{math.e:0.20f}")
2.71828182845904509080
P = 1e5 # amount borrowed
r = 0.05 / 12 # monthly interest rate
years = 20 # the duration of the mortgage in years
n = years * 12 # the duration of the mortgage in months
C = r * P / (1 - (1 + r) ** -n)
print(f"Loan amount: £{P:0.2f}")
print(f"Mortage duration: {years} years")
print(f"Monthly repayments: £{C:0.2f}")
print(f"Total mortgage value: £{n * C:0.2f}")
Loan ammount: £100000.00 Mortage duration: 20 years Monthly repayments: £659.96 Total mortgage value: £158389.38
x // y
and x % y
commands may come in useful here.# Conversion quantities
seconds_in_a_minute = 60
seconds_in_an_hour = 60 * seconds_in_a_minute
seconds_in_a_day = 24 * seconds_in_an_hour
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_year = 365 * seconds_in_a_day
# 1 million seconds
x = 1000000
years = x // seconds_in_a_year
remaining = x % seconds_in_a_year
weeks = remaining // seconds_in_a_week
remaining = remaining % seconds_in_a_week
days = remaining // seconds_in_a_day
remaining = remaining % seconds_in_a_day
hours = remaining // seconds_in_an_hour
remaining = remaining % seconds_in_an_hour
minutes = remaining // seconds_in_a_minute
remaining = remaining % seconds_in_a_minute
print(f"There are {years} years, {weeks} weeks, {days} days, " \
f"{hours} hours, {minutes} minutes and {remaining} seconds in {x} seconds.")
# 1 billion seconds
x = 1000000000
years = x // seconds_in_a_year
remaining = x % seconds_in_a_year
weeks = remaining // seconds_in_a_week
remaining = remaining % seconds_in_a_week
days = remaining // seconds_in_a_day
remaining = remaining % seconds_in_a_day
hours = remaining // seconds_in_an_hour
remaining = remaining % seconds_in_an_hour
minutes = remaining // seconds_in_a_minute
remaining = remaining % seconds_in_a_minute
print(f"There are {years} years, {weeks} weeks, {days} days, " \
f"{hours} hours, {minutes} minutes and {remaining} seconds in {x} seconds.")
There are 0 years, 1 weeks, 4 days, 13 hours, 46 minutes and 40 seconds in 1000000 seconds. There are 31 years, 37 weeks, 0 days, 1 hours, 46 minutes and 40 seconds in 1000000000 seconds.
print()
and math library commands to produce the following table where each value is printed using 8 character spaces and 4 decimal places. x | sqrt(x) | exp(x) | ln(x) | cos(x)
------------------------------------------------------
1.0000 | 1.0000 | 2.7183 | 0.0000 | 0.5403
2.0000 | 1.4142 | 7.3891 | 0.6931 | -0.4161
5.0000 | 2.2361 | 148.4132 | 1.6094 | 0.2837
print(" x | sqrt(x) | exp(x) | ln(x) | cos(x)")
print("------------------------------------------------------")
x = 1
print(f"{x:8.4f} | {math.sqrt(x):8.4f} | {math.exp(x):8.4f} | {math.log(x):8.4f} | {math.cos(x):8.4f}")
x = 2
print(f"{x:8.4f} | {math.sqrt(x):8.4f} | {math.exp(x):8.4f} | {math.log(x):8.4f} | {math.cos(x):8.4f}")
x = 5
print(f"{x:8.4f} | {math.sqrt(x):8.4f} | {math.exp(x):8.4f} | {math.log(x):8.4f} | {math.cos(x):8.4f}")
x | sqrt(x) | exp(x) | ln(x) | cos(x) ------------------------------------------------------ 1.0000 | 1.0000 | 2.7183 | 0.0000 | 0.5403 2.0000 | 1.4142 | 7.3891 | 0.6931 | -0.4161 5.0000 | 2.2361 | 148.4132 | 1.6094 | 0.2837