Linear Algebra and Programming Skills¶

Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University


Python Basics¶

Learning outcomes¶

On successful completion of this pages readers will be able to:

  • Use Jupyter Notebook to run Python commands;
  • Perform basic arithmetic operations using Python commands;
  • Import libraries into a Python program and call functions;
  • Create variables of different types and change a variable type;
  • Print formatted output.

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.


Jupyter notebooks¶

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.

Installing Python on your own machine using Anaconda¶

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.

  1. If you are using a machine on campus go to step 2 else go to https://www.anaconda.com/distribution/, download the appropriate version for your machine and install it following the onscreen prompts.
  2. Locate and load Anaconda Navigator.
  3. Click on the Launch button underneath Jupyter Notebook.
  4. A web broswer window will open showing you the file structure of your machine. Navigate to the directory that contains the notebook file you wish to open and then click on the filename to open it.

Google Colab¶

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:

  1. If you already have a Google account go to step 2 else go to https://myaccount.google.com/ and click on Create a Google account and follow the onscreen instructions.
  2. Go to https://colab.research.google.com;
  3. Sign in with your Google account details;
  4. Upload a Jupyter notebook by clicking in File and Upload Notebook.

Examples and exercises¶

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.

Using Jupyter notebooks¶

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
In [1]:
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day
Out[1]:
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
In [2]:
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week
Out[2]:
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).


Basic arithmetic operations¶

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

Example 1¶

Use Python to calculate the following:

  (i)   $3 + 4 = 7$

3 + 4
In [18]:
3 + 4
Out[18]:
7

  (ii)   $4 - 7 = -3$

4 - 7
In [19]:
4 - 7
Out[19]:
-3

  (iii)   $5 \times 3 = 15$

5 * 3
In [20]:
5 * 3
Out[20]:
15

  (iv)   $\dfrac{2}{9} = 0.2222\ldots$

2 / 9
In [21]:
2 / 9
Out[21]:
0.2222222222222222

  (v)   $2^5 = 32$

2 ** 5
In [22]:
2 ** 5
Out[22]:
32

  (vi)   $23 \operatorname{mod} 4 = 3$     ($x \operatorname{mod} y$ means the remainder when $x$ is divided by $y$)

23 % 4
In [24]:
23 % 4
Out[24]:
3

  (vii)   $\left\lfloor \dfrac{11}{3} \right\rfloor = 3$     ($\lfloor x \rfloor$ means $x$ rounded down to the integer below)

11 // 3
In [9]:
11 // 3
Out[9]:
3

Order of precendence of operations¶

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.

Example 2¶

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)
In [10]:
1 / (2 + 3)
Out[10]:
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
In [11]:
1 / 2 + 3
Out[11]:
3.5

This has calculated the value of $\dfrac{1}{2}+3$.


Exercise 1 - Basic arithmetic operations¶

  1. Use Python commands to evaluate:

    (a)   $2-(3+6)$;

In [12]:
2 - (3 + 6)
Out[12]:
-7

    (b)   $2(5-8(3+6))$;

In [13]:
2 * (5 - 8 * (3 + 6))
Out[13]:
-134

    (c)   $2(2-2(3-6+5(4-7)))$;

In [14]:
2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
Out[14]:
76

    (d)   $\dfrac{2(5-4(3+8)))}{3(4-(3-5))}$;

In [15]:
(2 * (5 - 4 * (3 + 8))) / (3 * (4 - (3 - 5)))
Out[15]:
-4.333333333333333

    (e)   $\dfrac{2(4^5)}{81-5^2}$.

In [16]:
(2 * 4 ** 5) / (81 - 5 ** 2)
Out[16]:
36.57142857142857
  1. Use a Python command to calculate the remainder of 14151 divided by 571.
In [17]:
14151 % 571
Out[17]:
447
  1. Use a Python command to calculate the number of times 1111 can be divided by 14.
In [18]:
1111 // 14
Out[18]:
79

