1 of 39

2 of 39

Module 1 : Introduction to OR, Data

Science and Programming

Session 1C : Principles of Programming

Dr Daniel Chalk

“An invitation to programming”

3 of 39

An Invitation to Programming

4 of 39

With thanks to my teacher in 1985…

5 of 39

What is programming?

Computers carry out instructions given to them by the user.

Instructions are a series of steps that the computer works its way through.

Programming languages allow us to communicate with the computer to provide it with instructions

We can write computer programs that bundle up these instructions, to be executed when the program is run.

6 of 39

Computer Architecture

One or more input devices (keyboards / mice etc) are used by the user to issue instructions.

A Central Processing Unit (CPU) interprets the instructions and executes them.

Memory is used to store information that may be required later, either in the short-term (RAM - Random Access Memory) or after the computer has been shut down (Storage – e.g. hard drive).

One or more output devices (monitors / speakers etc) are used to communicate the outputs of instructions to the user

7 of 39

Low vs High Level Languages

Low Level Programming Languages Machine Language is unique to the architecture of the computer we’re programming. It requires us to give low-level instructions that deal directly with processor-level interactions.

High Level Programming Languages

These languages strongly abstract from the details of the computer. They use natural language and are much less complicated to use. Examples : BASIC, C, C++, Java, Python, and many more...

8 of 39

Variables

Often, when programming, we need to store pieces of information for later use.

We store this information in the computer’s memory.

We organise this information into “boxes” called variables. Each variable has a name and a value.

NAME

“Dan”

NUMBER_OF_MODULES

5

HSMA_TUTOR

True

9 of 39

Variable Types

Information stored in variables come in all shapes and flavours, known as types.

10 of 39

Variable Types

Some programming languages are strongly typed. This means that when you create a variable, you have to say what type of variable it is (ie what kind of information it’ll store) and it then won’t let you put anything different in there.

Python is not strongly typed. You just need to give the variable a name, and then chuck in whatever you like. If you chuck in a different type, it’ll convert the variable to a different type.

This has pros and cons. But we love Python here, so we’ll choose to think of it as “accommodating” rather than “whimsical”.

11 of 39

Example

Let’s say we want to build a simple calculator that just adds up two numbers. We would need to tell the computer to :

1. Ask the user for the first number

2. Store the first number in memory as a variable

3. Ask the user for the second number

4. Store the second number in memory as a variable

5. Perform an addition operation on the two variable values

6. Store the result of the addition in memory as a variable

7. Display the result variable to the user.

12 of 39

Conditional Logic

It’s rare that our programs are completely linear. Often, we need to change what happens depending on whether or not something is true. This is known as Conditional Logic.

Conditional Logic allows us to tell the computer “if this is true, then do this”.

We can think about Conditional Logic like a Decision Tree.

13 of 39

Conditional Logic

Sometimes we may need to check multiple things at once to decide what course of action to take.

14 of 39

Loops

Often, we need the computer to do the same thing (or things) multiple times. To do this, we use loops.

There are two kinds of loops :

  • for loops : these are loops where we say “do this bunch of stuff this many times”

  • while loops : these are loops where we say “keep doing this bunch of stuff whilst this condition is true”

15 of 39

For Loops

Let’s say we want the computer to add two sugars to our cup of tea.

16 of 39

For Loops

Using the concept of variables, we could adapt this for loop to ask the user how many spoonfuls of sugar they’d like.

17 of 39

While Loops

Let’s say we want the computer to sing to us until we fall asleep.

18 of 39

PAGE 1

Chalk Showers and Baths Inc has approached you to ask you to design software for a new automated shower system - the Chalk Automated Shower with Genius Responses and Banter (CASH-GRAB) System.

In the new system, the user steps into the shower, and the shower asks them for their name, saying “good morning”, “good afternoon” etc depending on the current time. It then waits for the user to say “begin”, at which point the shower checks whether the user has a previous perfect temperature stored. If they do, it turns on at that temperature, and will remain at that temperature until the user says “too warm” or “too cold”.

If the user does not have a perfect temperature stored, the shower turns on at 30C. The shower continues to raise the water temperature by 2C every 5 seconds (up to a maximum of 42C). If the user says “too warm”, the shower drops the temperature by 1C every 5 seconds (down to a minimum of 16C). If the user says “too cold”, the shower again starts raising by 2C every 5 seconds. CONTINUED…

