Teaching material for Quantitative Methods track in Semester 1
Tutorial 1
Tutorial 2
Tutorial 3
Tutorial 4
Tutorial 5
Tutorial 6
Tutorial 7
Tutorial 8
This week we will cover some basic concepts of Python programming like data types, variables, functions and loops. Actually, we already encountered some of these last week…
Exercise 1: Look back at last week’s tutorial. Identify an example of each of the following:
check your answer at the end of the tutorial
In Python, a function is like a pre-built tool that you can use to perform a specific task. Think of it as something similar to the tools you might have in your toolbox at home, like a stapler or an eraser. These tools are designed for specific jobs, just like Python functions are designed for specific tasks in your code.
For example, let’s consider the len()
function. It’s like a tool that helps you measure the length of something. You can use it to find out how long a piece of text is, or how many items are in a list.
Here’s how you might use the len()
function:
len("Hello World!")
If you run the code above in your notebook it should tell you how many characters in the text, including spaces and punctuation.
There are three important features of a function: the function name, the arguments and the output. In the example above,
len
is the function name,"Hello World!"
inside the brackets is an argument, and12
is the output.Exercise 2: Try the min()
function in your notebook and try to work out what it does.
min(x, y)
: replace x
and y
with numbers. Does this work with more than two numbers?min("x", "y")
: replace x
and y
with text. Does the function do something different?Don’t forget to use Markdown
cells to take notes!
If you are not sure what a function does, then you can use the help()
function to give you some more information.
Exercise 3: Use the help()
function to see what the function round()
does and how to use it. Type help(round)
in your notebook. Can you explain the output? Experiment with the function to confirm how it works.
The function print()
is one of the most commonly used built-in functions, and its primary purpose is to display information on the screen, making it visible to you as the programmer or to the user of your code.
Exercise 4: Notice that when you run code in a cell the output of the code is displayed on the screen. So why is the print()
function so useful?
To get an idea, consider the following code cell:
1 + 1
2 + 2
3 + 3
How can you use the print()
function to display the answer of all three sums (using only one code cell)?
In Python, data types are used to classify and categorise different types of data values. There are many data types in Python. To start with we will consider four important data types (later we will encounter some more):
Data type | Description | Examples |
---|---|---|
int |
Integers are whole numbers — no fractions or decimal points! | -5, 1, 5, 8, 97, and 3,043 |
float |
Floating point numbers are those that have a decimal point | -1.43, 1.0, 3.14, .09, and 5,643.1 |
string |
Strings are text or strings of characters. Use quotations " or ' to indicate string data |
“Python”, “My name is”, “12”, and “Seven point four” |
list |
Lists are lists of values. Lists can contain Integers, Floats, Strings or a combination of data types | [1, 2, 3], [-7.2, 23.9, 8.3], [“yes”, “no”, “maybe”], and [1, “Jane”, 2.5] |
Functions are usually designed to work with specific data types, so it can be important to use the right data type. In Python you can check the data type using the type()
function.
Exercise 5: Use the type()
function with different data values as an argument, e.g., type("hello")
. Use this function to identify an example of each of the four data types given above.
You can, in some cases, automatically convert data values from one type to another using functions such as float()
, int()
, and str()
.
Exercise 6: Experiment with the functions float()
, int()
, and str()
to see which data types can be easily converted to other data types.
Before we discuss lists, let’s first look at variables.
A variable is a name that you can use to store data in your Python program. Think of it as a container that holds a value.
In Python, creating a variable is as simple as choosing a name and assigning a value to it using the equals sign (=
). Here’s how you create a variable:
variable_name = value
name = "John" # This creates a variable named 'name' and assigns the string "John" to it.
age = 30 # This creates a variable named 'age' and assigns the integer 30 to it.`
Notice that you can use the #
to add comments inside of code cells to annotate code. This symbol tells python to ignore everything after it on that line.
You can use variables to change values in code without re-writing all the code. For instance, instead of writing a greeting for each person:
print("Hello Alice")
print("Hello Bob")
print("Hello Charlie")
…we can instead use a variable for the name and an F-string, or formatted string, to change the name in the line of code that prints the name:
name = "Alice"
print(f"Hello {name}") # This line of code stays the same
name = "Bob"
print(f"Hello {name}") # This line of code stays the same
name = "Charlie"
print(f"Hello {name}") # This line of code stays the same
The f
before the quotation marks tells Python that some variables are coming up in the text string. The variables are indicated by the curly brackets {}
. These brackets tell Python that the text inside is a variable name and that it should look at the data inside the variable.
Based on the example above, it might seem like using variables uses more code, so what is the point?! Well, imagine if you don’t know the specific data values when you write the code. For example, we might want the user to enter their own name (which we don’t know yet). We can ask a user for input using the input()
function.
Exercise 7: Try the following code in your notebook:
name = input("What is your name?")
age = input("What is your age?")
country = input("Which country do you come from?")
print(f"Hello {name}! You are age years old and come from country.")
Notice what happens when you run the code. Modify the last line of code so that it correctly greets you and tells you your age and where you are from.
Exercise 8: Complete the following code in your notebook
name = input("What is your name?")
age = input("What is your age at the end of this year?")
birth_year = # complete this line to calculate the birth year
print(f"{name} was born in {birth_year}")
Hint: don’t forget to think about data types!
We can name variables however we want. Python doesn’t read or interpret our variable names, but it can be helpful for you, or anyone else reading your code, if you use meaningful variable names. There are also a few rules about naming variables:
name
and Name
are different variables.if
, for
, while
, etc.) or function names as variable names.In Python, a list is a versatile and commonly used data type that allows you to store and manipulate collections of items. Lists are ordered and can contain elements of different data types, including other lists. Lists are defined using square brackets []
, and elements within the list are separated by commas.
You can create a list by enclosing a comma-separated sequence of elements within square brackets. For example:
my_list = [1, 2, 3, 4, 5] # A list of integers
fruits = ["apple", "banana", "cherry"] # A list of strings
mixed_list = [1, "hello", 3.14, True] # A list with mixed data types
empty_list = [] # An empty list
You can access individual elements of a list by their index. Python uses zero-based indexing, which means the first element is at index 0, the second at index 1, and so on.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Prints "apple"
print(fruits[1]) # Prints "banana"
print(fruits[2]) # Prints "cherry"`
You can also use negative indexing to access elements from the end of the list. -1
refers to the last element, -2
to the second-to-last, and so on.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # Prints "cherry"
print(fruits[-2]) # Prints "banana"
You can extract a portion of a list by slicing it using the :
operator. This creates a new list with the selected elements.
fruits = ["apple", "banana", "cherry", "date"]
sliced_fruits = fruits[1:3] # This creates a new list ["banana", "cherry"]
Lists are mutable, which means you can change their elements. You can assign a new value to an element using its index.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi" # Changes the second element to "kiwi"
Exercise 9: Experiment with the above examples. Create your own lists and use indexing to select and modify lists. Note these examples in your notebook.
A for
loop is used for iterating over sequence, which we call an iterable
. The most common type of iterable
is a list
(see above). For now, whenever you see iterable
, then you can just think of a list in Python.
Remember the example above when we wanted to greet a list of people? We used variables so that we could create a line of code that stayed the same for each name.
name = "Alice"
print(f"Hello {name}") # This line of code stays the same
name = "Bob"
print(f"Hello {name}") # This line of code stays the same
name = "Charlie"
print(f"Hello {name}") # This line of code stays the same
name = "Deborah"
print(f"Hello {name}") # This line of code stays the same
Whenever we can create a line of code that we repeat because it stays the same, then we can use a for
loop and a list to write the code more succinctly.
names = ["Alice", "Bob", "Charlie", "Deborah"] # define a list of names
for name in names: # you can read this as "for each name in the list names"
print(f"Hello {name}") # python runs this code (the same line as before)
Exercise 10: Test this in your notebook to confirm that both examples produce the same output.
Try import this
in your notebook. this
is the zen of Python.
Now try the following cells:
import this
love = this
this is love
love is True
love is False
love is not True or False
love is not True or False; love is love
Love is complicated. Python doesn’t have to be.