Shorthand notation for basic arithmetic operations¶

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.


Using libraries¶

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()

The math library¶

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.

Example 4¶

Using functions from the math library, evaluate the following:

  (i)   $\sqrt{9} = 3$

import math

math.sqrt(9)
In [24]:
import math

math.sqrt(9)
Out[24]:
3.0

  (ii)   $\cos\left( \dfrac{\pi}{4} \right) = \dfrac{\sqrt{2}}{2} \approx 0.7071$

math.cos(math.pi / 4)
In [25]:
math.cos(math.pi / 4)
Out[25]:
0.7071067811865476

  (iii)   $e^2 \approx 7.3891$

math.exp(2)
In [2]:
math.exp(2)
Out[2]:
7.38905609893065

  (iv)   $4! = 24$

math.factorial(4)
In [3]:
math.factorial(4)
Out[3]:
24

Exercise 2 - Using the math library¶

  1. Use math library functions to evaluate:

    (a)   $\sqrt{3^2 + 4^2}$ ;

In [28]:
math.sqrt(3 ** 2 + 4 ** 2)
Out[28]:
5.0

    (b)   $\cos(\pi)$;

In [29]:
math.cos(math.pi)
Out[29]:
-1.0

   (c)   $\sin^{-1}(1)$;

In [30]:
math.asin(1)
Out[30]:
1.5707963267948966

   (d)   $\ln(e^2)$;  

In [31]:
math.log(math.exp(2))
Out[31]:
2.0

   (e)   $\log_{10}(1000000)$.

In [4]:
math.log10(1000000)
Out[4]:
6.0

Variables¶

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.

Example 5¶

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
In [33]:
x = 1
y = 2.5
z = -3

x + y + z
Out[33]:
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
In [34]:
x, y, z = 1, 2.5, -3

x + y + z
Out[34]:
0.5

Variable names¶

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:

  • a variable name cannot start with a number and must start with a letter or the underscore character
  • a variable name can only contain alpha-numeric characters and underscores (A - z, 0 - 9, and _ )
  • variable names are case-sensitive (age, Age and AGE are three different variables)

Example 6¶

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
In [35]:
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

Types of variables¶

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.

Example 7¶

Define the following variables

  (i)   $a = 2$

a = 2
a
In [36]:
a = 2
a
Out[36]:
2

  (ii)   $b = 1.5$

b = 1.5
b
In [37]:
b = 1.5
b
Out[37]:
1.5

  (iii)   $c = 5000000000 = 5 \times 10^9$

c = 5e9
c
In [38]:
c = 5e9
c
Out[38]:
5000000000.0

  (iv)   $d = 2 + 3i$

d = 2 + 3j
d
In [39]:
d = 2 + 3j
d
Out[39]:
(2+3j)

  (v)   $e = \text{True}$

e = True
e
In [40]:
e = True
e
Out[40]:
True

  (vi)   $f = \text{"this is a string"}$

f = "this is a string"
f
In [41]:
f = "this is a string"
f
Out[41]:
'this is a string'

Determining the type of a variable¶

We can determine what type a variable is using the type command.

type(variable_name)

Example 8¶

Determine the type of variable for each of the variables defined in example 6.

  (i)   a = 2

type(a)
In [42]:
type(a)
Out[42]:
int

  (ii)   b = 1.5

In [43]:
type(b)
Out[43]:
float

  (iii)   c = 5e9

In [44]:
type(c)
Out[44]:
float

  (iv)   d = 2 + 3j

In [45]:
type(d)
Out[45]:
complex

  (v)   e = True

In [46]:
type(e)
Out[46]:
bool

  (vi)   f = "this is a string"

In [47]:
type(f)
Out[47]:
str

Converting variable types¶

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'

Example 9¶

Use Python commands to convert the following variables

  (i)   $2.5$ to an integer

int(2.5)
In [48]:
int(2.5)
Out[48]:
2

  (ii)   $3$ to a floating point number