Exercise 1 : Chalk Showers and Baths Inc

19 of 39

PAGE 2

If the user says “perfect”, then the shower holds the current temperature, and records it in a variable called perfect_temp, alongside their name in a variable called user_name, and stores both of them in a list called user_preferences. If the user had a previous perfect temperature, their new temperature overwrites it. However, they can adjust the temperature in the same way - the only difference is the shower will turn on at their previously stored temperature until a new one is stored.

The shower continues to run until the user says “end shower”, at which point the shower says “Goodbye” followed by their name.

CONTINUED…

Exercise 1 : Chalk Showers and Baths Inc

20 of 39

Exercise 1 : Chalk Showers and Baths Inc

PAGE 3

You’ll now split into your groups, and as a group :

  • Draw a diagram outlining how the system will work, flagging any conditional logic, loops and variable storage
  • Write a list of the variables that will be used in the system, along with the type of each variable, and a short description of what the variable is storing

If you have time, you should also :

  • Propose some improvements to the system, and include them on your diagram.

You have 45 minutes, followed by a 10 minute break. When we return, I’ll ask a few groups at random to share what they’ve done.

21 of 39

Functions

Often, when we write things we want a computer to do, we want to do them more than once, maybe at different points in our computer program. Or even in a different program altogether. We want stuff to be reusable without having to write it out each time.

To prevent us having to write out the same sets of instructions time and again, we can wrap up a set of instructions in a function.

A function can take inputs (optionally), do something with them, and then return an output (optionally). The things it does are just sets of instructions.

A function is defined by giving it a name, the list of inputs it should expect (if any), the things we want it to do, and the outputs it should return (if any). The function doesn’t do anything until it is called, however.

22 of 39

Functions

23 of 39

Functions

Example : find_minimum(3, 7, 2) would return the value 2

24 of 39

Indentations

In Python (and some other languages), things like functions are represented using indentations. This means that the block of code representing the function is indented (with the tab key) so it knows what code belongs inside the function, and what is outside of it.

Stuff not in the function

Stuff in the function

Function declaration

25 of 39

Object Oriented Programming

So far, we’ve talked about programming using the procedural programming methodology. This is where we write a program purely as a list of instructions to be carried out.

But an important concept in modern programming is Object Oriented Programming (OOP).

In OOP, everything is centred around objects that have their own attributes (variables that belong to them) and methods (which are what functions are called when they belong to objects). Objects are created as instances of classes, which are essentially generalised blueprints for how certain types of objects should work. Let’s look at an example.

26 of 39

Object Oriented Programming

What is this?

27 of 39

Object Oriented Programming

What is this?

An ambulance

28 of 39

Object Oriented Programming

Let’s say we want to write code that defines how an ambulance works.

There will be properties the ambulance has. Things like :

  • The trust it belongs to
  • The registration number
  • Whether a patient is currently on board
  • Whether the siren is currently going off

There will also be things the ambulance does :

  • Driving
  • Parking
  • Having patients loaded into it / out of it
  • Switching the siren on and off

In Object Oriented Programming, the things it has are known as attributes and the things it does are methods.

29 of 39

Object Oriented Programming

The Ambulance Class

The piece of code that acts as a blueprint for what an ambulance is and does.

Dan’s ambulance

Sammi’s ambulance

Amy’s ambulance

Instantiation

Instantiation

Instantiation

Dan, Sammi and Amy’s ambulances above are instances of the ambulance class. We refer to them as Objects and they can all do their own thing separately from each other.

30 of 39

Object Oriented Programming

CLASS : Ambulance

Attributes

name_of_trust : string

reg_number : string

patient_on_board : boolean

siren_on : boolean

Methods

drive (speed : float)

park (location : string)

load_patient (patient_name : string)

unload_patient (patient_name : string)

turn_on_siren ()

turn_off_siren ()

31 of 39

Object Oriented Programming

CLASS

INSTANCES (Objects)

dans_ambulance

name_of_trust = “Chalk NHS Trust”

reg_number = CH41 LKS

patient_on_board = False

siren_on = True

sammis_ambulance

name_of_trust = “Rosser Healthcare”

reg_number = HS44 MAS

patient_on_board = True

siren_on = True

32 of 39

Object Oriented Programming

