Module 1 : Introduction to OR, Data
Science and Programming
Session 1C : Principles of Programming
Dr Daniel Chalk
“An invitation to programming”
An Invitation to Programming
With thanks to my teacher in 1985…
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.
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
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...
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
Variable Types
Information stored in variables come in all shapes and flavours, known as types.
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”.
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.
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.
Conditional Logic
Sometimes we may need to check multiple things at once to decide what course of action to take.
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
Let’s say we want the computer to add two sugars to our cup of tea.
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.
While Loops
Let’s say we want the computer to sing to us until we fall asleep.
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
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
Exercise 1 : Chalk Showers and Baths Inc
PAGE 3
You’ll now split into your groups, and as a group :
If you have time, you should also :
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.
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.
Functions
Functions
Example : find_minimum(3, 7, 2) would return the value 2
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
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.
Object Oriented Programming
What is this?
Object Oriented Programming
What is this?
An ambulance
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 :
There will also be things the ambulance does :
In Object Oriented Programming, the things it has are known as attributes and the things it does are methods.
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.
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 ()
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
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.
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.
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.
Inheritance
A vehicle
What is this?
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
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
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.
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)