float(3)
In [49]:
float(3)
Out[49]:
3.0

  (iii)   $123$ to a string

str(123)
In [50]:
str(123)
Out[50]:
'123'

Exercise 3 - Using variables¶

  1. Write a program that uses variables to convert a temperature in degrees Centigrade $C$ to degrees Fahrenheit $F$ using the formula

    $$F = \frac{9}{5}C + 32.$$
    What is the equivalent temperature in Fahrenheit of $37^\circ$C?
In [51]:
C = 37
F = 9 / 5 * C + 32
F
Out[51]:
98.60000000000001
  1. Write a program that calculates the length of the hypotenuse of a right-angled triangle given the lengths of the two other sides are 2 and 3.
In [52]:
side1, side2 = 2, 3
hypotenuse = math.sqrt(side1 ** 2 + side2 ** 2)
hypotenuse
Out[52]:
3.605551275463989
  1. Write a program that calculates an angle of a right-angled triangle in degrees given the lengths of the adjacent and opposite sides are 4 and 5.
In [53]:
adjacent, opposite = 4, 5
angle = math.atan(5 / 4)
angle
Out[53]:
0.8960553845713439

Formatting your code¶

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.

Spaces¶

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.

Example 10¶

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
In [54]:
1*2+3*4+5/6
Out[54]:
14.833333333333334
1 * 2 + 3 * 4 + 5 / 6
In [55]:
1 * 2 + 3 * 4 + 5 / 6
Out[55]:
14.833333333333334

Comments¶

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"""

Example 11¶

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
In [56]:
"""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
Out[56]:
11

Splitting lines of code¶

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.

Example 12¶

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
In [56]:
# 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
Out[56]:
9

Printing output¶

To output text or the value of a variable within a Python program we can use the print() command.

print("some text")
print(x)

Example 13¶

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")
In [57]:
print("hello world")
hello world

  (ii)   the value of the variable $x=2$

x = 2
print(x)
In [59]:
x = 2
print(x)
2

  (iii)   the values of the two variables $b=3$ and $c = 4$

b, c = 3, 4
print(b, c)
In [60]:
b, c = 3, 4
print(b, c)
3 4

Printing text and numbers¶

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.

Example 14¶

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.")
In [61]:
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.

Formatted output¶

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 return 1.23 using 4 character spaces

Example 15¶

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.")
In [62]:
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}.")
In [63]:
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.")
In [58]:
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}.")
In [65]:
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.


Printing multiple lines¶

It is possible to print multiple lines with a single print statement using the command \n which moves to the next line.

Example 16¶

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.")
In [66]:
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.

Suppressing the carriage return¶

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="")

Example 17¶

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")
In [67]:
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

Printing long lines of text¶

The \ command can come in useful to split up a print comand when you are printing long lines of text.

Example 18¶

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.")
In [68]:
print("some text, " \
      "some more text in the same print command.")
some text, some more text in the same print command.

Exercise 4 - Printing output¶

  1. Output the value of $e$ to 20 decimal places.
In [69]:
print(f"{math.e:0.20f}")
2.71828182845904509080
  1. Write a program that uses the formula below to calculate the monthly repayments and total value of a mortgage of £100,000 taken out over 20 years at a fixed annual interest rate of 5%.

    $$C = \frac{rP}{1-(1+r)^{-n}}$$
    where $C$ is the monthly repayment amount, $r$ is the monthly interest rate, $P$ is the amount borrowed, $n$ is the number of monthly repayments.

    Use print commands to output the loan amount, the duration of the mortgage, the annual interest rate, the monthly repayments and total value of the mortgage.
In [59]:
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
  1. Write a Python program that calculates the number of years, weeks, days and minutes that are are equivalent to 1 million seconds and 1 billion seconds. Output the answer in a single meaningful sentence.

    Hint: The x // y and x % y commands may come in useful here.
In [61]:
# 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.
  1. Use suitable 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
In [62]:
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