Topics
• This week we’re going to skim over the topics we’ve covered during the course.
• This is your last chance to ask questions about anything you might be unsure
about or not understand!
• The topics we’ll go over are:
• Problem Solving,
• Software Development Methodologies,
• Algorithms,
• Searching and Sorting.
• Introduction to Programming in Python (Data Types & Operators),
• Conditionals and Loops,
• Strings, Substrings and Files,
• Functions, Methods and Objects,
• Testing, Debugging and Documentation,
• Using and Writing Libraries,
• Performance, Efficiency and Optimisation.
3
What is Problem Solving?
• “Finding a solution to a difficult or complex
question or situation; to engage in the actions or
thoughts necessary to discover solutions to
problems.”
- https://en.oxforddictionaries.com/definition/problem-solve
4
Routine and Non-Routing Problems
• Routine (simple)
problems are the
kinds of problems
have simple solutions and
that occur regularly.
• Non-Routine
(complicated &
complex)
problems are more
difficult and often
require devising
strategies to solve.
• Then there are
wicked problems…
5
Characteristics of Wicked Problems
• Difficult to define.
• Have many interdependencies and are often multi-causal.
• Resolution attempts often result in unforeseen consequences.
• Often not stable.
• No clear solution.
• Socially complex.
• Responsibility of multiple domains.
• (Some) characterized by chronic policy failure.
Source: Australian Public Service Commission. (2012). Tackling wicked problems : A public policy perspective. Retrieved
from: http://www.apsc.gov.au/publications-and-media/archive/publications-archive/tackling-wicked-problems
6
The Importance of Problem Solving
“Regardless of profession or title, at some level we are all
hired to do the same job. We are all problem solvers, paid to
anticipate, identify, prevent, and solve problems within our
areas of expertise.
This applies to any job, at any level, in any organization,
anywhere in the world, and being aware of this is absolutely
vital to job search and career success in any field.”
― Martin Yate, Knock ‘Em Dead 2016: The Ultimate Job Search Guide
7
The Six-Step Problem Solving Process
• There are many different problem-solving methods, and the six-step method is
just one of them.
• The problem for most people is that they do not use one process to solve
problems and issues or to make decisions.
• Another problem is that people are not consistent in how they solve problems!
They do not find something that works and then do it the same way over and
over to be successful!
• The Six-Step Problem-Solving Process is as follows:
- Identify the problem,
- Analyse the problem,
- Generate potential solutions,
- Select and plan a solution,
- Implement the solution,
- Evaluate the solution
8
Step 1 – Identifying the Problem
• When identifying a problem the definition of the problem needs to be clear,
concise and unambiguous.
• You might consider using the Five W’s to help narrow this down:
• Who,
• What,
• When,
• Where, and
• Why.
• Note: ‘Why’ considers the impact of the problem – that is, why we should solve
it, rather than why the problem is occurring.
9
Step 2 – Determining the Root Cause(s) of a Problem
• Sometimes a Fishbone Diagram is used to help determine the root cause of a
problem. In such a diagram you start by agreeing on a definition of the problem,
and then break up to problem into separate chains of possible cause and effect.
10
Step 2 – Determining the Root Cause(s) of a Problem (Cont’d)
• For example, the below diagram charts possible causes and effects of why a
basketball player might miss a free throw:
11
Further Steps
• Some problem solving models have additional steps such as:
• 7 – Prevent Recurrence
• Now that you’ve investigated the problem and understand it, how can
you stop this problem from ever occurring again?
• 8 – Reward the team for a job well done!
• When a team has worked hard on a difficult problem and solved it well,
give them some kind of reward for all their hard work!
• This could be in the form of:
Money (woo!),
Time off (especially time off ‘in lieu’ or any unpaid overtime),
A raise or promotion (if appropriate),
• For example, the 8-step model is used by car manufacturers such as Ford and
Toyota when working on the engineering problems of creating vehicles.
12
Problem Solving Strategies and Techniques
• Some of the most commonly used problem solving strategies include:
• Trial and error,
• Using some form of algorithm to reach a solution, and
• Using some form of heuristic to reach a solution.
Source:
https://www.khanacademy.org/science/health-and-medicine/executive-systems-of-the-brain/cognition-2014-03-27T18:40:04.738Z/
v/problem-solving
13
Software Development Methodologies
• Largely regardless of programming domain or language, we tend to use one of
a handful of techniques to successfully design software that functions as
expected.
• The most commonly used development methodologies are:
• The Waterfall model,
• Agile development, and
• Scrum.
• We’ll take a brief look at the main characteristic of each methodology over the
next few slides, and then we can have a chat about which one we think is the
best method and why that might be.
14
The Waterfall / Waterflow Model
Fun fact: The maintenance of a system usually accounts for the vast majority of it’s lifetime costs! Not convinced? See:
https://en.wikipedia.org/wiki/Long_tail
• The waterfall model is the most traditional model of the three where the lifetime
of the developed system goes through a fixed sequence of steps.
• In this model we start with a large
requirements gathering phase to
work out what the system should do.
• Then we move on to designing how
the system should do these things.
• Then we actually write the
software, then test it to
make sure it all works and
meets our requirements.
• Finally the system is deployed and
maintained – often for many
years.
15
Agile Development
• Agile Development mostly refers to using a more cyclic iterative model of
software development.
Note: In this model you don’t end up with a single finished product at the end, you get multiple prototypes as you go
along until you either accept a final prototype or do a final ‘clean’ re-write of the final prototype’s functionality.
16
Agile Development (Cont’d)
• Another way of looking at the same process is like this, where you build up the
final application from a series of prototypes:
• Each sprint represents a concerted effort by the development team to create
the next prototype.
• In the Scrum method, the shareholders (i.e. people you’re building the software
system for) are closely involved at the beginning, and during each sprint.
17
Abstraction
• When we talk about abstraction – what we’re really talking about is
simplification.
• So when designing a computer program or working with data, what we want to
concentrate on are just the important parts with all of the ‘fluff’ taken away.
• Or to put it another way, we want to focus on only the information that is
relevant to the task at hand.
• When we simplify something, our brains are better able to deal with it – because
there’s less to think about!
• This makes life easier for us, and makes it less likely that we’ll make a mistake
or error.
18
Abstraction (Cont’d)
• If we wanted to write a program to store the record the progress of a student
in a course – here are some of the student attributes that we could store:
…and so on.
• But which of these attributes are the most important ones to store student
scores?
Family status
Middle name
Last name
Age
Date of Birth
Religion
Hair colour
Program
Institution
Student ID
Photograph
Next of Kin
Email address
Home address
Semester address
Home telephone
Semester telephone
Mobile phone
Eye colour
Medical history
Work history
Qualifications
Education
Nationality
Marital Status
Citizenship
Hobbies
First name
Grade Point Average
Volunteer experience
Awards
Criminal history
Drivers License
Income
Skin colour
Courses
19
Abstraction (Cont’d)
• Taking that big list of attributes of a Student, we can abstract away the ones
we don’t need to handle student scores, leaving us with something like this:
• So we’ve crunched down our list of 30+ attributes to just three – which are the
only ones required to uniquely identify a student, and we’ve added a few
attributes to track the student’s scores.
Question: Could we crunch our three attributes down any further? If so, should we?
First
Name
Last
Name
Student
ID
Task 1 Task 2 Task 3 Task 4
Jess Smith 30001111
John Brown 30001122
Jack Singh 30001133
James White 30001144
Joy Green 30001155
Model of a student AFTER abstraction
20
Modelling
• Modelling is the process where we look at a problem or situation and analyse it
so that we can unambiguously describe it.
• Once we have a model of a system, we can implement the model in software.
• So what we’re really saying is that modelling helps us to:
• Determine requirements and functionality,
• Communicate these requirements between all stakeholders (i.e. clients,
programmers, managers etc.), and
• Ensure consistency of work.
• To model a system there are a number of commonly used tools and formats
which we can use, and which you should be familiar with.
21
Activity Diagrams / Flowcharts
• Activity Diagrams show the decisions / branching of a program or system
based on the state of the system.
• For example, a Process Order activity diagram could look something like this:
22
Class Diagrams
• We typically draw class diagrams in a box listing the class name, the
attributes / properties of the class, and the methods (i.e. operations we can
perform) using objects of this class.
Source: Riley, D., Hunt, Kenny A, & ProQuest. (2014). Computational thinking for the modern problem solver (Chapman &
Hall/CRC textbooks in computing). Boca Raton, FL: CRC Press. p.118.
22
Name of the class
Attributes / Properties
Methods / Operations
23
Use Case Diagrams
• Although use cases imply the sequence of events, they do so in a loose
fashion (unlike flowcharts which have specific start and end points to the flow).
• An «extend» relationship occurs whenever one action is an extension or
specialised version of another. An «include» relationship results from one
action making use of another as part of its own function.
Source: Riley, D., Hunt, Kenny A, & ProQuest. (2014). Computational thinking for the modern problem solver (Chapman &
Hall/CRC textbooks in computing). Boca Raton, FL: CRC Press. p.122.
System boundary
Relationship
Function / Action
Actor (may be a
person or
different system)
24
Algorithms
• Algorithms are sequences of steps which are carried out in a specific order to
produce a desired outcome.
• Although you might not have any ‘book knowledge’ of algorithms, you actually
use them every single day.
• You already have an algorithm to:
• Brush your teeth,
• Make a phone call,
• Watch a DVD or BluRay,
• Wash the dishes, etc.
• All that makes these processes algorithms is writing down the series of steps
you perform, along with any branch conditions (can’t find toothpaste? phone is
flat, TV is switched off, etc.).
• Once you have the steps and their sequence worked out the desired outcome
will be the same every time!
25
Algorithms (Cont’d)
• Computers use algorithms for absolutely everything. They control what
happens when you switch your computer on, log in, launch an application etc.
• Really, you can think of all computer programs as algorithms – they’re just
sequences of steps along with branching points that determine the state of the
machine at any given time. So in this way, you can think of algorithms as the
text-only version of flowcharts!
EEqquuiivvaalleenntt
26
Pseudocode
• When creating or writing down algorithms, we commonly use pseudocode instead
of a specific programming language.
• Pseudocode is just a straight-forward plain-English description of what’s happening
that’s intended to be easy to comprehend and unambiguous.
• We indent sections of our pseudocode based on any branching criteria. For
example, if we wanted to print out whether each student in a class had passed or
failed an assignment then we might write out our algorithm in pseudocode like this:
For each student in class
If student assignment grade is greater than or equal to
50
Print student name + “Pass”
else
Print student name + “Fail”
27
Sorting Algorithms – Bubble Sort
• Here’s our starting list of un-sorted values:
• We compare the left-most two values (14 and 33) and see that they’re already
sorted, so we leave them alone:
• We move to the right and compare the next two values (33 and 27) and see
that they are not sorted, so we swap them:
• We move to the right again and compare the next two values (33 and 35) and
see that they’re sorted, so we leave them alone:
14 33 27 35 10
14 33 27 35 10
14 27 33 35 10
14 27 33 35 10
28
Sorting Algorithms – Bubble Sort (Cont’d)
• We move on to the final pair of values (35 and 10) and see that they aren’t
sorted so we swap them:
• Now that we’re at the end of the list we go back to the beginning and see that
14 and 27 are still sorted:
• We move across and 27 and 33 are still sorted so that’s fine:
• We move across again and see that 33 and 10 not sorted though, so we need
to swap them:
14 27 33 10 35
14 27 33 10 35
14 27 33 10 35
14 27 10 33 35
29
Sorting Algorithms – Bubble Sort (Cont’d)
• We look at the final 33 and 35, and as they’re sorted we leave them alone:
• Now we go back to the beginning again – 14 and 27 are in order:
• But 27 and 10 aren’t so we swap them:
• Carrying on through the list, 27 and 33 are now fine:
• As are 33 and 35 so again we leave them alone:
14 27 10 33 35
14 27 10 33 35
14 10 27 33 35
14 10 27 33 35
14 10 27 33 35
30
Sorting Algorithms – Bubble Sort (Cont’d)
• Back at the beginning, 14 and 10 are in the wrong order so we swap them:
• Moving along, 14 and 27 are fine:
• 27 and 33 are fine:
• And 33 and 35 are fine:
• Finally, we go all the way through the list again from the beginning and this time
we don’t make ANY swaps at all – this indicates that our list is now sorted!
Visualisation of process: https://www.youtube.com/watch?v=RT-hUXUWQ2I
Hungarian folk dance version (I kid you not): https://www.youtube.com/watch?v=lyZQPjUT5B4
10 14 27 33 35
10 14 27 33 35
10 14 27 33 35
10 14 27 33 35
10 14 27 33 35
31
Sorting Algorithms – Selection Sort
• Our next sorting algorithm is called selection sort and it works a little
differently – with selection sort, you essentially take the smallest entry from the
unsorted portion of an array and build a sorted array at the start, entry by entry.
• Let’s start with the same list of numbers we had before:
• We take the first element and assign it to be our lowest value:
• Then we compare it to the next value, and the next – and so on – until we either
find a value that is lower than our current lowest value, or we hit the end of the
list:
14 33 27 35 10
14 33 27 35 10
14 33 27 35 10
14 33 27 35 10
14 33 27 35 10
NNooppee!!
32
Sorting Algorithms – Selection Sort (Cont’d)
• When we get to the 10 it is lower, so that becomes our lowest value:
• As we’ve now hit the end of the list, we swap our current lowest value with the
first element, so now we have one sorted element:
• Then we start from the next index along and make that our lowest:
• 27 is smaller than 33 so that becomes our new lowest:
• 27 is not smaller than 35, but 14 is smaller than 27 – so 14 is our new lowest:
10 33 27 35 14
10 33 27 35 14
10 33 27 35 14
10 33 27 35 14
14 33 27 35 10
10 33 27 35 14
33
Sorting Algorithms – Selection Sort (Cont’d)
• As we’ve now hit the end of the list we swap our lowest value (14) with the
value in index 1 (i.e. the 2nd location – so 33 and 14 swap places):
• Next up we’re starting at index 2 (3rd location) and marking that as our lowest:
• Neither 35 nor 33 are lower than 27, so when we get to the end of our list 27 is
still our lowest value:
10 33 27 35 14
10 14 27 35 33
SSoorrtteedd sseeccttiioonn UUnnssoorrtteedd sseeccttiioonn
10 14 27 35 33
10 14 27 35 33
10 14 27 35 33
34
Sorting Algorithms – Selection Sort (Cont’d)
• Technically we swap our lowest value (27) with index 2 (3rd location) here – but
it’s already in index 2 so doing so doesn’t change anything:
• Moving on to start at index 3 (4th location) we take 35 as our lowest:
• 33 is lower than 35 so that then becomes our lowest:
• Aaaand we’ve hit the end of the list again so we swap the first unsorted index
(i.e. 35) with our current lowest (33), then as there’s only a single ‘unsorted’
value at the right-hand side, it’ll be our largest and we’ve get a sorted list!
Visualisation of process: https://www.youtube.com/watch?v=3hH8kTHFw2A
10 14 27 33 35
10 14 27 35 33
10 14 27 35 33
10 14 27 35 33
SSoorrtteedd sseeccttiioonn UUnnssoorrtteedd sseeccttiioonn
35
Searching
• We can sort numbers, words, colours – absolutely anything where we can say
that one thing is bigger than or smaller than another thing.
• But why is this such a big deal? Who cares?!
• WE CARE! Because the other thing that we often need to do is (you guessed
it):
Searching!
And we can search data faster if it has been sorted!
36
Executing Programs
• There are three different ways in which we can convert a program in a high-level
language like Python into a version that can be executed on a CPU:
• Compilation
• All program code is converted into machine code before the program
executes. Once a program has been compiled into machine code it is
ready to be executed – this typically means that the code can execute
very quickly.
• Pure Interpretation
• Each line of program code in converted into machine code for execution
(one line at a time) as the program executes. This typically means that
the code executes less quickly than compilation.
• Hybrid Implementation
• In hybrid implementation, the program code is translated into an
intermediate programming language which is designed to be able to
be interpreted quickly before the program executes. Once this has been
done, it is this intermediate code that is actually interpreted into machine
code. This typically results in code that executes relatively quickly.
Note: So the execution speed hierarchy from fastest to slowest is: Compilation, then Hybrid Interpretation, then Pure
Interpretation.
37
Executing Programs (Cont’d)
• To paraphrase the previous slide, we could say:
• Compilation
• Your source code is converted to an executable file BEFORE you run it.
• Pure Interpretation
• Your source code is converted into executable instructions AS you run it.
• Hybrid Implementation
• Your source code is converted to an intermediate format BEFORE you run
it (compilation)…
• …and then than intermediate format is converted into executable
instructions AS you run it (interpretation).
• Think of Java – your Test.java gets compiled into Test.class, and then
that Test.class gets interpreted into machine code in order to actually run!
38
Pure Interpretation
• Pure interpretation is largely the opposite approach to compilation.
• In an interpreted programming language, the program source code is
interpreted line-by-line at runtime, with no intermediate translation
whatsoever.
• You can think of the interpreter program as a simulation of a machine whose
fetch-execute cycle deals with high-level language programs rather then
machine code instructions.
Source
Program
IInntteerrpprreetteerr
CCoommppuutteerr
Results
Input data to go
with program
Machine code
Source code
to machine
code
39
Standard Mathematical Operators
• Now we know about some of the most common types of data we might want to
work with, it’s time to move on to some of the operators than help us perform
calculations.
• If you’ve programmed in any language before then you’ll already be familiar
with many of them, although there are some Python-specific operators, too.
• The standard “big four” operators are:
Operator
Symbol
Operator Name Example
- Plus 10 + 2 equals 12
- Minus 10 – 2 equals 8
- Multiply 10 * 2 equals 20
/ Divide 10 / 2 equals 5
40
Some Other Operators
• While we don’t need to use these right away, there are a few other operators that
sometimes come in handy – for example:
• Modulus
• The symbol for modulus is %
• For example, we might say x = 10 % 3, and x would be 1 because it’s the
remainder when we divide 10 by 3 (i.e. 10 divided by 3 is 3 remainder 1).
• Power
• To raise a value to a power we use **
• For example, we might say 3 ** 2 to mean 32 which is 9.
• Equal to
• To compare two primitive values we use two equals signs ==.
• For example, is 4 == 4 (True), is 4 == 5 (False).
• Not Equal To
• Just like it sounds but using the symbols !=, so for example 4 != 4 is False
(because 4 is equal to 4), 4 != 5 is True because 4 is not equal to 5 etc.
41
Operator Precedence
• The order in which operators are applied to data is really important, and there’s
a simple rule that governs which “value-pairs” in a calculation get calculated
before others!
• For example, what’s the result of the following calculation?
2 + 10 * 5 = ?!?
• Clue: BODMAS!
42
Operator Precedence (Cont’d)
• In the previous question, we could either say the answer is 60 by calculating:
(2 + 10) * 5 = 60
• Or we could say that the correct answer is 52 by calculating:
2 + (10 * 5) = 52
• If you said 52 then you’d be correct! Because according to BODMAS, the order
in which we calculate the “value-pairs” is:
• Brackets
• Orders (i.e. powers and roots like 32 or )
• Division
• Multiplication
• Addition
• Subtraction
43
The input Function
• When we want to get console input from the user, we use the input method.
• We typically assign the result of running the input method to a variable as we
just saw when we wrote:
name = input(“Please enter your name: “)
print(“Hello, ” + name + “!”)
• When using the input function, the type of the data returned is always a string.
• This will cause us problems if we did something like this:
number = input(“Please enter a number between 1 and 10: “)
sum = number + 5
print(“Adding 5 to that gives: ” + sum) NNooppee!!
44
The input Function (Cont’d)
• The reason we’re going to have a problem is because we’re getting some data
and assigning it to a variable called number…
• …and then we’re trying to add together that number variable and an integer –
but the input function converts whatever data is entered into a string!
• And as we saw previously – we can’t add an int and a string together!
45
The input Function (Cont’d)
• So how do we get around this problem?
• We have to convert the entered data into the type we want it to be!
• For example:
number = input(“Please enter a number between 1 and 10: “)
sum = int(number) + 5
print(“Adding 5 to that gives: ” + sum)
• The int function attempts to convert whatever is in the brackets after it into an
integer.
• It will fail if we give it data which cannot be converted into an int, for example if
we wrote the following then the conversion would fail:
number = int(“This won’t convert to int!”)
46
The input Function (Cont’d)
• We could also do it like this, if we wanted to:
number = int( input(“Please enter a number between 1 and 10: “) )
sum = number + 5
print(“Adding 5 to that gives: ” + sum)
• They both work the exam same way and provide the same result.
• Where we do the conversion doesn’t matter – that we do the conversion
matters!
• Also, this “conversion” has a special name – it’s called a cast. So you might
“cast an int to a float” or “cast a string to an int” etc.
• Make sure you know what casting is (i.e. changing the data type of a variable) –
it’s a very important thing to know. Trust me on this.
47
• So we could write some code like this:
num1 = int( input(“Please enter the first number: “) )
num2 = int( input(“Please enter the second number: “) )
sum = num1 + num2
print(“The sum of”, num1, “+”, num2, “is:”, sum)
• We can also achieve the same output as the above by making the final line:
print( “The sum of + is “.format(num1, num2, sum) )
• Each set of curly-braces, , in the above line will have the relevant variable
substituted in its place, in the order they’re declared:
print( “The sum of + is “.format(num1, num2, sum) )
String / Print Substitutio
48
String / Print Substitution (Cont’d)
• We can do a better job by substituting like this:
print( “The sum of 0 + 1 is 2”.format(sum, num1, num2) )
• This has the benefit that when have a numbered (or “indexed”) substitution, we
could do something like this if we wanted and it would all work out alright:
print( “The sum of 2 + 0 is 1”.format(num2, sum, num1) )
…but to
compensate…
Note: The order that we specify the variables to substitute is always the same, the first is 0, the second is 1 and so on!
00 11 22
00 11 22
Order has
also changed!
Order has
changed!
OOrrddeerr ccaannnnoott cchhaannggee!!
00 11 22
49
Branching
• Branching is a term used to describe how we can do one thing out of a range
of possible things based on one or more conditions.
• You already know a lot about branching – you do it everyday in your lives!
• Let’s take some plain-English examples of branching behaviour you might do on
any given day:
• IF your cup of coffee is cold you might MICROWAVE it.
• IF your phone rings you might either ANSWER it or IGNORE it.
• IF your car is LOW ON FUEL you might FILL UP AT A PETROL STATION
or RISK RUNNING OUT OF GAS!
• IF it’s raining AND you have an umbrella AND you’re outside, you might PUT
THE UMBRELLA UP.
Simples!
50
Conditional Operators
• When we branch in a programming language, we use conditional operators
to help us specify the conditions under which we want to do one thing, or a
different thing (i.e. the behaviour of our program changes depending on what’s
going on!)
• To do this we can use any of the conditional operators from the table below*: - = there are one or two others like “===” (strict equality), but we’re not too fussed about them right now.
Conditional
Operator
Meaning Example Evaluates to…
< Less than if (3 < 4): DoSomething() 3 < 4 is True <= Less than or equal to if (3 <= 3): DoSomething() 3 <= 3 is True More than if (5 > 4): DoSomething() 5 > 4 is True
= More than or
equal to
if (5 >= 4): DoSomething() 4 >= 4 is True
== Equal to if (5 == 4): DoSomething() 5 == 4 is False
!= Not equal to if (5 != 4): DoSomething() 5 != 4 is True
51
“if” Statements
• Whenever we want to perform one operation or another, different operation
depending on circumstances, we can use an if statement.
• if statements in Python are arranged like this:
if (some-condition-is-true):
do-something
• What’s really important here is that we put the colon ( : ) after the closing
braces of our condition, and that we tab-indent the code that we want to run if
the condition is true!
• For example:
if (3 < 4): print(“three is less than four!”) print(“three is still less than four!”) Note: We can perform this ‘if-test’ without using brackets if we want, i.e. if 3 < 4: instead of if (3 < 4): 52 Using “if” with “else” • Commonly we might want to do one thing under certain conditions, and something else otherwise – and the way that we do this is to use if statements in combination with else statements, like this: currentDay = “Tuesday” weekendStartDay = “Saturday” if (currentDay == weekendStartDay): print(“Yay!”) print(“What fun stuff shall we do?”) else: print(“Boooo!”) print(“Work work work… Bah!”) print(“What’s for lunch?”) Will the final print statement ever run, sometimes run or always run? Which one of these two blocks will run? 53 The elif Statement • Fortunately for us, we don’t have to indent things out to absurdity – we can use the elif statement, instead! • For example, the previous code can now be written like this: cost = 0 num = int( input(“Please enter the number 1, 2, 3 or 4: “) ) if (num == 1): cost = 1000 elif (num == 2): cost = 2000 elif (num == 3): cost = 3000 elif (num == 4): cost = 4000 print( “Final cost is: $0”.format(cost) ) No ridiculous amount of indentation required! 54 Short-hand Notation to Manipulate Variables (Cont’d) • We can perform mathematical operations and assignment the long way… myNumber = 5 myNumber = myNumber + 10 # myNumber is now 15 myNumber = myNumber * 2 # myNumber is now 30 myNumber = myNumber – 6 # myNumber is now 24 myNumber = myNumber / 2 # myNumber is now 12 • …or we can use a short-hand equivalent (which just saves us some typing): myNumber = 5 myNumber += 10 # myNumber is now 15 myNumber *= 2 # myNumber is now 30 myNumber -= 6 # myNumber is now 24 myNumber /= 2 # myNumber is now 12 55 Using OR in Python • All languages have some manner of OR operator, and in Python we use the word ‘or’ for this operation. • We generally use the OR operator, when we want something to happen if one or more conditions is met. • A pseudo-code example: If I am thirsty OR I am too hot: Drink something cold. • Another example might be: If it is raining OR it is cold: Wear a jacket. “Pseudo-code” is just a plain language (not computer code) description of what the code does! 56 Using OR in Python (Cont’d) • Let’s say that we have two boolean variables (True/False values) called cond1 and cond2 (i.e. conditions 1 and 2). • If we create a “truth-table” using these two conditions, we get this: • We can see from the above table that for an OR operation to be true, either condition A must be true OR condition B must be true. • And if both of them are true, then great! But we only needed one to be true to get a result of true! Value of cond1 Value of cond2 Result of OR operation True True True True False True False True True False False False 57 Using OR in Python (Cont’d) • Now let’s write some code to make sure we can see how this works in Python. Take another look at the pseudo-code below: If I am thirsty OR I am too hot: Drink something cold. • If we were thirsty, but not too hot, we might write this in Python as follows: thirsty = True tooHot = False if (thirsty == True) or (tooHot == True): print(“Hmm, I feel like having a cold drink”) else: print(“I don’t feel like a cold drink.”) • Which of the two print statements will get executed in the code above? 58 Using OR in Python (Cont’d) • When we’re comparing boolean values in an if-statement we can use a little bit of shorthand, if we’d like to, in order to save ourselves some typing. • For example, instead of writing the code if (todayIsSunday == True): [DO-SOMETHING] • We could instead write: if (todayIsSunday): [DO-SOMETHING] • We can do the same to check if something is False by using the NOT operator, which is an exclamation mark ( ! ). • So if (!todayIsSunday) and if (todayIsSunday == False) also the exact same thing. Use whichever you’d prefer! These mean the exact same thing! 59 Using OR in Python (Cont’d) • Now let’s get some feedback from the user, and act on it. But first, just to make things clear, let’s write some pseudo-code which describes what we want to do: Ask the user if they understand the ‘or’ operator If the user answers “Y” OR “y” then: Display “Yay! Good stuff!” Otherwise: Display “Keep trying – it’ll make sense soon!” • We could then write the following Python code to perform the above: answer = input(“Getting the OR operator? (y/n): “) if (answer == “Y”) or (answer == “y”): print(“Yay! Good stuff!”) else: print(“Keep trying – it’ll make sense soon!”) 60 Using OR in Python (Cont’d) • So far, we’ve been performing one of two actions depending on whether at least one condition has been true. Instead of directly jumping into some code, we can also do things like set other variables. For example: wearJacket = False raining = input(“Is it raining? (y/n) “) cold = input(“Is it cold outside? (y/n) “) if (raining == “y”) or (cold == “y”): wearJacket = True if (wearJacket == True): print(“Brrr! Definitely jacket weather!”); else: print(“It’s quite nice out today – no jacket req’d!”) 61 Converting Cases • We can make comparing input easier on ourselves by converting the input into either uppercase or lowercase. Let’s try it out: name = “Bruce Wayne” name = name.upper() print(name) • Which prints out: BRUCE WAYNE • While to convert to lowercase we could use: name = “BrUcE WaYnE” name = name.lower() print(name) • Which prints out: bruce wayne 62 Using AND in Python • Now we know how the OR operator works, let’s take a look at the AND operator, which is designated by an ampersand symbol: & • We generally use the AND operator, when we want something to happen if more than one condition must be met. • A pseudo-code example of this could be: If my mobile phone has charge AND my mobile phone has signal: I can receive a phone call. • Another example might be: If I have a valid passport AND I have a plane ticket to Paris: I can fly to Paris. 63 Using AND in Python (Cont’d) • To take this a bit further, let’s say that we have two boolean variables called cond1 and cond2 (i.e. conditions 1 and 2). • If we create a truth-table for the AND operator using these two boolean variables, we get this: • We can see from the above table that for a AND operation to be true, both condition A AND condition B must be true. Value of cond1 Value of cond2 Result of AND operation True True True True False False False True False False False False 64 Using AND in Python (Cont’d) • Let’s give this a go – take a look at the following pseudo-code: If I my mobile phone has charge AND has signal: I can receive a phone call. Otherwise: I can’t receive a phone call. • We might write this in Python as follows: mobileHasCharge = True mobileHasSignal = False if (mobileHasCharge == True) and (mobileHasSignal == True): print(“Call me!”) else: print(“The number you have dialled cannot be reached.”) • Which of the two print statements will get executed in the code above? 65 Using a Mixture of Data Types with Conditionals • So far we’ve been using the same types of data for our AND or OR statements, but we don’t have to – we can mix up the data types if we like: name = “Dave” sunny = True cash = 350 if (name == “Dave”) and (sunny == True) and (cash > 300):
print(“Dave is winning! =D”)
else:
print(“It’s just another day…”)
• In the above code, if any single one of the three conditions that we’re testing for
evaluates to False, then the program will print “It’s just another day…”
SSttrriinngg ddaattaa ooff ttyyppee ssttrr
BBoooolleeaann ddaattaa ooff ttyyppee bbooooll
IInntteeggeerr ddaattaa ooff ttyyppee iinntt
66
Creating and Working With Ranges of Numbers
• Python allows us to create a set of integers between zero and an end value by
using the range statement.
• We can then print out that range of numbers using the print statement, for
example:
print( range(5) )
• When we run the above command, it will display all the whole numbers from
zero up until it’s at “one step less than” the end value we specified, going up
by 1 per time.
• So if we run the above command, the output we’ll see is:
[0, 1, 2, 3, 4]
EEnndd vvaalluuee
67
Creating and Working With Ranges of Numbers (Cont’d)
• We can also use a two parameter version of the range statement where we
specify a starting value and an ending value.
print( list( range(4, 10) ) )
• Again, when we run the above command, it will display all the whole numbers
from the first number we specified, up until it’s at “one step less than” the end
value we specified.
• So if we run the above command, the output we’ll see is:
[4, 5, 6, 7, 8, 9]
FFiirrsstt ppaarraameetteerr:: ssttaarrtt vvaalluuee
SSeeccoonndd ppaarraameetteerr:: eenndd vvaalluuee
68
Creating and Working With Ranges of Numbers (Cont’d)
• When we just saw the range function, we provided it:
• A range-start value of 4, and
• A range-end value of 10.
• Because we only provided two parameters (i.e. 4 and 10) to the range statement,
the numbers in our range increased by 1 each time as the default behaviour.
• But what if we wanted the numbers in our range to increase by 2’s? Or 5’s? Or
7’s? In this case, we can specify a third parameter, which controls how much to
increase the value of the numbers in our set by!
• This might sound complicated – but it’s really very simple! Try running this:
print ( list( range(0, 10, 2) ) )
• If we run the above command, we’ll generate a set of numbers starting at 0 and
going up by 2 each time until the value is one step less than our end value of 10:
[0, 2, 4, 6, 8]
69
Creating and Working With Ranges of Numbers (Cont’d)
• The technical term for this “one step less than” behaviour is that the range
statement returns us a set of numbers in what’s called a:
half-inclusive range
• In maths, you might see this specified as:
[Start-value, End-value)
• The square bracket [ means that the number is INCLUDED in the range.
• The parenthesis ) means that the number is NOT INCLUDED in the range.
• Let’s try some examples…
70
Variables and Lists
• As we’ve seen, a variable is a named piece of data, and it usually only contains
a single piece of information.
• For example, these are all variables:
total = 123
name = “Bob”
price = 49.95
• A list, on the other hand, is still a named piece of data – but this time it usually
contains more than a single piece of information, for example:
beatles = [“John”, “Paul”, “George”, “Ringo”]
• Or it could contain a set of the last seven days temperatures:
lastSevenDayTemps = [23, 25, 28, 34, 23, 23, 17]
71
Variables and Lists (Cont’d)
• Let’s just take a quick look at our Beatles example again:
beatles = [“John”, “Paul”, “George”, “Ringo”]
• If you’ve programmed before, you might recognise this looks like an array –
however, while arrays are typically fixed in size Python lists are dynamic in
size, and they can also store different types of data (unlike typical arrays).
• Every item in the list has a numbered location called its index that starts at 0
and goes up to one-less-than-the-number-of-items.
• So in the above example:
• beatles[0] is “John”,
• beatles[1] is “Paul”,
• beatles[2] is “George”, and
• beatles[3] is “Ringo”.
Quiz: What’s the value of beatles[4]?
72
Storing Different Types of Data in Lists
• In most programming languages if you create an array / list, then all the data in
it has to be of the same type (i.e. integers, floats, strings etc).
• In Python, because it’s a dynamically typed language this is not the case and
we’re free to mix and match data types.
• For example, the following is perfectly legal in Python:
myList = [ ‘Bananas’, 123, True, float(3.14159) ]
• Printing it out gives you exactly what you’d expect:
[ ‘Bananas’, 123, True, 3.14159 ]
73
Adding and Removing Elements to/from Lists
• Lists are dynamic structures, which means that not only can we modify the data
in a list, we can add things to them and remove things from them as we please.
For example:
shoppingList = [‘Milk’, ‘Bread’]
shoppingList.append(‘Sugar’)
print(shoppingList) # Prints [‘Milk’, ‘Bread’, ‘Sugar’]
shoppingList.remove(‘Milk’)
print(shoppingList) # Prints [‘Bread’, ‘Sugar’]
shoppingList.insert(1, ‘Bananas’) # Params: index, data
print(shoppingList) # Prints [‘Bread’, ‘Bananas’, ‘Sugar’]
del shoppingList[2]
print(shoppingList) # Prints [‘Bread’, ‘Bananas’]
Note: When we call remove and give a specific item, only the first element that matches is removed, not all of the
matching elements!
74
Multidimensional Lists
• We can embed lists inside other lists to create multidimensional lists if we want
to, for example:
first = [1, 2, 3]
second = [4, 5, 6]
third = [7, 8, 9]
myList = [first, second, third]
• To access the elements of a multidimensional array we use multiple sets of
square brackets:
print(myList) # prints [ [1,2,3], [4,5,6], [7,8,9] ]
print(myList[0]) # prints [1,2,3]
print(myList[1]) # prints [4,5,6]
print(myList[2]) # prints [7,8,9]
print(myList[0][0]) # prints 1
print(myList[1][1]) # prints 5
Note: We can embed lists as deeply as we’d like, so we can have a list which contains lists which contains lists which
contains lists and so on.
TThhiiss lliisstt ccoonnttaaiinnss lliissttss!!
75
Tuples
• Tuples (pronounced too-ple) are similar to lists, but once you’ve put some data
into a tuple then that data cannot be changed. The technical term for this is that
tuples are immutable.
• So for example, I could create a tuple of two elements like this:
myTuple = (‘Star Wars’, 1978)
• To access the elements we could use code such as:
print(‘The film’, myTuple[0], ‘was originally released in’, myTuple[1])
• If we try to modify a tuple’s value we get an access violation:
myTuple[1] = 2078
Traceback (most recent call last):
File “”, line 1, in
myTuple[1] = 2078
TypeError: ‘tuple’ object does not support item assignment
76
Tuples (Cont’d)
• This immutable property of tuples extends a little further than not being able to
modify the data in a tuple, for example:
• You can’t add elements to a tuple. Tuples have no append or extend
methods.
• You can’t remove elements from a tuple. Tuples have no remove or pop
methods.
• We can find elements in a tuple, since this doesn’t change the tuple, and we
can also use the in operator to check if an element exists in the tuple (because
again, the tuple is not modified).
• So why would we want tuples at all? The reason is that it allows us to create a
kind of read-only data structure, that once set cannot be modified (not on
purpose, not by accident, not maliciously by a third-party).
77
Loop Types
• When we use loops in modern programming languages, there are only three
different types of loops that we can use:
• We can use a for loop, or
• We can use a while loop, or
• We can use a do-while loop equivalent (there is no exact do-while loop in
Python – but we can create something that works the same way).
• Those are our only three options (we don’t use GOTO statements anymore –
it’s not considered good practice in modern programming)
• The type of loop that we decide to use (for, while or do-while) depends on two
important factors that we have to ask ourselves:
- Do we know exactly how many times the loop should execute (yes/no),
and - Do we always want the loop to execute at least once? (yes/no)
Note: We’ll come back to these two questions shortly – first, let’s take a look at each type of loop in action!
78
“For” Loops in Python
• The syntax for writing a for loop in Python is:
for [VARIABLE-NAME] in [SOME-KIND-OF-SET]:
[DO-SOMETHING]
• Let’s try it out by using a loop to print out the values from 1 to 10:
for loop in range(1, 11):
print(loop)
• This will print out:
1
2
…
9
10
When to use “for” loops:
We use “for” loops when we
know exactly how many times
we want the loop to execute
before it even begins.
79
“For” Loops in Python (Cont’d)
• The set of data that we “loop through” (the correct term for this is: iterate)
doesn’t have to be just numbers though – we can iterate through any kind of set!
• Let’s write a short loop that prints out all the names of the Beatles band
members:
beatles = [“John”, “Paul”, “George”, “Ringo”]
for loop in beatles:
print( “0 was in the Beatles!”.format(loop) )
• This will print out:
John was in the Beatles!
Paul was in the Beatles!
George was in the Beatles!
Ringo was in the Beatles!
80
“While” Loops in Python
• A while loop continues to run while a certain condition is true, for example:
counter = 1
while (counter <= 5):
print(“value of counter is: “.format(counter) )
counter += 1
• Which will produce the following output:
value of counter is 1
value of counter is 2
value of counter is 3
value of counter is 4
value of counter is 5
Quiz: What would happen if we forgot to put the counter += 1 line inside our while loop?
When to use “while” loops:
We use “while” loops when we
want to continue looping while a
condition is true, and we might not
know how many times it’ll run.
If the condition is never true, then
the loop may never run at all!
81
“While” Loops in Python (Cont’d)
• Another example of a while loop might be to keep looping until the user
provides some input which causes us to terminate the loop, for example:
arrived = False
while (arrived == False):
reply = input(“Are we there yet? (y/n)”)
if (reply == “y”):
arrived = True
print(“Finally! Phew!”)
• This loop will only end when we finally provide “y” as our reply, which sets our
arrived variable to True!
• As the loop is created to run only “while (arrived == false)” – when this is no
longer the case, the loop no longer runs and we print out our “Finally! Phew!”
message.
Note: The specific value used to stop a while loop from executing is called a sentinel.
82
“While” Loops in Python (Cont’d)
• What will happen when we run the code below?
arrived = True
while (arrived == False):
reply = input(“Are we there yet? (y/n)”)
if (reply == “y”):
arrived = True
print(“Finally! Phew!”)
• This time, the loop will never execute because the initial condition of arrived
being False is never met!
• So in this case, we’d skip the loop entirely, and go straight to the “Finally!”
message.
Initial value changed
from False to True
83
“Do-While” Loops in Python
• Sometimes, we want a loop to always execute at least once – and in most
languages, we’d use what’s called a do-while loop for this – but in Python,
there is no such thing, so we have to make our own!
• Luckily for us, it’s actually very easy to do:
counter = 1
while True:
if (counter <= 5):
print( “Value of counter is: 0”.format(counter) )
counter += 1
else:
break
• In the above loop, when counter is greater than 5 the else condition runs, which
calls the break statement – and the break statement breaks us out of the loop
so we don’t get stuck in an infinite loop!
84
“Do-While” Loops in Python
• The same do-while loop:
counter = 1
while True:
if (counter <= 5):
print( “Value of counter is: 0”.format(counter) )
counter += 1
else:
break
When to use “do-while” loops:
We use “do-while” loops when we want to
continue looping while a condition is true,
and we might not know how many times it’ll
run – BUT – we always want the loop
‘body’ to execute at least once.
85
Multiplying Strings (Cont’d)
• By multiplying strings we can also do things like this:
print(“All work and no play makes Jack a dull boy.n” * 99)
• Or maybe:
print(“Excited: ” + (“!” * 1) ) # !
print(“Really excited: ” + (“!” * 3) ) # !!!
print(“Really, really excited: ” + (“!” * 6) ) # !!!!!!
NNeewwlliinnee cchhaarraacctteerr
86
Substrings
• When working with strings, we can extract part of a string (which is called a
substring), like this:
letters = “ABCD”
print(letters[0]) # A
print(letters[1]) # B
print(letters[2]) # C
print(letters[0:2]) # AB
print(letters[1:-1]) # BC (-1 is the last element)
• When we use this [start:end] notation, what we’re really saying is:
• Start and include the first character we specify as the start of our range,
• But exclude the last character that we specified as the end of our range.
• Just like the range statement: range(0, 3) gives use the set of data [0,1,2],
when extracting strings using [start:end], we include the start of the range, but
exclude the last element of the range.
You could also
do this one as:
letters[1:3]
87
Substrings (Cont’d)
• To print a string, we know we can use Python code like this.
phrase = “Knowledge is power.”
print(phrase)
• But what if we only wanted to print out the first 9 characters? In this case, we
can print out the word Knowledge (which is 9 characters) by specifying a range
that goes from character 0 to character 9 like this:
phrase = “Knowledge is power.”
print(phrase[0:9]) # Knowledge
• Why do we get 9 characters when we specified the range 0 to 9 (which is 10
characters?) Because K is the 0th character, and we get the range:
[start-location-inclusive : end-location-exclusive]
88
Substrings (Cont’d)
• So in our example we said:
Start at character 0, keep going until, but do
not include, character 9
print( phrase[0:9] )
• But if we omit (which just means do not include) a value either side of the colon
in [start : end] then Python takes that as:
• [:9] means “Go from the start up to but not including the 10th character”,
and
• [9:] means “Go from the 10th character to the end of the string”.
• Let’s take a look at it in action…
89
Finding Substrings
• If we want to find a substring within a string in Python, we can use the find
function, which works like this:
quote = “Eat when hungry, sleep when tired.”
first = quote.find(“when”)
print( “‘when’ starts at location: 0”.format(first) )
• Which will display:
‘when’ starts at location: 4
• The find function will return one of two integer values:
• If the substring exists in the string it will return the character number of the
first occurrence of the substring, or
• If the substring does not exist in the string, it will return the value -1.
Because the first
character is at index 0,
not at index 1!
90
Determining If A String Is Purely Alphabetical or Numerical
• Sometimes we may want to check if something is a number or a letter – and
again, Python comes to the rescue with the isalpha() and isdigit() functions.
• Let’s give it a shot:
s = “123456”
print( s.isdigit() ) # True – only digits in string
s = “12Three456”
print( s.isdigit() ) # False – not purely digits
s = “ElvisPresley”
print( s.isalpha() ) # True – all chars alphabetical
s = “Elvis Presley”
print( s.isalpha() ) # False – space ‘ ‘ is not a letter!
91
Working with Files in Python
• Like any good language, Python allows us to work with files, but also like any
good language, we need to know what we want to do with the files before we
open them. The options we have available are:
- To open a file for reading only – which is mode r,
- To open or create a file for writing only – which is mode w,
- To open a file for appending only – which is mode a, and
- To open a file for reading and writing, which is mode r+.
• The difference between options 2 and 3 above is that if a file exists and has
some data in it already:
• If we open it for writing, any existing file contents will be discarded, and
• If we open it for appending, any new data we write can be added to the
end of the existing data in the file.
92
Opening a File in Python
• Before we can read from a file, we have to open the file, like this:
file = open(“Names.txt”, “r”)
or
file = open(“Names.txt”, “w”)
or
file = open(“Names.txt”, “a”)
or
file = open(“Names.txt”, “r+”)
OOppeenn NNaameess..ttxxtt ffoorr rreeaaddiinngg..
OOppeenn NNaameess..ttxxtt ffoorr wwrriittiinngg..
OOppeenn NNaameess..ttxxtt ffoorr aappppeennddiinngg..
Open Names.txt for reading AND
writing.
93
Reading Lines from a File
• We can open a file for reading, read a line from the file and print it like this:
file = open(“Quotes.txt”, “r”)
first = file.readline()
print(first)
• Once we’ve read the first line of a file, each subsequent call to readline will
read the next line of the file, so to get the second and third lines of the file we
could write:
second = file.readline()
print(second)
third = file.readline()
print(third)
file.close()
The Quotes.txt file must
be in the same directory
as your Python script for
this to work!
The close function is
explained in detail on the
next slide!
94
Reading Lines from a File (Cont’d)
• When we’ve finished working with a file, we should always close the file for two
important reasons: - When we close a file, we free up any resources like RAM and buffers that
Python allocated itself in order to work with the file, and - If we’ve opened a file and modified it, the changes only get written to the
file when the file is closed! So if we create a new file or modify an existing
file and forget to close it – the changes won’t “stick”!
• Another important thing happens when we close a file, and that’s that the file
pointer (which is just a piece of memory which stores where we are in the file
gets reset back to zero).
95
Counting Elements in a List
• When we have a list of data in Python, we can find out how many elements are
in the list by using the len function (short for length), for example:
beatles = [“John”, “Paul”, “George”, “Ringo”]
size = len(beatles)
print(size) # Prints 4. Elements are at indices 0, 1, 2 & 3
• Although we can loop through all the elements in a set using…
for loop in beatles:
print(loop)
• …sometimes it’s good to know how many elements we’re working with, so after
running the code at the top of the slide, another way to print each element in
turn could be by using code like the below:
for loop in range(0, len(beatles)):
print(beatles[loop])
Note: If we’d already calculated the size variable as size = len(beatles) then we could use range(0, size)
96
What is a function?
• A function is just a named “block of code”, that we can execute by calling it by
name!
• Functions are defined in Python by using the def keyword, like this:
def sayHello():
print(“Hello!”)
• In the above example, our function is called sayHello(), it doesn’t take any
parameters (which we’ll discuss very shortly), and the entire function is just a
single line of code which prints Hello! to the screen.
• To execute the above function (i.e. make it run), we can simply call the function
by name, like this:
sayHello()
97
Functions and Parameters (Cont’d)
• We can use parameters / arguments like this:
def sayHello(name):
print(“Hello, !”.format(name) )
• And we can execute the function like this:
sayHello(“Bob”)
• What’s happening is: The data that we provide when we call the function (which is
called an actual parameter or argument) gets passed to the function.
• When this happens, that data gets given its own name for use inside the function
(called a formal parameter).
• So inside the sayHello function, the variable called name (formal parameter)
stores whatever information we passed to the function when we called it (actual
parameter or argument) – which in this case is just the string data “Bob”.
98
Using Multiple Parameters
• We’ve seen that we can create a functions that take no parameters, and a
single parameter as input to work with – but we can also write functions that
take multiple parameters just as easily:
def printSum(firstNum, secondNum):
sum = firstNum + secondNum
print( “The sum of the numbers is 0”.format(sum) )
• We could then use the above function like this:
printSum(5, 3)
• Which will display:
The sum of the numbers is 8
99
Using Multiple Parameters (Cont’d)
• When using our printSum function, we could call it like this:
printSum(5, 3)
printSum(3, 5)
• Both of the above calls will produce the exact same output, because it doesn’t
matter if we add 5 plus 3, or if we add 3 plus 5 – either way the answer is
always 8!
• In the first case:
firstNum will be 5, and secondNum will be 3.
• While in the second case:
firstNum will be 3, and secondNum will be 5.
• No problems so far…
100
Using Multiple Parameters (Cont’d)
This won’t work because our printSum function takes
two parameters and we aren’t giving it any parameters!
printSum()
This won’t work because our printSum function takes two
parameters and we’re only giving it one parameter!
printSum(5)
This WILL work because our printSum function takes two
parameters, and we’re giving it two parameters! Hurrah!
printSum(5, 3)
This won’t work because our printSum function takes two
parameters and now we’re giving it three parameters! That’s
too many parameters!
[Button id=”1″]
[ad_2]
Source link
"96% of our customers have reported a 90% and above score. You might want to place an order with us."