Each instance of a class operates as a separate, unique object. So Sammi can drive her ambulance at 50mph with her sirens on… :

sammis_ambulance.drive(50)

sammis_ambulance.turn_on_siren()

…whilst Dan takes a leisurely drive back to base after a long shift…

dans_ambulance.drive(20)

dans_ambulance.turn_off_siren()

dans_ambulance.park(“Base”)

Whilst these ambulances operate as separate objects, we only had to write the code defining what an ambulance is and does once.

33 of 39

Constructors

A constructor defines what happens when an object is instantiated from a class (ie created from a blueprint).

The constructor essentially “constructs” the object, specifies the initial values for the attributes, and may even run some methods to start things off.

The constructor is itself a method within the class.

In our example, the constructor might set up the name of the trust and registration number, and specify that the siren is off and there’s no patient loaded at the start.

34 of 39

Object Oriented Programming

Object Oriented Programming uses something known as The Four Pillars to create efficient code :

ENCAPSULATION

The code that defines what an ambulance is and what it does is self-contained and separate from everything else.

ABSTRACTION

Someone who needs to use the code for an ambulance doesn’t need to know all the technical details.

INHERITANCE

An ambulance is a type of vehicle.

We’ll come back to this in a minute…

POLYMORPHISM

When I drive a car and I drive an ambulance, I say I’m driving. But driving an ambulance is a bit different to driving a car.

35 of 39

Inheritance

A vehicle

What is this?

36 of 39

Inheritance

In Object Oriented Programming, we can also have classes that are based on other classes. This is known as inheritance.

In our example, we could create a Vehicle class that has attributes and methods applicable to all vehicles, and then create an Ambulance class which inherits this stuff but adds its own ambulance-specific things too.

This improves efficiency if we need to write multiple classes that are similar.

In this example, the Vehicle class would be known as the parent and the Ambulance class as the child.

CLASS : Vehicle

Attributes

reg_number : string

Methods

drive (speed : float)

park (location : string)

PARENT

CLASS : Ambulance

Attributes

Everything in Vehicle carried across

patient_on_board : boolean

siren_on : boolean

Methods

Everything in Vehicle carried across

load_patient (patient_name : string)

unload_patient (patient_name : string)

turn_on_siren ()

turn_off_siren ()

CHILD

Inheritance

37 of 39

Inheritance

CLASS : Vehicle

Attributes

reg_number : string

Methods

drive (speed : float)

park (location : string)

PARENT

CLASS : Ambulance

Attributes

Everything in Vehicle carried across

patient_on_board : boolean

siren_on : boolean

Methods

Everything in Vehicle carried across

load_patient (patient_name : string)

unload_patient (patient_name : string)

turn_on_siren ()

turn_off_siren ()

CHILD

CLASS : Car

Attributes

Everything in Vehicle carried across

number_of_doors : int

Methods

Everything in Vehicle carried across

open_boot ()

close_boot ()

CLASS : Bus

Attributes

Everything in Vehicle carried across

passenger_capacity : int

Methods

Everything in Vehicle carried across

open_doors ()

close_doors ()

take_fare (fare_amount : float)

CHILD

CHILD

38 of 39

Designing Classes

There’s no right or wrong answer about how you should break up your code into object blueprints (classes). Sometimes it will be obvious, but other times there may be more subtle ways to carve things up.

Consider self-contained things in your system that have stuff / store information and do stuff.

Also, Object Oriented Programming can be difficult to grasp - even for experienced coders - so don’t worry if it takes you a while to get your head around this. You’ll have lots of practice in the course.

39 of 39

Exercise 2 : OOPs Dan Did it Again

You have been asked to ensure that the code for your CASH-GRAB shower system is Object Oriented.

After a 5 minute break, in your groups, you will have 30 minutes to draw up some diagrams showing the Classes you think you might use, along with their attributes and methods. You should include a short description of what each attribute stores and each method does. Remember - there are no right or wrong answers to this, it’s a design task! But try to achieve consistency within your design.

At the end of the task, we’ll ask a few groups to share their designs!

CLASS : Vehicle

Attributes

reg_number : string

Methods

drive (speed : float)

park (location : string)

reg_number : a string variable that stores the registration number of the vehicle

drive (speed) : a method that causes the vehicle object to begin driving at a given speed (given as a floating point number)

park (location) : a method that causes the vehicle to park at a given location (given as a string)