3  Lab: Repetition

Welcome to the second part of IM939 lab 1. Here we are going to look at how to deal with repetition, or actually how to avoid repetition using functions, methods and control flow.

DRY

Python takes pride in using the “Don’t Repeat Yourself (DRY)” coding principle, and this is something you will likely see repeated almost as a mantra by (Python) coders and something you should get familiar with.

3.1 Functions

How do we get the length of a list?

lunch_ingredients = ['gravy', 'potatoes', 'meat', 'veg']
len(lunch_ingredients)
4

We used a function. The syntax for a function is function_name(argument1, argument2). In our above example we passed the list lunch_ingrediants as an argument to the len function.

james = {'age':35, 'hair colour': 'brown', 'Glasses': 'yes'}
len(james)
3

One very useful function is to check a data type. In base R it may be obvious but when you move to libraries, with different data types, it may be worth checking.

type(james)
dict
type(lunch_ingredients)
list
type(55)
int

3.2 Methods

What is really happening? Well all data types in Python have functions built in. A variable is an object (a string, a list, an int, etc.). Each object has a set of methods do stuff with that object.

For example, I can add a value to the lunch_ingredients list liks so

lunch_ingredients.append('yorkshire pudding')
lunch_ingredients
['gravy', 'potatoes', 'meat', 'veg', 'yorkshire pudding']

Note the objectname.method notation. By adding a yorkshire pudding, a fine addition to any meal, my lunch ingredients now number 5.

I can count these easily.

len(lunch_ingredients)
5

Which is the same as the following.

lunch_ingredients.__len__()
5

You can tab complete to see what methods are available for a given object. There are quite a few built in python functions.

However, do be aware that different objects will likely have different methods. For instance, can we get a length of an int?

len(4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 len(4)

TypeError: object of type 'int' has no len()

The error “TypeError: object of type ‘int’ has no len()” essentially means an int object has no len dunder method.

To see the methods for a given object, type in the object name in a code cell, add a period ‘.’ and press tab.

3.3 Flow control

3.3.1 For loops

You may need to repeat some code (such as reading lines in a csv file). For loops allow you to repeat code but with a variable changing each loop.

For instance,

for ingredient in lunch_ingredients:
    print(ingredient)
    
gravy
potatoes
meat
veg
yorkshire pudding

The above loop went through each ingrediant and printed it.

Note the syntax and spacing. The for statement finishes with a : and the next line has a tab. For loops have to be defined like that. If you miss out the tab then you will be shown an error. It does make the code more readable though.

for ingredient in lunch_ingredients:
    print(ingredient)
gravy
potatoes
meat
veg
yorkshire pudding

At least the error is informative.

We can have more than one line in the loop.

for ingredient in lunch_ingredients:
    print('I love to eat ' + ingredient)
    print('food is great')
    
I love to eat gravy
food is great
I love to eat potatoes
food is great
I love to eat meat
food is great
I love to eat veg
food is great
I love to eat yorkshire pudding
food is great

3.3.2 If statements

An if statement allows us to run different code depending on a condition.

my_num = 3

if my_num > 5:
    print('Number is bigger than 5')
    
if my_num < 5:
    print('Number is less than 5')
Number is less than 5

We can include this in a for loop.

for i in range(10): #go through each number 0:10
    print(i)
0
1
2
3
4
5
6
7
8
9
for i in range(10):
    print(i)
    if i == 5:
        print('We found a 5!')
0
1
2
3
4
5
We found a 5!
6
7
8
9

You can also include an else part of your if statement.

for i in range(10):
    print(i)
    if i == 5:
        print('We found a 5! :)')
    else:
        print('Not a 5. Boo hoo :(')
0
Not a 5. Boo hoo :(
1
Not a 5. Boo hoo :(
2
Not a 5. Boo hoo :(
3
Not a 5. Boo hoo :(
4
Not a 5. Boo hoo :(
5
We found a 5! :)
6
Not a 5. Boo hoo :(
7
Not a 5. Boo hoo :(
8
Not a 5. Boo hoo :(
9
Not a 5. Boo hoo :(