Performing Calculations with Computers II#
Learning Objectives:#
To have an understanding of objects and variable types in Python.
To understand the difference between ints, floats, strings and tuples.
To understand and be able to use lists, tuples, dictionaries and numpy arrays.
To be able to define and use a function in Python.
Understand what a Python Module is.
Overview#
In this session we are going to develop our understanding of what Python is and how we use it by learning about the different objects used in Python. Take some time to read through these materials and try to understand what the snippets of code provided are doing.
Note: Sometimes we want to write notes in our script that do not interfere with our code. These are called comments. We can add a comment into our code by typing “#” before the text we wish to comment. Use comments sparingly - our code should be understandable without them!
# This is how I would write a comment in my code.
Strings#
A string (str) is simply a collection of words and or numbers. In Python we can write a string by placing some information in either ‘ ’ or “ “. For example, below I will create a string and get the computer to print it out for me using the print() command:
myString = "This is an example of a string!"
print(myString)
# I can also print a string without saving it as a variable.
print("How many odd numbers are there between 0 and 10?")
# If I want to print a number, I can simply insert it into the
# print command brackets separated from my string by a comma:
print("How many odd numbers are there between 0 and 10?", 5, "?")
This is an example of a string!
How many odd numbers are there between 0 and 10?
How many odd numbers are there between 0 and 10? 5 ?
Often it will be useful to take just a section of a string or perhaps a specific character. The way to do this is by slicing, which is the term used to describe splitting data into smaller chunks. We can slice lots of things (lists and arrays), but here let’s demonstrate how we can slice a string.
newString = "Go and explore the peak district!"
# Note that the Oth element of the string is the first letter of our string.
# In Python all indexes start at zero NOT one!
print(newString[0])
print(newString[3])
print(newString[5])
G
a
d
# We can also slice strings into sectionns. For example, the command below will print the first 5
# characters of our string, but not the 5th:
print(newString[0:5])
Go an
# Alternatively, we may wish to index from the end of our string. For example, if we wanted to print the from
# the last five characters from the end to two before the end of the string we could slice as follows:
print(newString[-5:-2])
ric
#Perhaps we want to print characters of our string, but skip every other character:
print(newString[0:34:2])
G n xlr h ekdsrc!
# We could always print the string backwards?
print(newString[::-2])
!crsdke h rlx n G
Above we have shown how we may slice strings into smaller chunks of information. In other instances it may be useful to merge strings together - this is known as concatenating.
string1 = "Go and explore"
string2 = "the peak district!"
# We can concatenate the strings using "+". Note I need to add a space.
sentence = string1 + " " + string2
print(sentence)
Go and explore the peak district!
Using Python we are also able to do lots of things with strings. For example, we can replace specific words, change which letters are capitalised, search for terms in the string, or “multiply” the string.
# We can also use functions built into Python to modify our string.
# For example, perhaps we live in the north-west and the peak district is a little far out for us:
newString = newString.replace('peak', 'lake')
print(newString)
Go and explore the lake district!
# Finally, perhaps you still haven't gone out and explored and I wish to be a little louder:
newString = newString.upper()
print(newString)
GO AND EXPLORE THE LAKE DISTRICT!
# Now you have finally explored the lake district you decide to write a book about it.
# The title of the book needs to be formatted nicely:
newString = newString.title()
print(newString)
Go And Explore The Lake District!
# Remind me, did we explore in the lake district or the peak district? Lets check our string to find out.
searchTerm1 = "lake"
searchTerm2 = "peak"
print("It is", searchTerm1 in sentence, 'that', searchTerm1, 'is in the sentence.')
print("It is", searchTerm2 in sentence, 'that', searchTerm2, 'is in the sentence.')
It is False that lake is in the sentence.
It is True that peak is in the sentence.
# Are we enjoying learning about strings!?
politeAnswer = "yeah "
disingenuousAnswer = politeAnswer * 3
print(politeAnswer)
print(disingenuousAnswer)
yeah
yeah yeah yeah
Ints and floats#
Now that we have covered the basics of strings, let’s consider how we deal with numbers in Python. Simply put we can either use ints or floats. An int is an integer number whereas a float is a floating point number (does not need to be a whole number).
myInteger = 1
myFloat = 15.0
# Let's see what class the interpreter assigns to each of our variables:
print(myInteger, type(myInteger))
print(myFloat,type(myFloat))
1 <class 'int'>
15.0 <class 'float'>
Something to note is that when we perform calculations using floats and ints, the output will also either be a float or an integer based on the calculation performed. If we only use ints the output will also be an int, but if we use a float at any point in our calculation, the output will be a float.
# Here we demonstrate how types may be converted during calculation
print(type(15*myInteger))
print(type(1*myFloat))
print(type(myInteger*myFloat))
print(type(myInteger+myFloat))
<class 'int'>
<class 'float'>
<class 'float'>
<class 'float'>
As we may need to use specifically either a float or an int later in our script, it is very convenient that we are able to convert variable types very easily in Python.
# By putting our float inside the int() function, we can convert it back into an int
newVariable = int(myInteger*myFloat)
print(newVariable,type(newVariable))
15 <class 'int'>
# If we so wish we can also convert our variable back into a float
newVariable = float(newVariable)
print(newVariable,type(newVariable))
15.0 <class 'float'>
# We can also convert our variable into a string, but note how this impact the calculations we perform:
newVariable =str(newVariable)
print(5*newVariable)
15.015.015.015.015.0
As a consequence of how computers store information using binary (1’s and 0’s), often the number we tell the computer to use is not the exact number it uses, although using a 64bit computer, the difference will be very small!
If we execute the following code calculation in our computer we would expect it to return the answer 0.55, but this is not the answer we get…
4.9 - 4.845
0.055000000000000604
Lists and Tuples#
Up to this point we have only considered how to store single items of information, but often we will need to store more information. For example, if we wanted to plot a graph we would need the information corresponding to the x-coordinates and the information corresponding to the y-coordinates. It would be impractical to store every single x and y value as a single variable.
In Python a list is just a collection of information. To define a list we simply put our information in a set of square brackets and separate each item using a comma. As before we can slice, concatenate and index our list items.
nordicCountries = ["Iceland", "Denmark", "Norway", "Sweden", "Finland"]
balticCountries = ["Estonia", "Lativa", "Lithuania"]
# Using the index I can extract items from a list or slice the list:
islandNations = nordicCountries[0]
print("The island nations that are part of the nordic nations include: ", islandNations)
continentalNordics = nordicCountries[1:5]
print("The continental nations that are part of the nordic nations include: ", continentalNordics)
The island nations that are part of the nordic nations include: Iceland
The continental nations that are part of the nordic nations include: ['Denmark', 'Norway', 'Sweden', 'Finland']
# Similarly, I can concatenate lists:
coolContinentalCountries = balticCountries + continentalNordics
print("Of the nations that form the baltic and nordic countries, the following are continental: \n", coolContinentalCountries)
Of the nations that form the baltic and nordic countries, the following are continental:
['Estonia', 'Lativa', 'Lithuania', 'Denmark', 'Norway', 'Sweden', 'Finland']
# A list can be made up from any collection of information:
randomList = ["Aston Martin", 11, ["apple", "pear", "orange"], 3.14159]
print(randomList)
print("The third item in my list is", randomList[2])
print("The last two items in my list are", randomList[-2:])
['Aston Martin', 11, ['apple', 'pear', 'orange'], 3.14159]
The third item in my list is ['apple', 'pear', 'orange']
The last two items in my list are [['apple', 'pear', 'orange'], 3.14159]
A tuple is very similar to a list, the difference being that a tuple is immutable (it cannot be changed). We can create a tuple by putting our items between round brackets and separated by commas. Although we can still index, slice and concatenate tuples, there are only two methods associated with them: index and count.
myTuple = ("England", "Ireland", "Scotland", "Wales", "Wales", "France", "Netherlands")
# The count method will tell us how many instances of an item appear in the tuple
print(myTuple.count("Wales"))
#The index method will tell us where an item appears in the tuple
print(myTuple.index("Netherlands"))
2
6
Dictionaries#
A dictionary may be used to store information with specific associated keys. For example, perhaps we would like to catalogue information and would like to be able to reference these properties later in our script.
VW_Cars = {
"Golf": {
"year": 2022,
"price": 25000,
"engine": "1.4L TSI",
"horsepower": 147,
"fuel_type": "Petrol"
},
"Polo": {
"year": 2021,
"price": 20000,
"engine": "1.0L MPI",
"horsepower": 79,
"fuel_type": "Petrol"
},
"Passat": {
"year": 2022,
"price": 35000,
"engine": "2.0L TSI",
"horsepower": 174,
"fuel_type": "Petrol"
},
}
Note how the dictionary above is structured. As we use dictionaries to store information, there are lots of methods we can use to find, extract, and remove items from the dictionary. Below is an example of how we may use the .keys() and .get() methods.
# We can find out what the keys in our dictionary are using the .keys() command:
print("The keys in our car catalogue are:", VW_Cars.keys())
The keys in our car catalogue are: dict_keys(['Golf', 'Polo', 'Passat'])
# We can extract information from the dictionary as follows using the .get() command:
model = "Golf"
print("Information for VW", model, ":", VW_Cars.get(model))
Information for VW Golf : {'year': 2022, 'price': 25000, 'engine': '1.4L TSI', 'horsepower': 147, 'fuel_type': 'Petrol'}
# Or simply:
print("Information for VW Passat:", VW_Cars["Passat"])
Information for VW Passat: {'year': 2022, 'price': 35000, 'engine': '2.0L TSI', 'horsepower': 174, 'fuel_type': 'Petrol'}
Numpy Arrays#
One of the most ubiquitous data structures is the array. An array is a matrix of numbers that can be any number of dimensions. For now, we will only use 2D arrays to make visualising them easier. We will use a type of array called a Numpy Array, this is very common and used by nearly everyone. To use numpy we have to import the numpy library into Python to give us access to the array commands. To do this we simply write an import command at the top of our Python script.
import numpy as np
# The "as np" is present as it means that each time we call something from the numpy library, we only
# need to write "np." before the numpy command, rather than "numpy." e.g. "np.mean" vs "numpy.mean"
It is vital that you understand how to make and use numpy arrays as you will be using throughout the semester for data analysis and plotting. Take time to read through the code below and try to understand what it is doing.
# Lets start by making a simple 1D array:
array1 = np.array([1,2,3,4,5,6,7,8,9])
print(array1)
print('The first value in my array is', array1[0])
print('The last value in my array is', array1[-1])
print('The first 3 values in my array are', array1[0:3])
[1 2 3 4 5 6 7 8 9]
The first value in my array is 1
The last value in my array is 9
The first 3 values in my array are [1 2 3]
# It is often useful to store information in 2 dimensional arrays:
array2 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(array2)
[[1 2 3]
[4 5 6]
[7 8 9]]
# When extracting information/slicing 2D arrays, we must provide additinal information
# (corresponding to the x index and the y index)
print('The value in the top left is', array2[0,0])
print('The first row is', array2[0,:]) # prints the whole row
print('The middle column is', array2[:,1]) # prints the whole column
print('The mean of the 1D array is', np.mean(array1))
print('The mean of the 2D array is', np.mean(array2))
The value in the top left is 1
The first row is [1 2 3]
The middle column is [2 5 8]
The mean of the 1D array is 5.0
The mean of the 2D array is 5.0
# We can also ask numpy to perform calculations using a specific axis, thus giving us three different mean values:
print('The mean of the 2D array in Y is', np.mean(array2, axis=0))
print('The mean of the 2D array in X is', np.mean(array2, axis=1))
The mean of the 2D array in Y is [4. 5. 6.]
The mean of the 2D array in X is [2. 5. 8.]
When using numpy arrays, we are not limited to performing calculations on a single array, we can perform calculations using multiple arrays e.g. addition, subtraction, multiplication and matrix calculations. Furthermore, within the numpy library there are many different methods that can be called, for example, we may wish to resize our array, or determine how many individual elements it is made up from.
# Let's resize our first array so that it has the same dimensions as our second:
print('Shape', np.shape(array1))
array1 = np.reshape(array1,[3,3]) # Lets make it 3x3
print('Shape', np.shape(array1))
print(array1)
Shape (9,)
Shape (3, 3)
[[1 2 3]
[4 5 6]
[7 8 9]]
# Summation
print(array1+array2)
[[ 2 4 6]
[ 8 10 12]
[14 16 18]]
# Multiplication
print(array1*array2)
[[ 1 4 9]
[16 25 36]
[49 64 81]]
#Real matrix multiplication
print(np.matmul(array1, array2))
[[ 30 36 42]
[ 66 81 96]
[102 126 150]]
Before we move onto the next topic, I would like to make you aware of a few tools in numpy that you may find useful:
np.zeros() - used to create an array filled with zeros,
np.ones() - used to create an array filled with ones,
np.linspace() - used to create a 1D array with linearly spaced values between a start and stop, where we define how many values we would like in our array,
np.arange().- used to create a 1D array with values between a start and stop, where we define the step increment between the two values.
Examples of the following numpy tools are provided below:
zerosArray = np.zeros([3,6])
print(zerosArray)
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
onesArray = np.ones([3,6])
print(onesArray)
[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]
l_Array = np.linspace(0, 9, 10)
print(l_Array)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
a_Array = np.arange(0, 10, .5)
print(a_Array)
[0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. 5.5 6. 6.5 7. 7.5 8. 8.5
9. 9.5]
Activities#
Strings#
Save your first, middle (if applicable) and as three different variables (first, middle, last). Use the print statement and appropriate string methods to:
Print the statement “My full name is: first middle last”.
Print the statement in all caps.
Print the statement in capitalising only the first letter of each word.
Print the statement backwards.
Print every second letter of the statement.
Create a new variable “age” and set it equal to your age. Make a new string that says “and my age is x”. Concatenate the first and second statements into a new sentence.
# Strings activitiy:
Calculations#
Using the len() function, determine how many letters are in your first and second names. Ensure that these numbers are stored as variables (first & second). The len() function determines the length of something, this may be a string or a list or an array etc. An example is shown below:
aLongName = "Daenerys Stormborn of House Targaryen, the First of Her Name, Queen of the Andals and the First Men, Protector of the Seven Kingdoms, the Mother of Dragons, the Khaleesi of the Great Grass Sea, the Unburnt, the Breaker of Chains"
print(len(aLongName))
# This would return and print the number of characters (letters and spaces) in aLongName - in this case 228.
228
From the two saved variables determine:
The product of “first” and “second”.
The radio of “first” to “second”.
The value of “first” to the power of “second”.
The total number of letters in your first and second name.
The difference in the number of characters of your first and second name.
For each calculation above, get the computer to print out a statement such as “the product of first and second is … ”.
# Calculations activity:
Lists and Numpy Arrays#
Generate a list of 10 items and:
Print the 7th item of the list.
Print the first 4 items of the list.
Print the 2nd, 4th, 6th and 8th items of the list.
Generate a numpy array containing the numbers 0 to 12:
Determine all values of the times tables up to 12 using this array (e.g. 0x0 to 12x12).
Print each array containing the times tables e.g. (0, 2, 4, 6… and then 0, 3, 6, 9…).
# List and numpy array activity: