Python For Computer Science

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 117

The Python

Workbook
Python
Get Started 6
Download and install python..................................................................................................................6
Download Visual Studio Code and the Python extensions..................................................................... 6
Alternative IDE........................................................................................................................................ 7
But before we start… 7
What is Python?......................................................................................................................................7
How does this course work?...................................................................................................................7
Terminology:........................................................................................................................................... 8
Python Conventions. 9
Hello, Hello again! 10
Purpose:................................................................................................................................................10
Learning Activity:.................................................................................................................................. 10
Next Step: Do it yourself 11
Another Variation (calling a subroutine)...............................................................................................11
Terminology:......................................................................................................................................... 12
Collect information from the user:....................................................................................................... 13
Modifying the user input...................................................................................................................... 13
Escape Charactors.................................................................................................................................13
Another One?................................................................................................................................... 14
Add a parameter and sing................................................................................................................ 15
UX and UI- Thinking about your product.............................................................................................. 16
Variables and Errors 17
Resources:.............................................................................................................................................17
Purpose:................................................................................................................................................17
Learning Activity:.................................................................................................................................. 17
Naming Conventions in Python............................................................................................................ 17
Structure of a program......................................................................................................................... 17
Make the Speed Calculator...................................................................................................................17
Speed Calculator................................................................................................................................... 18
Some basic maths................................................................................................................................. 19
Some More math..................................................................................................................................20
Maximum and Minimum..................................................................................................................20
Power function................................................................................................................................. 20
Math module Square root................................................................................................................ 20
Round up and down with floor and ceil methods............................................................................. 20
factorial............................................................................................................................................ 20
Comparing Values – Using more operators.......................................................................................... 21
Try this script.................................................................................................................................... 21
Order of operations.............................................................................................................................. 22
Okay, Let’s try a circle and import.................................................................................................... 22
Extension:............................................................................................................................................. 23
Solution:................................................................................................................................................23
Learning Activity – Circumference of a circle........................................................................................23
The math Module............................................................................................................................. 25
Terminology:......................................................................................................................................... 26
Python 3 Reserved words:.................................................................................................................... 26
Data Types: 27
Resources:.............................................................................................................................................27
Purpose:................................................................................................................................................27
What are the data types in python?..................................................................................................... 27
Learning Activity: Char program........................................................................................................... 28
Output.............................................................................................................................................. 28
Learning Activity: Data type program................................................................................................... 28
Terminology:......................................................................................................................................... 29
Selection - Conditional Statements – If, then, else 30
Resources:.............................................................................................................................................30
Purpose:................................................................................................................................................30
Learning Activity – Counting and triangles – For Loop......................................................................... 31
Factorial n!....................................................................................................................................... 31
Learning Activity Another simple if elif and Else.................................................................................32
Learning Activity – isalpha and isnumeric............................................................................................ 32
Learning Activity - While and If............................................................................................................33
Learning Activity: pick two numbers.................................................................................................... 34
Another one..........................................................................................................................................34
Fibonacci Sequence – to how many?................................................................................................ 35
Learning Activity – calculate your Tax...................................................................................................36
For and Range functions....................................................................................................................... 38
Game time: Guess that number........................................................................................................... 39
Objective:..........................................................................................................................................39
Hint: Generate random numbers......................................................................................................40
Learning activity: Using true and False in conditional statements....................................................... 40
Objective...........................................................................................................................................40
Terminology:......................................................................................................................................... 41
Boolean Operators – and, or, not 42
Resources:.............................................................................................................................................42
Purpose:................................................................................................................................................42
Truth Tables.......................................................................................................................................... 43
Order of Operations..............................................................................................................................43
Learning Activity:.................................................................................................................................. 44
Learning Activities – Boolean And........................................................................................................ 45
Learning Activities – Boolean Or...........................................................................................................45
Learning Activity – Boolean Not & And................................................................................................ 45
Learning Activity - Boolean – Using Or................................................................................................. 45
Summary program: making a meal out of operators.......................................................................46
Terminology:......................................................................................................................................... 46
Lists or Arrays 48
Resources:.............................................................................................................................................48
Purpose:................................................................................................................................................48
Learning Activity: - Array one!.............................................................................................................. 49
The second and third Dimension.......................................................................................................... 50
Learning Activity – Multi Dimensional Array........................................................................................ 50
Learning Activity – Multi Dimensional Array 2 – Cylinder Volume....................................................... 52
Iteration one.....................................................................................................................................52
Iteration two.....................................................................................................................................52
Manipulating the array......................................................................................................................... 54
Learning Activity – manipulate the data...............................................................................................54
Learning activity: Another look at methods for arrays......................................................................... 56
Learning Activity: Lists and if Else......................................................................................................... 58
Learning Activity: Tuples and Sets........................................................................................................ 59
Learning Activity – What is in that Pizza?............................................................................................. 60
Learning Activity – Manipulating data in an array – Batting scores in cricket.......................................61
Learning activity Recursion – Count down time................................................................................... 61
Learning Extension – modify the countdown....................................................................................... 63
Learning activity – Simple recursion – calculating the sum of a list of numbers.................................. 63
The three laws of recursion.................................................................................................................. 63
Game Time: Paper, Rock, Scissors.........................................................................................................64
Objective:..........................................................................................................................................64
Hints:................................................................................................................................................ 64
Extension: - Tabulate that array!...........................................................................................................65
Attributes..........................................................................................................................................65
Terminology:......................................................................................................................................... 66
Going Gui 67
Purpose:................................................................................................................................................67
UI - Considering the User Interface...................................................................................................... 67
Jakob Nielsen’s Heuristic Evaluation.................................................................................................67
Learning Activity: My First Window......................................................................................................68
.GRID..................................................................................................................................................... 69
Learning Activity – Colours and frames................................................................................................ 69
Learning Activity – Side by Side CLI and GUI.........................................................................................70
Learning Activity: Prime Numbers........................................................................................................ 72
Prime Number - Text Based Solution............................................................................................... 73
Prime Number - GUI Based Solution................................................................................................73
Learning Activity – message boxes....................................................................................................... 74
Learning activity – messagebox with list box........................................................................................76
Text Boxes and Entry Boxes...................................................................................................................77
Learning activity Text and Entry boxes..................................................................................................77
Checkboxes and radio buttons..............................................................................................................78
Learning activity Radio Buttons............................................................................................................ 78
Learning activity – Check boxes............................................................................................................ 79
Adding images...................................................................................................................................... 80
Learning activity: Combining different elements in GUI & quit button................................................ 81
Creating a tabs...................................................................................................................................... 83
Terminology:......................................................................................................................................... 84
Local and Global Variables 85
Resources:.............................................................................................................................................85
Purpose:................................................................................................................................................85
Learning Activity: A Simple Calculator in a GUI.................................................................................... 85
Extension – add in the quit button....................................................................................................87
Sort and Search 88
Purpose:................................................................................................................................................88
Learning Activity:.................................................................................................................................. 88
Selection Sort....................................................................................................................................88
Quick Sort......................................................................................................................................... 90
Insertion sort.................................................................................................................................... 91
Bubble Sort....................................................................................................................................... 93
Merge Sort........................................................................................................................................93
Linier Search or Sequential Search....................................................................................................95
Binary Search....................................................................................................................................96
Read and write to files 97
Purpose:................................................................................................................................................97
Learning Activity:.................................................................................................................................. 97
Modes...............................................................................................................................................97
Read file............................................................................................................................................97
Write to file.......................................................................................................................................98
Add data to the file...........................................................................................................................99
Creating a new file............................................................................................................................99
What dates is it? 101
Purpose:..............................................................................................................................................101
Learning Activity:................................................................................................................................ 101
Date & time now!........................................................................................................................... 101
Bringing it together Log file time........................................................................................................ 102
Extension matplotlib 103
Purpose:..............................................................................................................................................103
Learning Activity: Plot and array of points – line graph...................................................................... 103
Add a little style..............................................................................................................................104
Visualise your results.......................................................................................................................... 106
Plotting several datasets on one graph.......................................................................................... 107
Scatter plots........................................................................................................................................108
Plotting two or more datasets in the same scatter plot................................................................. 109
Bar Graphs – vertical and Horizontal.................................................................................................. 110
Vertical bar graph...........................................................................................................................110
Horizontal bar graph...................................................................................................................... 111
Pie Graphs...........................................................................................................................................112
Add a Legend..................................................................................................................................113
bbox_to_anchor............................................................................................................................. 114
Histogram........................................................................................................................................... 114
Get Started

Download and install python

The best place to get Python from is from http://www.python.org

Figure 1. Go to the Python website for access to the latest versions and updates of
python.

Click on Downloads and then select the operating system, download the 3.0+
software package for your operating system

Figure 2. Select the 3.+ python bundle for your operating system.

Install the software. This will install the interpreter for the Language and also IDLE

Download Visual Studio Code and the Python extensions


Visual Studio Code is a free multi-platform, open-source multi-language IDE. Once
the base framework is downloaded and install extensions to program in a range of
languages can be installed. These include Python, HTML, CSS
Download the application from -
https://code.visualstudio.com/

Then once the application is installed go to the visual


studio marketplace and search for the Python
Extension.

Alternative IDE
Go to the Wing IDE website http://wingware.com/
and download the latest version of the Wing IDE –
Wing 101 or Wing-personal.

But before we start…

What is Python?
Python is a high level programming language. It is
an interpreted language rather than a compiled language.
Python was developed in the 1980’ and 90’s and is derived from a number of other
languages including C and C++

Python is:
● Open sources and free
● Easy to learn and read
● High level
● Interactive
● Extensible, flexible and versatile

How does this course work?


The stages of development in this learning sequence will involve you using online
resources, trailing code in IDLE and developing your own programs using Visual
Studio Code, the computer science circles from the University of Waterloo. Then
follow up with a series of short tasks where you trial your code and extensions and
develop a library of software snippets.

Terminology:
Operating system: the software that supports a computer's basic functions, such
as scheduling tasks, executing applications, and controlling peripherals

Software Package: an assemblage of files and information about those files.

Language : A programming language is a formal constructed language designed


to communicate instructions to a machine, particularly a computer. Programming
languages can be used to create programs to control the behavior of a machine or
to express algorithms.
Interpreter: a program that can analyze and execute a program line by line.

Compiler : a computer program (or a set of programs) that transforms source


code written in a programming language (the source language) into another
computer language (the target language), with the latter often having a binary form
known as object code.

IDLE: Integrated DeveLopment Environment. This is the software application that


allows you to run the Python code in a terminal windows. It is an application with
the Python Bundle.

Integrated development environment (IDE) is a programming environment that


has been packaged as an application program, typically consisting of a code
editor, a compiler, a debugger, and a graphical user interface (GUI) builder.

High Level Language: A machine-independent programming language, such as


C, C++, Java, Perl and COBOL. It lets the programmer concentrate on the logic of
the problem to be solved rather than the intricacies of the machine architecture
such as is required with low-level assembly languages.

Low Level Language: a low-level programming language is a programming


language that provides little or no abstraction from a computer's instruction set
architecture—commands or functions in the language map closely to processor
instructions. Generally this refers to either machine code or assembly language.
Python Conventions.
Use lower_with_under for variables

For example

student_names

Use i as a counter variable name

i=i+1

Use white space around keywords, brackets, operators and commas

print(“This is your name” , + name )

Use double quotes for strings

print(“computational thinking”)

No brackets in If statements conditions

if a == True and b == True:


print(“both inputs are true”)
else:
print(“at least one input is false”)

Comments with a space at the start

print('Hello world \nThis is a test')


# This uses \n to add in a line break
Hello, Hello again!
Resources:
Visual studio Code - https://code.visualstudio.com/
Computer Science Circles - http://cscircles.cemc.uwaterloo.ca/
Python Wiki - https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
Python Software Foundation https://www.python.org/about/gettingstarted/
The python guru - http://thepythonguru.com/getting-started-with-python/
Python programming language - http://pythonprogramminglanguage.com/
Getting started with Python http://thepythonguru.com/getting-started-with-python/
Usability tsting for teens
https://www.usability.gov/get-involved/blog/2015/02/working-with-kids-and-teens.ht
ml

Purpose:
This first tutorial will start with printing text on the screen and developing an
understanding or syntax, errors and debugging.

Learning Activity:

Go to the Computer Science Circles site at the University of Waterloo


http://cscircles.cemc.uwaterloo.ca/ You will need to set up an account and the Guru
is your teacher. Then click on the link to 0: Hello!

Figure 3. Set up an account on the Circle site and then go to the first tutorial 0:Hello!
The focus of this tutorial is about writing your first program and learning some of the
basics of Syntax.
Read through the page and work through the three interactive boxes.
Next Step: Do it yourself
Now create a new project in Wing 101 IDE or use an editor to develop the first
program. Save this on your desktop or your documents in a folder called My python
examples.

Figure 4. Print - outputting information

print('Python is free - open source software')


print('Python is interpreted')
print('Python is high-level')
print('Python is extensible - allows the addition of low level modules to the interpreter
for customisation')

If you are using a text editor save the file with the file extension .py – for example
print.py

Run the program

Another Variation (calling a subroutine)


Build your text input and output program that you played with in IDLE in the
programming environment.

You will need to define the routines being used here.

def main():

print('Hello world')
print('This is a test')
# this code prints the two messages above. There are other ways of doing this more efficiently
print('Hello world \nThis is a test')
# This uses \n to add in a line break
main()

This also adds in a definition of a subroutine that is called and run – the subroutine is
called main.
Figure 5. Adding comments and printing

Terminology:
Comments: Comments are statements that are added to the code that are read
only, they are not executed. This is the way you can annotate the code to explain
your actions. In Python you can use the # symbol to add comments. When a
program is compiled the comments are removed.

Example:
Print(‘This text will be displayed on the screen when the program is executed’)
# this is a comment and it is ignored when the program is run in an interpreter or
removed when compiled
Collect information from the user:
Create the following program and add suitable comments explaining the structure
and purpose of the code:

print('Hi there, this script needs to collect some information about you')
user = input(“What is your name? : “)
print(“Welcome “, user)
lang = input(“What is your favourite language? :”)
print(user, ", ",lang, “is”, “fun”, sep =' ** ', end = "!\n")

What does sep do?

Modifying the user input.

We can alter the appearance of the input by using the following methods:

.lower() - this transforms all of the input into lower case


.upper() – this transforms all of the inputs into upper case
.strip() – this removes trailing and leading whitespace

# Enter the users name


name=input("Please enter your full name ")
# print message with name in upper case
print("welcome, " , name.upper())
#print message in lower case and remove the trailing and leading whitespace
print("welcome," , name.lower().strip())

Figure 6. the output from .upper() .lower() and .strip() Note the leading whitespace

Escape Charactors

Escape charactors are used to help to format the text and include charactors that
may be used for a programming purposes.

#This script looks at escape charactors in python. - these are useful for some
formating of the script

print('Escape characters all start with the backslash key ( \ ) combined with
another character within a string to format the given string a certain way.')
print('\n New Line - this uses the backslash and letter n for \\n')
print("This string\nspans multiple\nlines.")

print('\n Tab - this uses the backslash and the letter t for \\t')
print('\tThis line is tabbed in')
print('To include charactors like \' or \" or \\ you need to include the backslash
and then the charactor you wanted in the text')

Try this script out

Another One?

Try this:
■ def main():
print("Happy birthday to you!" )
print("Happy birthday to you!" )
print("Happy birthday, dear Fred...")
print("Happy birthday to you!")

Then execute the function main(). It should give you this:


>>> main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred...
Happy birthday to you!

There is some duplicated code in this short program.

print("Happy birthday to you!" )

So we can make it more efficient by defining another function. This one is called
happy

def happy():
print("Happy birthday to you!")

So now we can rewrite the program

def happy():
print("Happy birthday to you!")

■ def singFred():
happy()
happy()
print("Happy birthday, dear Fred...")
happy()

and when we run this it should look like this

■ >>> singFred()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred...
Happy birthday to you!
What more functions? Lets add in another function called singlucy().
■ def singLucy():
happy()
happy()
print("Happy birthday, dear Lucy...")
happy()

Now Modify the Main() function.

■ def main():
singFred()
print()
singLucy()

Which gives us….


■ >>> main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred..
Happy birthday to you!

Happy birthday to you!


Happy birthday to you!
Happy birthday, dear Lucy...
Happy birthday to you!

Add a parameter and sing
Lets Extend it a little more. This time lets add a Parameter into the function. A
parameter is a variable that is initialized when the function is called.

def happy():
print("Happy birthday to you!")

def sing(person):
happy()
happy()
print("Happy birthday, dear", person + ".“)
happy()

Our Output should look like this

>>> sing("Fred")
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred.
Happy birthday to you!
UX and UI- Thinking about your product
Whether we are building a website, or coding a program, the experience of the user
is a critical factor we must consider.

There are many models that can be examined, but two that we look at are Peter
Morville’s User Experience Honeycomb which looks at the users experience in
interacting with the object and Jacob Nielsen’s Heuristic Evaluation which examines
the usability of an interface

User experience (UX) focuses on having a deep understanding of users, what they
need, what they value, their abilities, and also their limitations. It also takes into
account the business goals and objectives of the group managing the project. UX
best practices promote improving the quality of the user’s interaction with and
perceptions of your product and any related services.

http://semanticstudios.com/user_experience_design/

The User experience considers seven different factors that influence the overall user
experience. As a developer you need to ask yourself about each of the factors. This
should be done in the planning stage, in peer testing iterations and in the evaluation
of finished product. Consider the feedback as you work through.

When you start your peer testing read this article to help you design and refine your
testing. -
https://www.usability.gov/get-involved/blog/2015/02/working-with-kids-and-teens.html

UI or User Interface will be examine in more detail as we start to investigate


Developing GUI’s or Graphical User Interfaces
Variables and Errors

Resources:
Tutorial on Variables http://cscircles.cemc.uwaterloo.ca/1-variables/
Extension Tutorial on errors http://cscircles.cemc.uwaterloo.ca/1e-errors/
Text input and output -
http://pythonprogramminglanguage.com/text-input-and-output/
Python guru – datatypes and variables -
http://thepythonguru.com/datatype-varibles/

Purpose:
To learn about variables and errors.
To develop an understanding of the structure of programs

Learning Activity:

Work through the Tutorial on Variables and Errors on the CIRCLE website. Once you
have completed the interactive elements on the site, try the code snippets on your
machine in IDLE.

Naming Conventions in Python

Use lower_with_under for variables

For example

student_names

Structure of a program

def hello():
print(“Hello”)
print(“Computers are fun”)

The first line of the code above defines a Function called hello. def hello(): We use
functions to organise the structure of a program and to allow us to run or execute
several statements together.

Are statements are the commands we want the the computer to execute in this case
the statement is print(‘Hello’). The command has a parameter which is the bit in the
brackets.

Make the Speed Calculator


Now open your IDE or editor (Wing 101) – its time to add another program to your
library of tools.
Take the code you have unscrambled in Speed Calculator in the Circles Tutorial and
build the program for this.

Think carefully about what you are going to call your:


Function
Variables
and add in suitable comments.

Run and debug your program

Speed Calculator

Figure 7. Speed Calculator program


def speed():
downhillDistance = 4
print('Downhill Distance =\t', downhillDistance)
downhillTime = 72
print('Downhill Time =\t', downhillTime)

uphillDistance = 4
print('Uphill Distance =\t', uphillDistance)
uphillTime = 72
print('Uphill Time =\t', uphillTime)

Distance = downhillDistance + uphillDistance


print('Total distance =\t', Distance)
Time = downhillTime + uphillTime
print('Total Time =\t', Time)

Speed = Distance/Time
Speed = float(Speed)
print('Speed = Distance/Time')
print(Speed,'=',Distance,' / ', Time)

speed()

Some basic maths

Process Operator Purpose


Addition + A+B
Subtraction - A–B
Multiplication * A*B
Division / A/B
For example
5 / 2 is 2.5
Floor division // A // B
This truncates the result to a decimal and removes
the decimal points
For example
5 // 2 is 2
Modulus % A%B
This displays the remainder after dividing the
variables
For example
10 % 7 is 3
Exponent ** A ** B

Try out this program to apply the basic math functions

#sets variables.
a=9
b = 14
c=3
d=6

#prints variables.

print('a=',a, 'b=',b, 'c=',c, 'd=', d)


print('Addition - operator is + ')
print('example:\t' 'a + b = ', a + b)
print('Subtraction - operator is - ')
print('example:\t' ' b - c = ', b - c)
print('Multiplication - operator is * ')
print('example:\t' ' c * d = ', c * d)
print('Division - operator is /')
print('example:\t' ' b / c = ', b / c)
print('Floor Division (truncates to decimal - removing any decimal point) -
operator is //')
print('example:\t' ' b // c = ', b // c)
print('Modulus (displays the remainder after dividing the values) - operator is
% ')
print('example:\t' ' b % c = ', b % c)
print('Exponent - operator is ** ')
print('example:\t' ' c ** d = ', c ** d)

Some More math.

Maximum and Minimum


The max() and min() provide the highest and lowest valuable from a selection

#max and min math functions


a = min(6,7,8,9,1,23,45,67)
b = max(6,7,8,9,1,23,45,67)
print ("minimium is ", a)
print ("maximium is ", b)

Power function
Using pow(x, Y) returns x to the power of y or Xy

#power x to the power of y


c = pow(4,6)
print ("4 to the power of 6 = ", c)

Math module Square root.


Using the math module (you need to import it) allows a range of functions including
square root.

#Square root
import math
d = math.sqrt(64)
print("the square root of 64 is ", d )

Round up and down with floor and ceil methods


Rounding up and down using the floor and ceil functions in the math module.
#round up and down
import math
e = math.ceil(2.3)
f = math.floor(2.3)
print("The ceil of 2.3 - rounded up- is: ", e)
print("The floor of 2.3 - rounded down- is: ", f)

factorial
A factorial multiplys all the whole numbers from the chosen number down to one
4! = 4 x 3 x 2 x 1
#factorial
import math
print("The factorial of 4 or 4! is ",math.factorial(4))
print("The factorial of 9 or 9! is ",math.factorial(9))
Comparing Values – Using more operators

There are more operators that we can use. These include:


Equality ==
Inequality !=
Greater than and less than > and >=
Greater than or equal to or less than or equal to < and <=

Try this script

#using operators to compare values

#assign values to variables


nil = 0
num = 0
max = 1
cap = 'A'
lower = 'a'
#state values
print('The values of the variables are\n' 'nil=',
nil,'\nnum=',num,'\nmax=',max,'\ncap=',cap,'\nlower=',lower)

#script
print('\nEquality operator is == this compares two values to see if they are the
same and returns either a true or false \n')
print('Equality == :\t\t\t', nil, '==', num, nil==num)
print('Equality == :\t\t\t', nil, '==', max, nil==max)
print('Equality == :\t\t\t', cap, '==', lower, cap==lower, '\n')

print('\ninEquality operator is != this compares two values to see if they are


the different and returns either a true or false \n')
print('Inequality != :\t\t', nil, '!=', num, nil!=num)
print('Inequality != :\t\t', nil, '!=', max, nil!=max)
print('Inequality != :\t\t', cap, '!=', lower, cap!=lower, '\n')

print('\nGreater than and less than operator are > and < this returns either a
true or false depending on the value and operator \n')
print('Greater than > :\t\t', nil, '>', max, nil>max)
print('Greater than > :\t\t', max, '>', nil, max>nil)
print('Less than < :\t\t\t', nil, '<', max, nil<max )
print('Less than < :\t\t\t', max, '<', nil, max<nil ,'\n')

print('\nGreater than or equal to and less than or equal to operator are >= and
<= this returns either a true or false depending on the value and operator \n')
print('Greater than > :\t\t', nil, '>=', num, nil>=num)
print('Greater than > :\t\t', max, '>=', nil, max>=nil)
print('Greater than > :\t\t', nil, '>=', max, nil>=max)
print('Less than < :\t\t\t', nil, '<=', max, nil<=max )
print('Less than < :\t\t\t', nil, '<=', num, nil<=num )
print('Less than < :\t\t\t', max, '<=', nil, max<=nil ,'\n')
Order of operations

The order in which we do our math functions is pretty significant. The results can be
a little different depending on what gets done first. Examine this script.

#order of operations is important in Math functions. The answer you get can
be completely different depending on the order of operations.

#Here are the variables for this script

a=5
b=7
c=2
d=9
e = 17
f = 12

#print the variables


print('a=', a, '\nb=', b, '\nc=', c, '\nd=', d, '\ne=', e, '\nf=', f )

#Calculation and formula


print('\nHere is the first formula using all six variables\n')
print('g = a + b - c * d / e % f')
g=a+b-c*d/e%f
print(g, '\n')
print('\nHere is the second formula this time with the order of operation
changed\n')
print('h = a + (b - c ) * d / e % f')
h = a + (b - c ) * d / e % f
print(h, '\n')
print('\nAnd finally this formula\n')
print('i = a + b - c * d / (e % f)')
i = a + b - c * d / (e % f)
print(i)

Okay, Let’s try a circle and import

This is a simple program that will calculate the area of a circle.

Import is a keyword used to import modules into the program. In this case

import math

will bring in the Math module. Using the keywords from allows specific elements to
be imported. For example

from math import cos

Which imports the cos() function


How could you alter this so you could enter the radius directly rather than adding it
into the print area statement?

import math

def area_of_circle(r):
a = r**2 * math.pi
return a

print (area_of_circle(1))

Extension:

import math

r = float(input(“Enter your radius”))

def area_of_circle(r):
a = r**2 * math.pi
return a

print (area_of_circle(r))

Solution:

import math

def calcCircle():
radius = float(input("Enter the radius of your circle in mm : "))

circleRadius = (math.pi * radius * radius)


print("The area of the circle is " +format(circleRadius)+" mm")

calcCircle()

Learning Activity – Circumference of a circle

The formula for the circumference of a circle is

Write and test a program that calculates the circumference of a circle where you
enter the value of the radius. Make sure you add suitable comments.
The math Module
The math module has the following mathematical functions (and many many more)
math.factorial(x)
Return x factorial. Raises ValueError if x is not integral or is negative.
math.exp(x)
Return e**x.
math.log(x[, base])
With one argument, return the natural logarithm of x (to base e).
math.log10(x)
Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
math.pow(x, y)
Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far
as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a
zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y)
is undefined, and raises ValueError.
Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use
** or the built-in pow() function for computing exact integer powers.
math.sqrt(x)
Return the square root of x.
math.cos(x)
Return the cosine of x radians.
math.hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the
origin to point (x, y).
math.sin(x)
Return the sine of x radians.
math.tan(x)
Return the tangent of x radians.
math.pi
The mathematical constant π = 3.141592…, to available precision.

Do you want more math functions? Go to


https://docs.python.org/3/library/math.html#module-math for the complete list

Terminology:
Function: Functions are reusable snippets or sections of code that allow us to
organise the structure of our program and reuse the function as often as we
require. Functions start with a def keyword.

Variable: A variable is a way of storing data to be used in a program. Variables


have been given names or identifiers. Identifiers where possible should be
descriptive. Some words can not be used as identifiers for variables - these are
called reserved words
Global variables: Variables that are not bound to any function, but can be
accessed inside as well as outside the function are called global variables.
Local variables: Variables which are declared inside a function are called local
variables.
Statement: A statement is a command that you wish python to execute

Parameter: This is the element that is being manipulated and is between the
brackets in the python statement i.e. print(‘hello’). The text ‘hello’ is the parameter.
Parameters do not always have to in be in speech marks

Syntax Error: This is an error in the code where the interpreter can not
understand the code you have written. This could be a spelling mistake, wrong
capitalizations etc

Run-time error: A run-time error is where the syntax is correct but the structure of
the code is such that you can not run the instructions

Reserved words: Some identifiers are part of python itself and can not be used to
be the names of variables. Some reserved words are and, del, for, is, raise, assert,
elif, in, print etc

Python 3 Reserved words:


False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
pass else import assert
break except in raise
Data Types:

Resources:
Tutorial on types - http://cscircles.cemc.uwaterloo.ca/4-types/
TutorialPoint – Python Variable types -
https://www.tutorialspoint.com/python/python_variable_types.htm

Purpose:
There are a range of data types that are used in programming. While sometimes you
can question the significance of using an integer or a float when defining a variable
or a constant, there are important reasons for defining accurate the type of data we
are expecting.
What are the data types in python?

A constant is an identifier with an associated value which cannot be altered by the


program during normal execution – the value is constant.

A variable, which is an identifier with a value that can be changed during normal
execution – the value is variable.

Character (chr): This is a single character, like X, £, 4, or *. You don’t often create
single character variables, but they are at the core of the language so you need to
know what they are.

String (str): This is a “string” of characters of any length. In my previous example –


your name on web form – your name would be stored as a String variable

Integer (int): A whole number – whole meaning there are no digits after a decimal
point. So 65 would be a valid integer; 65.78 would not.

Floating-point number (float): A number that may have digits after the decimal
place. 65.00 is technically a floating point number, even though it could be
represented just as easily as an integer as 65. It takes more memory to store a float,
which is why there is a distinction instead of just creating a “number” datatype.

Boolean : A variable to represent true or false (or it could also mean 0 or 1, on or


off). The simplest datatype and commonly used.

Hex and Oct: Hex is the hexadecimal string and oct is the octal value of the string
Learning Activity: Char program

This is a simple program which used the add and assign operator += to add
characters or char to message.

newline = ""
greeting = "Welcome to Python"
for char in greeting:
newline += char
print (newline)

Output

Figure 8. Outputting charactors one at a time.

Write this program and add in comments explaining what is happening here
Learning Activity: Data type program

The following script looks at different data types and converts between them
#Heading
print('\t\tData Types\n\n')

#This is a program investigating data types


print('This program will convert values from one data type to another and use
the \"type\" function to identify the data type as either \"str\", \"int\", or \"float\"\n
')
print('\nThe Default datatype for python is String - alphanumeric charactors,
both numbers and letters\n')
#input the variables for the experiment
a = input('Enter a number (a):')
b = input('Enter a second number (b):')

#data type is string str


print('\nThe Default datatype for python is String - alphanumeric charactors,
both numbers and letters\n')
sum = a + b
print('\nData Type sum:', sum, type(sum))
print('The result of this is a concanated string - the two values are joined.')

#data type is an integer int


sum = int(a)+int(b)
print('\nData Type sum:', sum, type(sum))
print('The result of this the addition of two whole numbers. An integer is a
whole number.')

#data type is a float


sum = float(sum)
print('\nData Type sum:', sum, type(sum))
print('A float is a number including decimal points.')

#data type Charactor chr


sum = chr(int(sum))
print('\nData Type sum:', sum, type(sum))
print('chr converts an integer value into its charactor representation.')

#data type is a Charactor and integer


sum = ord(sum)
print('\nData Type sum:', sum, type(sum))
print('ord converts a charactor into the integer value.')

#data type is a Hexadecimal hex


hexa = hex(int(a))
hexb = hex(int(b))
print('\nData Type a value is:', a, 'As Hexadecimal it is', hexa)
print('\nData Type b value is:', b, 'As Hexadecimal it is', hexb)
print('Hexadecimal is the base 16 value of the variable.\n')

Terminology:
String: A number of charactors of any type
Character: A single charactor
Integer: A Whole number
Float:A decimal number
Boolean:True or false value
Octal: Octal value for a character based one 0,1,2,3,4,5,6,7
Hexadecimal: Hexadecimal value for a character based on
0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
Selection - Conditional Statements – If, then, else

Resources:
Computer Science Circles – If - http://cscircles.cemc.uwaterloo.ca/6-if/
Computer Science Circles – 6D - Design, Debugging and Donuts -
http://cscircles.cemc.uwaterloo.ca/6d-design/
TutorialPoint – Python Loops -
https://www.tutorialspoint.com/python/python_loops.htm
Edison Follow_torch program - http://edpyapp.com/
https://en.wikipedia.org/wiki/Fibonacci_number

Purpose:
To understand selection
To Understand the use of if, elif and else in conditional statements

If performs a basic conditional test that evaluates a given expression for a Boolean
value of either true or false.

The structure of the statement is important or errors are likely.


The tested expression must be followed by a :
The statements to be executed need to be indented.

For example

if tested-expression:
Statement to be run when the test is true
Statement to be run when the test is true
else:
Statement to be run when the test is false
Statement to be run when the test is true

Figure 10. Flow charts are a useful way of


representing a process

A third element can be added to develop a branching conditional statement. This is


elif

if tested-expression1:
Statement to be run when the expression1 is true
Statement to be run when the expression1 is true
elif
Statement to be run when the expression2 is true
Statement to be run when the expression2 is true
else:
Statement to be run when the expressions are false
Statement to be run when the expressions are false

Learning Activity – Counting and triangles – For Loop

for i in range(0, 20):


print('*' *i)

Your Product should look like this

Figure 11. factorial output.

Factorial n!

From Wikipedia…

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all
positive integers less than or equal to n. For example,

Examine the if, elif, else statement below and modify it to calculate factorials in the
range 1 to 10.

def factorial(n):
if n<0:
return None
elif n<2:
return n
else:
return n*factorial(n-1)

print factorial(5)
Learning Activity Another simple if elif and Else

# ---- Change this number ----


avg = 81
# ---- Change this number ----

if avg > 40 and avg <= 50:


print('pretty good average')
elif avg > 50:
print('pretty amazing average')
else:
print('you need more runs!')

Learning Activity – isalpha and isnumeric

This short script allows you to test if a string contains only alphabetical charactors.
This is a function called isalpha()
Similarly the function isnumeric() will return true if the string only contains numbers
and false if one or more charactors are not numeric.

#isalpha is a test of whether the text is alpha or contains other charactors

studentname = input("enter your name; ")

if studentname.isalpha() == False:
print("please enter your name")
else:
print("next statement or task on completing the test")

Then try this….

#isnumeric() returns true if only numbers are in the string and false is one or more
characters are not numeric

yourfavnum = input("what is your favourite whole number: ")

if yourfavnum.isnumeric() == True:
print(yourfavnum, " is a number")
else:
print(yourfavnum, " is a not number")
You can combine these two programs like this using a nested If Else statement

studentname = input("enter your name; ")

if studentname.isalpha() == False:
print("Incorrect Answer you were asked to enter you name not a number")
else:
print(studentname, "next statement or task on completing the test")
yourfavnum = input("what is your favourite whole number: ")

if yourfavnum.isnumeric() == True:
print(yourfavnum, " is a number")
else:
print(yourfavnum, " is a not number")

Learning Activity - While and If

This exercise uses a while loop, imports the date/time module and has an if
statement as well.

The purpose of the loop is to VALIDATE an entry which is entering a lower case y
and if this is entered it shows the current time. If a lower case n is entered it will exit
the program using the exit() function.

from datetime import datetime

now = datetime.now()
response = ""

while response !="y":


response = input("Do you want the current time? y/n ")
response.lower
if response=="n":
exit()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

Try this program out and consider the operators being used here != and ==
If you wanted to increase the options for example including a response like yes you
could add and response !=”yes”
And is a Boolean operator.
Learning Activity: pick two numbers

Try this out:

#This program investigates basic if -else statements


print('\t\t\tif-else statements\n')
#set variables
a = input('pick a number between one and nine:')
b = input('pick a second number between one and nine:')

#sets the values of a and b as integers


a= int(a)
b= int(b)

#scripts

print('The variables')
print('a =\t', a, 'b =\t', b)
print('\n\nThe script')
print('\nThis program has two parts and compares the variables and looks at which is
the maximum value\n')

print('Variable a is:', 'one' if (a == 1) else 'Not one\n')


print('Variable b is:', 'Even' if (b % 2 == 0) else 'odd\n')
print('Variable a has ', 'a different value from b' if (a !=b) else 'the same value as b')
#If the modulus of the number divided by 2 is 0 the variable is even

print('\nThis part of the program compares the first variable to the second and
caluculates which is larger and assigns this value to the variable max')

max = a if (a > b) else b

print('The larger variable is', 'a' if (max == a) else 'b')


print('\nGreater value is', max)

Another one

And now try this script.


This script is using if, elif and else for a branching if else statement.

#branching if else statements


print('\t\tBranching if else statements\n')

print('This program use if, elif and else statements to develop branching if
statements. \n\nIMPORTANT:\nIndenting the code is very important. The indents
identify the code blocks\n ')

#User input of a number as an integer


num = int(input('\nPlease enter a number:'))
if num > 5 :
print('Number exceeds five')
elif num < 5:
print('Number is less than five')
else :
print('Number is five')

#Alternative branching if else statements using and and or


print('\n\nAlternative branching if else statements using and and or')
if num > 0 and num < 4:
print('Number is 1, 2 or 3')
if num > 7 and num < 9:
print('Number is eight')
if num == 1 or num == 3:
print('Number is 1 or 3')

Fibonacci Sequence – to how many?

Fibonacci was a mathematician from the Republic of Pisa, in Italy. Born in 1170 he
was considered one of the greatest mathematicians of the Middle Ages.

The Fibonacci numbers are the numbers in the following integer sequence, called
the Fibonacci sequence, and characterized by the fact that every number after the
first two is the sum of the two preceding ones:

The sequence Fn of Fibonacci numbers is defined by the recurrence relation:

Usually F0 = 0 and F1 = 1

The first 21 Fibonacci numbers Fn for n = 0, 1, 2, …, 20 are:[18]


F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17 F18 F19 F20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Here are two variations of code used to generate the Fibonacci numbers. Use this
code to output the first 21 number in the sequence.

Version one (With thanks to Ashraf Thomson)

a=0
b=1
count = 0
n = int(input())
print (a)
count = count + 1
print (b)
count = count + 1
while n > count:
a=a+b
print(a)
count = count + 1
b=a+b
print(b)
count = count + 1

Check the numbers are accurate


Add comments to the code

Version two

def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a+b

f = fib()
for x in xrange(10):
print f.next(),

https://en.wikipedia.org/wiki/Fibonacci_number

Learning Activity – calculate your Tax

This program calculates the tax that is owed for a person earning a salary in New
Zealand.
● The first $14000 that the person earns is taxed at 10.5%,
● the next bracket upto $48,000 is taxed at 17.5% and then
● the next bracket upto $70000 is taxed at 30%.
● Any money earned above the first $70000 of earning is taxed at 33%

Income Bracket Tax on the income bracket


$0 - $14,000 10.5%
$14,001 to $48,000 17.5%
$48,001 to $70,000 30%
Over $70,000 33%

salary = int(input("Please enter your salary in NZ dollars: "))


tax = 0
if (salary > 70000):
tax = 14020 + (salary - 70000) * 0.33
elif (salary > 48000):
tax = 7420 + (salary - 48000) * 0.30
elif (salary > 14000):
tax = 1470 + (salary - 14000) * 0.175
elif (salary < 14001):
tax = (salary * 0.105)
print("Tax on salary of", salary, "is", tax)

The Inland Revenue Department has a tax calculator which will also do this
calculation -
http://www.ird.govt.nz/calculators/keyword/incometax/calculator-tax-rate.html

Write this program and then run a trace table which compares your results to those
of the IRD. Indicate if the data being used is boundary data or extreme data

Salary Your Calculations IRD Calculation Test data type


$14000
$13999
$23000
$71000
$101010
$10
$0
$2500000
$72134

In Australia the tax brackets are different from those used in New Zealand.
● The first $18200 earned is not taxed,
● the next bracket between $18201 and $37000 is taxed at 19%
● the next bracket between $37001 and $87000 is taxed at 32.5%
● the next bracket between $87000 and $180000 is taxed at 37%
● Any earnings beyond the first $180000 are taxed at 45%

Salary Tax rate for bracket


$0-$18200 0%
$18201-$37000 19%
$37001-$87000 32.5%
$87001-$180000 37%
>$180001 45%

Write a program for the Australian tax scheme and test the tax rate using this trace
table.
Salary Your Calculations
$14000
$13999
$23000
$71000
$101010
$10
$0
$2500000
$72134

For and Range functions


The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Below are two for statements that use a range to specify the outputs. The first uses
range(3, 20, 4) or Start at 3, stop before 20 in steps of 4.
The second starts at -5 stops before 6 in steps of one, and uses a conditional if Else
statement to identify the number.

Code Output
Game time: Guess that number

Objective:
Create a simple guessing game that randomly generates an whole number between
1 and 100. The player enters a guess and is told if the guess is too high, too low or
accurate. A count of attempts is kept.

A flowchart of the game might look like this.


Hint: Generate random numbers
Try this:

#random number generation


import random
# imports the random number module
number = random.randint(1,100)
#using the random method to generate a random integer
print("The random number is", number)

print(random.randint(1, 100))
#Random range(start value, stop value)

Learning activity: Using true and False in conditional statements

Objective
To use The true and false statements to change modify a conditional statement

True and False are reserved words in python and many other languages. A reserved
word is one where the meaning of the word is fixed and can not be changed by the
user.

Here is the example code that uses the True and False reserved words to change
the output of the if statement.

Try the code out and write and explanation in for the different statements. What does
it do

Code Explanation
def repeat(s, exclaim):
result = s + s + s
if exclaim:
result = result + '!!?!'
return result

def main():
print(repeat('Yehaa ', False))
print(repeat('Woo Hoo ', True))

main()

Terminology:
Subroutine: A section of code written outside of the main program. The cover term
for procedures and functions.
Selection: A decision within a computer program when the program decides to
move on based on the results of an event.

Nesting: Including one programming construct within another.

Looping: Repeatedly executing a section of code.

Iteration: The repetition of a block of statements within a computer program.

Condition controlled iteration: A loop that repeats until a condition is either met or
no longer met. This is usually implemented using a WHILE or REPEAT UNTIL
loop.

Count controlled iteration: A loop that repeats a set number of times, usually
implemented using a FOR loop. A loop counter is used to keep track of how many
times the loop has iterated.
Boolean Operators – and, or, not

Resources:
Computer Science Circles – Else, And, Or, Not -
http://cscircles.cemc.uwaterloo.ca/9-else-and-or-not/
TutorialPoint – Python Basic Operators -
https://www.tutorialspoint.com/python/python_basic_operators.htm

Purpose:
To investigate the use of Boolean operators in python
To understand the order of operations
To apply Boolean operators to programming
To Understand Boolean logic it helps to re-cap on some prior learning.

In Computer science, a Boolean expression uses a Boolean operators to produce


a Boolean value. The Expression is the question being asked or the formula. The
Operators are And, Or, Not, Nor, Xor, Nand. The Boolean value is either true (1) or
false (0(

Boolean operators are only concerned with the values True (I) and False (0)
Symbol Statement Explanation Example
AND The output is true when A Output X=1
is true and B is true if both inputs A and B are
1
OR The output is true when A Output X =1
is true or B is true, or both if either A or B = 1
are true
NOT The output is true when A Output X = 1
is true or B is false and if the input A = 0
A&B are false
XOR The output is true when A Output X=1
is true or B is not true, but If (Input A =1 AND Input B
not when both A and B are =0)
true. Or (Input A = 0 AND Input
B = 1)
NAND The Output is true when Output X = 1
both A and B are both not If Input A and Input B are
true both NOT 1
NOR The output is true when Output X = 1
neither A or B are true If Neither Input A or input
B is 1
Truth Tables
Truth tables trace the output of a logic gate or circuit in a similar way to a trace table
in an algorithm. The Number of inputs will give you the number of output you will
need to calculate.

A and B Truth Table (Example one)


Number of Number of Input Output
Inputs combinations
1 21 2 A B X
2
2 2 4 0 0 0
3
3 2 8 0 1 0
4
4 2 16 1 0 0
1 1 1
Truth Tables (Example two)

Figure 9. Boolean logic truth tables. Image Source:


https://learn.sparkfun.com/tutorials/digital-logic

Order of Operations
Boolean operators have an "order of operations" just like mathematical operators.
The order is
NAO: not (highest precedence), and, or (lowest precedence)
so for example,
not x or y and z means (not x) or (y and z)
Source: http://cscircles.cemc.uwaterloo.ca/9-else-and-or-not/
Learning Activity:

#Boolean operators in python

#state variables
a = True
b = False

#script
#AND boolean logic
print('AND Boolean logic')
print ('The AND operator evaluates two operands and only return TRUE if
both operands are TRUE.\n')
print ('a AND a =\t\t', a and a)
print ('a AND b =\t\t', a and b)
print ('b AND a =\t\t', b and a)
print ('b AND b =\t\t', b and b ,'\n')

#OR boolean logic


print ('OR Boolean logic')
print ('The OR operator evaluates two operands and will return TRUE if either
operands is TRUE.\n')
print ('a OR a =\t\t', a or a)
print ('a OR b =\t\t', a or b)
print ('b OR a =\t\t', b or a)
print t('b OR b =\t\t', b or b ,'\n')

#NOT boolean logic


print ('NOT Boolean logic')
print ('The NOT operator, called a unary operator. It returns the inverse of the
value of the given operand. So is a is true not a returns false.\n')
print ('a = ',a, '\t\tnot a=', not a)
print ('b = ',b, '\t\tnot b=', not b, '\n')

#NAND Boolean Logic


def NAND (a,b):
if a == True:
if b == True:
return False
else:
return True

print ('NAND Boolean logic')


print ('The NAND operator.\n')
print ('a NAND a =\t\t', NAND(a,a))
print ('a NAND b =\t\t', NAND(a,b) ,'\n')

#XOR Boolean Logic


def XOR (a,b):
if a != b:
return True
else:
return False
print ('XOR Boolean logic')
print ('The XOR operator.\n')
print ('a XOR a =\t\t', XOR(a,a))
print ('b XOR a =\t\t', XOR(b,a))
print ('a XOR b =\t\t', XOR(a,b))
print ('b XOR b =\t\t', XOR(b,b) ,'\n')

Learning Activities – Boolean And

# -----Alter these True, False values


a, b = True, False
# -----Alter these True, False values

if a == True and b == True:


print('both inputs are true')
else:
print('at least one input is false')

Learning Activities – Boolean Or

# -----Alter these True, False values


a, b = True, False
# -----Alter these True, False values

if a == True or b == True:
print('at least one input is true')
else:
print('both inputs are false')

Learning Activity – Boolean Not & And

a, b, c, d = True, True, False, False


if not(a and b and c and d):
print('one of these values is false')
else:
print('none of the value are false')

Learning Activity - Boolean – Using Or


# -----Alter these True, False values
train1, bus1, bus2 = False, True, True
# -----Alter these True, False values

if train1 == True or bus1 == True and bus2 == True:


print('Yes, I can get to work.')
else:
print("Can't make it today.")
Summary program: making a meal out of operators

Finally try this out:

# making a meal out of operators


snack = True
if snack == True:
print("snack is good")

#using else
jelly = False
if jelly == False:
print("jelly was a lie")
else:
print("jelly is yummy")

# Not
thirsty = False
if not thirsty:
print("You don't need a coffee")

# and
lunch = True
pie = True
if lunch and pie:
print("pie for lunch")

# or
dinner = False
cake = True
if dinner or cake:
print ("let them eat cake")

Terminology:
AND – Boolean expression - The output is true when A is true or B is true, or both
are true.
OR – Boolean expression - The output is true when A is true or B is true, or both
are true.
NOT– Boolean expression - The output is true when A is true or B is false and
A&B are false.
NAND– Boolean expression - The Output is true when both A and B are both not
true.
NOR– Boolean expression - The output is true when neither A or B are true.
XOR– Boolean expression - The output is true when A is true or B is not true, but
not when both A and B are true.
Lists or Arrays

Resources:
CS Circles – Lists (Arrays) - http://cscircles.cemc.uwaterloo.ca/13-lists/
CS Circles Recursion - https://cscircles.cemc.uwaterloo.ca/16-recursion/
Python Lists – Google for Education - https://developers.google.com/edu/python/lists
Python List and tuple tutorial – Google for education -
https://www.youtube.com/watch?v=EPYupizJYQI
TutorialPoint – Python Lists - https://www.tutorialspoint.com/python/python_lists.htm
TutorialPoint – Python Tuples - https://www.tutorialspoint.com/python/python_tuples.htm
TutorialPoint – Python Dictionary - https://www.tutorialspoint.com/python/python_dictionary.htm

W3Schools
https://www.w3schools.com/python/python_lists.asp
https://www.w3schools.com/python/python_tuples.asp
https://www.w3schools.com/python/python_sets.asp
https://www.w3schools.com/python/python_dictionaries.asp

Purpose:
To develop an understanding of using lists (Arrays) to store and retrieve information
To understand and use one and two dimensional arrays
To understand the difference between lists, tuples and sets
To manipulate the data in lists (Arrays)

An Array is defined as:


A set of related data items stored under a single identifier and accessed based on
their position. Arrays can work in one or more dimensions.
Reeves, B. Computer Science. Hodder Education. 2015

Lists and arrays are data structures created by programmers to store data. A list can
be manipulated and modified. Another type of list is a tuple is a list that can not be
changed. A third type of list is a Set is a restricted list of unique values, so you can
not repeat the values.

A list uses [ ] brackets


A tuple uses () brackets
A set uses {} brackets

Lists or Arrays have an index which starts with 0 and the data is associated with this
index value.

For example – the Rainbow Array


Index 0 1 2 3 4 5 6
Data ‘red’ ‘yellow’ ‘pink’ ‘blue’ ‘orange’ ‘purple’ ‘green’
For this set of data we can call up the values that are stored at index value 0 and 5.
These are respectively the first and 6th value in the array.
rainbow = ['red', 'yellow','pink','blue','orange','purple','green']
print ('first colour', rainbow[0], '\n')
print ('first colour', rainbow[5], '\n')
print ('the number of items in the array are: ', len(rainbow), '\n')
The result looks like this

The len stands for length of a string or the number of items in a list. Here, len gives
us the number of items in this array or list.

Learning Activity: - Array one!

Try this out

#working with lists


print('working with lists - Lists are often called arrays in other programming
languages')

#data Months - lists


print("This list has the 12 months of the year in order - the list is called
Months. \nMonths = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']\n")

#The list of months


Months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']

# this section prints a selection of months called from the list


print('First Month:\t', Months[0],'\n')
print('Second Month:\t', Months[1],'\n')
print('Tenth Month:\t', Months[9],'\n')
print('Eight Month:\t', Months[7],'\n')

#This section get the number of a month from the user and then check that it
is within the acceptable range (1-12)
x = input('\nEnter the number of the month (Number from 1 to 12): ')
x = int(x)
print( 'the value is', 'too high' if (x > 12) else 'within acceptable range')
a=x

#the location within the list starts at 0, months start at 1 so the value is
manipulated to correctly search the list
x = x-1

#prints the result


print('Your month is number',a ,', which is:', Months[x],'\n' )
Here is the output of this program

The second and third Dimension

The rainbow array is a one dimensional array. A two dimensional array would have a
second element added in to the values
myArray=[[1,2],[3,4]]

Learning Activity – Multi Dimensional Array

This activity involves making a number of multi dimensional lists or arrays. The
product looks like this:
Here is the code for this program
# This program looks at multi-dimensional lists
#Data
coords = [[1,2,3],[4,5,6],[7,8,9]]
#script
print('The multi-dimensional list has the following structure\n')
print('\n\t1,\t2,\t3')
print('\t4,\t5,\t6')
print('\t7,\t8,\t9\n')

print('Co-ordinates, 0,0 (top left)\t\t:', coords[0][0])


print('Co-ordinates, 0,1 (top middle)\t:', coords[0][1])
print('Co-ordinates, 0,2 (top right)\t\t:', coords[0][2])
print('Co-ordinates, 1,0 (middle left)\t:', coords[1][0])
print('Co-ordinates, 1,1 (middle middle)\t:', coords[1][1])
print('Co-ordinates, 1,2 (middle right)\t:', coords[1][2])
print('Co-ordinates, 2,0 (bottom left)\t:', coords[2][0])
print('Co-ordinates, 2,1 (bottom middle)\t:', coords[2][1])
print('Co-ordinates, 2,2 (bottom right)\t:', coords[2][2])
#Data
wordcoords = [['one','two','three'],['four','five','six'],['seven','eight','nine']]
#script
print('\nThe second multi-dimensional list uses numbers instead of words and has the
following structure\n')
print('\n\tone,\ttwo,\tthree')
print('\tfour,\tfive,\tsix')
print('\tseven,\teight,\tnine\n')

print('Co-ordinates, 0,0 (top left)\t\t:', wordcoords[0][0])


print('Co-ordinates, 0,1 (top middle)\t:', wordcoords[0][1])
print('Co-ordinates, 0,2 (top right)\t\t:', wordcoords[0][2])
print('Co-ordinates, 1,0 (middle left)\t:', wordcoords[1][0])
print('Co-ordinates, 1,1 (middle middle)\t:', wordcoords[1][1])
print('Co-ordinates, 1,2 (middle right)\t:', wordcoords[1][2])
print('Co-ordinates, 2,0 (bottom left)\t:', wordcoords[2][0])
print('Co-ordinates, 2,1 (bottom middle)\t:', wordcoords[2][1])
print('Co-ordinates, 2,2 (bottom right)\t:', wordcoords[2][2])
#extract first letter of each member of the list
print('\nThis part of the program extract first letter of each member of the list.\n')
print('\t',wordcoords[0][0][0],wordcoords[0][1][0],wordcoords[0][2][0])
print('\t',wordcoords[1][0][0],wordcoords[1][1][0],wordcoords[1][2][0])
print('\t',wordcoords[2][0][0],wordcoords[2][1][0],wordcoords[2][2][0])
#Selecting from the list
a = input('\nEnter row number (1-3): ')
b = input('\nEnter column number (1-3): ')
a = int(a)
b = int(b)
a = a-1
b = b-1
#prints the result
print('Your number is: \t',coords[a][b], 'or', wordcoords[a][b] )
Learning Activity – Multi Dimensional Array 2 – Cylinder Volume

This activity is an iterative process that will after several iterations produce a multi
dimensional array.

Iteration one

Use the program below to calculate the volume of a cylinder.

Create the program in your editor of choice and add comments to explain the code.

import math

#script
def volume():
radius=float(input("enter the radius of the cylinder in mm: "))
height=float(input("Enter the height of the cylinder in mm: "))

cylinderVolume=(math.pi*((radius)**2)*height)

print("the volume of the cylinder is " +format(cylinderVolume)+ " mm")

volume()

Iteration two

Using the previous program as a base develop a multi-dimensional array that


calculates the volume of a range of values for height and radius.

Use the following values in the array

Index 0 1 2 3 4
0 7 14 3 101 17
1 5 6 3 3 12

You can use and adapt the following examples


import math

#data

Cylinder = [[7,5],[14,6],[3,3],[101,3],[17,12]]
Volume = []

#script
for i in range (0,len(Cylinder)):
currentarray=Cylinder[i]
r=currentarray[0]
h=currentarray[1]
Volume.append(math.pi*((r)**2)*h)
print(Volume)

#adapted from Original code from Jouveer

Or you could adapt this approach using integers rather than floats

import math

#data

Cylinder=[(7,5),(14,6),(3,3),(101,3),(17,12)]
counter=0

#script
for counter in range(0,len(Cylinder)):
radius=int(Cylinder[counter][0])
height=int(Cylinder[counter][1])
volume=int(math.pi*(radius**2)*height)
print("volume="+str(volume))
counter+=1
exit
Manipulating the array

There are a range of methods that can be used to manipulate the information within
the array. The common methods are:
Here are some other common list methods.
list.append(elem) -- adds an element to the end of the list. elem is the data being
added.
list.insert(index, elem) -- inserts the element at the given position or index, it moves
the other elements to the right. Index is the list position elem is the element or data
being inserted.
list.extend(list2) adds the elements in a second list called list2 to the end of the
original list.
list.index(elem) -- searches for the given element from the start of the list and
returns its index.
list.remove(elem) -- searches for the first instance of the given element and removes
it
list.sort() -- sorts the list.
list.reverse() -- reverses the list.
list.pop(index) -- removes and returns the element at the given index. Returns the
rightmost element if index is omitted (roughly the opposite of append()).

Learning Activity – manipulate the data

#This program manipulates the data in Lists.


#The method uses the object (list)name and then dot suffixed method
#The methods are .append(x) .extend(L) .insert(i,x) .remove(x) .pop(i) .index(x)
.count(x) .sort() .reverse()
# L = length of list
# i = index position
# x = object

print('\t\t\tManipulating lists')
print('\nThis program manipulates the data in Lists. The method uses the object
(list)name and then dot suffixed method.\n ')
print('The methods are \n\tlist.append(x) \n\tlist.extend(L) \n\tlist.insert(i,x)
\n\tlist.remove(x) \n\tlist.pop(i) \n\tlist.index(x) \n\tlist.count(x) \n\tlist.sort()
\n\tlist.reverse()\n\n')
print('Where: \n\tL = length of list \n\ti = index position \n\tx = object \n\n ')

#data
shelf = ['apples', 'pear', 'oranges', 'carrots', 'lemons', 'superwines']
shoppingbasket = ['eggs', 'beans', 'peas', 'chicken', 'basil', 'cabbage']

#script
print('On the shelf are:', shelf)
print('The number of items on the shelf are:', len(shelf))
print('In the shopping basket are:', shoppingbasket)
print('The number of items in the shopping basket are:', len(shoppingbasket),'\n')

#adding to the shopping basket using append


print('Adding bread to the shopping basket')
shoppingbasket.append('bread')
print('\nAppend - add item x to the end of the list.\nNew list is now:', shoppingbasket)

#adding to shopping basket using insert


print('\nAdd butter as second item in shopping basket. \nBefore:',shoppingbasket)
shoppingbasket.insert(1,'butter')
print('\nList with inserted item', shoppingbasket)

#removing from shelf using pop


print('\nUsing pop to remove a specific item - item 3. In this case shelf.pop(2) the 2 is
the index value of the list - important lists start at 0, 1, 2, 3.....\nList before',shelf, '\n')
shelf.pop(2)
print('\nList after removing item 3', shelf)

#removing from shelf using remove


print('\n\nUsing .remove(x) to remove a specific item. In this case removing lemons
from the shelf using shelf.remove(lemons) \nThe list before:', shelf)
shelf.remove('lemons')
print('\nList removing lemons', shelf)

#adding the entire of the shelf list to the shoppingbasket list using extend(L)
print('\nAdding the entire of the list to the shopping basket list. \nThe shoppingbasket
list prior to the extend:', shoppingbasket)
shoppingbasket.extend(shelf)
print('The list when the shelf list is added', shoppingbasket)

#using the sort method


print('\nUsing the sort method to sort the shoppingbasket.\nThe list before the sort:',
shoppingbasket)
shoppingbasket.sort()
print('\nThe list after the sort:', shoppingbasket)
Learning activity: Another look at methods for arrays

#list and list methods

#print first list


firstlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
print (firstlist)

#change second list items


secondlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
secondlist[0:3] = ["lead learners", "old boys and girls"]
print(secondlist)

#insert items
thirdlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
thirdlist.insert(2, "other people")
print(thirdlist)

#append item into list


fourthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
fourthlist.append("cleaners")
print(fourthlist)

#extend the list


fifthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
otherjobs = ["bus drivers", "librarians", "caterers"]
fifthlist.extend(otherjobs)
print(fifthlist)

#remove items from a list


sixthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
sixthlist.remove("students")
print(sixthlist)

#removing item using pop and index position


seventhlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
seventhlist.pop(0)
print(seventhlist)

#removing last item using pop


eighthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
eighthlist.pop()
print(eighthlist)

#clear the list


ninthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
ninthlist.clear()
print(ninthlist)

#Sort this list (works for numbers too)


tenthlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
tenthlist.sort()
print(tenthlist)
#desending sort list
eleventhlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
eleventhlist.sort(reverse = True)
print(eleventhlist)

#count this list


twelfthlist = ["teachers", "Students", "Students", "Students","Alumni", "Support staff",
"admin staff"]
x = twelfthlist.count("Students")
print(x)

#where is the item in the list


thirteenthlist = ["teachers", "Students", "Students", "Students","Alumni", "Support
staff", "admin staff"]
x = thirteenthlist.index("Alumni")
print(x)

and the result looks like this:


Learning Activity: Lists and if Else

In. this activity you will use an if else statement and some comparative operators to
add and remove items from a list.
The comparative operators are == and !=

list = []
add = ""
while add != "stop" :
add = input("enter your items here:")
if add == "clear":
list.clear()
print(list)
elif add == "remove":
remover = int(input("enter the list number you want to remove:"))
list.pop(remover-1)
print(list)
elif add == "stop":
print("thank you")
break
else:
list.append(add)
print(list)
Learning Activity: Tuples and Sets

#types of lists - sets and tuples


print('\t\tTypes of lists - sets and tuples.\n\n')

#tuples
print('A TUPLE is a list that can not be changed. The Tuple uses brackets () rather
than []. The values can not be changed by the program.\n')

animals = ('Dog', 'cat', 'mouse','rat')


print('Tuple - immutable list', animals,'\tLength', len(animals))

#sets
print('\nSets are a type of restricted list of unique values - you can\'t repeat values.
Sets use {} rather than [] of a list or the () of a tuple. \nSets can be used for
comparisons of the contents\n')

print('Sets can be manipulated by the following methods:\n\tset.add(x) - adds and


item to the set\n\tset.update(x,y,z) - adds multiple items to the set\n\tset.pop() -
removes a randon element from the set\n\tset.discard(i) - removes the item at
position i (remember index starts at 0)\n\tset1.intersection(set2) - returns items that
appear in both sets\n\tset1.difference(set2) - returns the items in set one that are not
in set 2')

print('\n\nTwo sets of colours - left and right')


left = {'red', 'blue', 'green', 'orange', 'pink'}
print("left = {'red', 'blue', 'green', 'orange', 'pink'}","Length:",len(left))
right = {'red', 'green', 'yellow', 'orange', 'grey'}
print("right = {'red', 'green', 'yellow', 'orange', 'grey'}\n","Length:",len(right))
left.add('lemon')

print('Add lemon to the Left list', left, 'Length of left list:',len(left),'\n\n')


print('is green in left set?', 'green' in left)
print('is orange in right set?', 'orange' in right)
print('is lemon in left set?', 'lemon' in right, '\n\n')
print('Common colours in both sets',left.intersection(right))
print('Colours only in left set',left.difference(right))
print('Colours only in right set',right.difference(left))
Learning Activity – What is in that Pizza?

This is an example of a python array from the APC Magazine

Create this Pizza program

pizzas = [
['Margherita','tomato base','oregano','cheese','garlic'],
['Italian Classic','tomato base','oregano','anchovies','kalamata olives'],
['Vegetarian','tomato base','onion','capsicum','mushroom','kalamata olives',
'pineapple','semidried tomatos']
]

print('Types of pizzas: ')


count = 0
for pizza in pizzas:
count += 1
print(count,' * ', pizza[0])

pizzatype = int(input('Enter a number to list ingredients: '))-1


print('A', pizzas[pizzatype][0], 'pizza has the following ingredients:')
for ingredients in range(1,len(pizzas[pizzatype])):
print(' * ', pizzas[pizzatype][ingredients])

Add in suitable comments to explain what is happening with this python program
pizzas = [
['Margherita','tomato
base','oregano','cheese','garlic'],
['Italian Classic','tomato
base','oregano','anchovies','kalamata olives'],
['Vegetarian','tomato
base','onion','capsicum','mushroom','kalamata
olives',
'pineapple','semidried tomatos']
]

print('Types of pizzas: ')


count = 0
for pizza in pizzas:
count += 1
print(count,' * ', pizza[0])

pizzatype = int(input('Enter a number to list


ingredients: '))-1

print('A',pizzas[pizzatype][0], 'pizza has the


following ingredients:')

for ingredients in
range(1,len(pizzas[pizzatype])):
print(' * ', pizzas[pizzatype][ingredients])
Learning Activity – Manipulating data in an array – Batting scores in cricket
This is another activity from APC magazine – this one manipulates the data in an
array and makes use of the Len – command.

Try this out

batting_scores = [34, 39, 0, 99, 180, 15, 87, 23, 16, 2]


print('batting_scores (raw) :', batting_scores)

# calculate average
total_runs = 0
for score in batting_scores:
total_runs += score
batting_average = total_runs / len(batting_scores)
print('Batting average:', batting_average)

# get highest and lowest scores


print('Highest score :', max(batting_scores))
print('Lowest score :', min(batting_scores))

# calculate median (middle) score


batting_scores.sort()
print('batting_scores (sorted):',batting_scores)
midIndex = int(len(batting_scores)/2)
if len(batting_scores)%2 != 0:
median_score = batting_scores[midIndex]
else:
median_score = ( batting_scores[midIndex] + batting_scores[midIndex-1] ) / 2
print('Median score :', median_score)

Learning activity Recursion – Count down time

Recursion is the process where programme or sub-routine call itself. A simple


introduction and explanation of recursion can be the Launch program below.
The Base case is the last case of the recursion. In this case its is 0. When the Base
case is reached it will print off then message. Every recursion the last step MUST be
the base case.
The Reduction step is the function that moves the program towards the base case.
In this case it is n-1

def launch(n):
if n == 0:
print("Blast Off launch launch launch")
else:
print(n)
launch(n-1)

launch(10)
Figure 12. The output for the launch program.
Learning Extension – modify the countdown
Try this example from the Computer Science circles:

def countdown(n):
print('Entering countdown(',n,')')
if n == 0:
print('Blastoff!')
else:
print(n)
countdown(n - 1)
print('Exiting from countdown(',n,')')

limit = int(input())
countdown(limit)

Learning activity – Simple recursion – calculating the sum of a list of numbers

Try this out

def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum

print(listsum([1,3,5,7,9]))

Why is this an example of recursion?

The three laws of recursion

Recursive algorithms must obey three important laws:

1. A recursive algorithm must have a base case.


2. A recursive algorithm must change its state and move toward the base case.
3. A recursive algorithm must call itself, recursively.

A base case is a base case is the condition that allows the algorithm to stop
recursing.

A change of state means that some data that the algorithm is using is modified.

The final law is that the algorithm must call itself.


Game Time: Paper, Rock, Scissors

Objective:
To create a paper, scissor, rock guessing game where the computer randomly
selects one of the three objects and then compare the players selection:
Rules
● Same object vs same object is a tie
● Paper covers rock
● Scissors cut paper
● Rock breaks scissors

Hints:
Use an list (array) for the options for the computer
Remember that the index of an array starts at zero

Code snippet
#create a list (array) of play options
guessoptions = ["Rock", "Paper", "Scissors"]

#assign a random play to the computerguess


computerguess = guessoptions[randint(0,2)]
Extension: - Tabulate that array!

Tabulate is a module that you will need to install. You will need to do this from the
terminal - the command is pip3 install tabulate

Then once this is installed try this out. This function allows you to format your list into
a table.

# you need to install the tabulate module - from terminal pip install tabulate #

from tabulate import tabulate

testdata = [[ "Name", "Age", "Balance"],


["Jayden", 16, 16],
["James", 16, 45],
["Jane", 16, 35],
["Jana", 18, 55],
["Jordan", 22, 145]]

table1 = tabulate(testdata)
table2 = tabulate(testdata,headers='firstrow',showindex='always')
table3 = tabulate(testdata,headers='firstrow',tablefmt='plain')
table4 = tabulate(testdata,headers='firstrow',tablefmt='grid',
showindex='always', numalign='center')
table5 = tabulate(testdata,headers='firstrow',tablefmt='fancy_grid',
numalign='left')
table6 = tabulate(testdata,headers='firstrow',tablefmt='jira',
showindex='always')
table7 = tabulate(testdata,headers='firstrow',tablefmt='textile',
numalign='right')

print("basic tabulation nothing added")


print(table1)
print ("\n header is first row and show index")
print(table2)
print ("\n plain table format")
print(table3)
print("\n grid table format, show index and align to center")
print(table4)
print("\n fancy grid table format and align to left")
print table5)
print("\n Jira table format and show index")
print(table6)
print("\n textile table format and align to right")
print (table7)

Attributes
showindex property always
headers property firstrow or keys
numalign property left, center, right
tablefmt property - plain, grid, fancy_grid, jira, textile & HTML
Terminology:
Array - A set of related data items stored under a single identifier and accessed
based on their position. Arrays can work in one or more dimensions.

List – an array that can be manipulated and modified. A list uses [ ] brackets.

Tuple is a list that can not be changed. A tuple uses () brackets

Set is a restricted list of unique values, so you can not repeat the values. A set
uses {} brackets

Recursion. A method of programming where the answers or solution is dependent


on smaller instances of the same problem.

Base case: the last case of the recursion. Every recursion the last step MUST be
the base case.

Reduction step: the function that move the recursion towards the base case.

Tabulate a module that allows you to present text in a table format. Tabulate
needs to be installed
Going Gui
Resources:
Heuristic Evaluation https://en.wikipedia.org/wiki/Heuristic_evaluation
Usability https://www.usability.gov/how-to-and-tools/methods/index.html
Nielsen’s Heuristics -
https://www.usability.gov/how-to-and-tools/methods/heuristic-evaluation.html
Python wiki – Tkinter - https://wiki.python.org/moin/TkInter
Python GUI programming (Tkinter) -
http://www.tutorialspoint.com/python/python_gui_programming.htm
Tkinter – Python interface to Tcl/Tk - https://docs.python.org/2/library/tkinter.html

Purpose:
To explore and develop an understanding of developing Graphical user interfaces
To incorporate GUI into python programming
To consider Heuristics in the development of the GUI
Incorporating different elements into the graphical user interface including:
● Text, entry boxes and labels
● Buttons
● Use of frames
● Titles
● Radio buttons and check boxes
● Message boxes

UI - Considering the User Interface

When we start to build our user interfaces we need to consider how useful and
suitable these are for our users. The best concept in the world can be ruined by a
poorly conceived, rushed or haphazard User Interface.

Jakob Nielsen’s Heuristic Evaluation

Jakob Nielsen is a Dutch expert in Human computer interactions. He developed in


1994 a set of 10 heuristics or measures that should be considered in the
development of a system/program or application. These are:

1. Visibility of system status:


The system should always keep users informed about what is going on,
through appropriate feedback within reasonable time.
2. Match between system and the real world:
The system should speak the user's language, with words, phrases and
concepts familiar to the user, rather than system-oriented terms. Follow
real-world conventions, making information appear in a natural and logical
order.
3. User control and freedom:
Users often choose system functions by mistake and will need a clearly
marked "emergency exit" to leave the unwanted state without having to go
through an extended dialogue. Support undo and redo.
4. Consistency and standards:
Users should not have to wonder whether different words, situations, or
actions mean the same thing. Follow platform conventions.
5. Error prevention:
Even better than good error messages is a careful design which prevents a
problem from occurring in the first place. Either eliminate error-prone
conditions or check for them and present users with a confirmation option
before they commit to the action.
6. Recognition rather than recall:
Minimize the user's memory load by making objects, actions, and options
visible. The user should not have to remember information from one part of
the dialogue to another. Instructions for use of the system should be visible or
easily retrievable whenever appropriate.
7. Flexibility and efficiency of use:
Accelerators—unseen by the novice user—may often speed up the interaction
for the expert user such that the system can cater to both inexperienced and
experienced users. Allow users to tailor frequent actions.
8. Aesthetic and minimalist design:
Dialogues should not contain information which is irrelevant or rarely needed.
Every extra unit of information in a dialogue competes with the relevant units
of information and diminishes their relative visibility.
9. Help users recognize, diagnose, and recover from errors:
Error messages should be expressed in plain language (no codes), precisely
indicate the problem, and constructively suggest a solution.
10. Help and documentation:
Even though it is better if the system can be used without documentation, it
may be necessary to provide help and documentation. Any such information
should be easy to search, focused on the user's task, list concrete steps to be
carried out, and not be too large.
https://www.usability.gov/how-to-and-tools/methods/heuristic-evaluation.html

Learning Activity: My First Window


We develop the GUI or graphical user interface by importing a module called Tkinter.
Most of our development has been baced around the command line interface. This is
easier to code but lacks the finish and polish of a GUI.

Figure 13. My First Window using Tkinter

Here is the code:


#import the tkinter GUI module
from tkinter import *

#create a window object


window = Tk()

#add a title to the window


window.title('My First window')

#create a label in the window and add text to the label


label = Label(window, text='Good Morning Students')

#position the label using vertical and horizontal padding


label.pack(padx=200, pady=50)

#This is a mandatory statement to execute the window code


window.mainloop()
.GRID
.grid is a geometry manager. It allows you to place the objects into a your window or
frame. Essentially the .grid geometry manager treats the layout of each window and
frame like a table a networks of rows and columns

As such…
● A cell is the intersection of a row and column
● The column is as wide as the widest cell in the column
● The row is as heigh as the highest cell in the row
● You can combine cells by spanning – columnspan and rowspan
● Sticky positions your widget within the cell
o Sticky=NE is top right
o Sticky = SE is bottom right
o Sticky = E is right center
o Sticky = N is top center
o And so on

Learning Activity – Colours and frames


This is a simple task to explore the use of colours and frames within the GUI.

Create this simple GUI.


Figure 14. Colours and frames in a GUI

window = Tk()
window.title('colours and frames')

frame1 = Frame(window, height=100, width=100, bg='blue')


frame1.grid(row=0, column=0)

frame2 = Frame(window, height=100, width=100, bg='yellow')


frame2.grid(row=0, column=2)

frame3 = Frame(window, height=100, width=100, bg='red')


frame3.grid(row=1, column=1)

frame4 = Frame(window, height=100, width=100, bg='orange')


frame4.grid(row=2, column=0)

frame5 = Frame(window, height=100, width=100, bg='green')


frame5.grid(row=2, column=2)

window.mainloop()

Learning Activity – Side by Side CLI and GUI


In this activity we will look at developing a CLI (Command line interface) and GUI
(Graphical user interface) version of the same task.
The task essentially provides a times table for a multiple number being inputted for
the number of times entered in the second selection.

Here is the CLI/Text based version

#input the number to be multiplied and the number of pultiples required


number = int(input('Input number to be multiplied: '))
number_required = int(input('Input the number of multiples: '))

#calculate the values and output these


for counter in range(1, number_required+1):
multiple = number * counter
print(multiple)
Figure 15. CLI times table multiples output

Now here is the GUI version

#calculate multiples
#imports GUI module
from tkinter import *

#define the calculation and identify the inputs and outputs


def multiply():

#get content of the input boxes


number1 = int(textbox_input1.get())
number2 = int(textbox_input2.get())

#clear the text output box

textbox_output.delete(0.0, END)

#Process amd output result

for counter in range(1, number2 + 1):


multiple = str(number1 * counter) + '\n'
textbox_output.insert(END, multiple)

#develop the interface


window = Tk()
window.title('Multiples application')

#assign size and background colour


window.geometry('250x400')
window.configure(background='linen')

#create the labels for the window


input_label = Label(window, text='number to multiply: ', bg='linen')
input_label.grid(row=0, column=0, sticky=W)
input_label2 = Label(window, text='number of multiples: ', bg='linen')
input_label2.grid(row=2, column=0, sticky=W)
output_label = Label(window, text='Output: ', bg='linen')
output_label.grid(row=0, column=1, sticky=E)

#create the text entry boxes


textbox_input1 = Entry(window, width=5)
textbox_input1.grid(row=1, column=0, sticky=NW)
textbox_input2 = Entry(window, width=5)
textbox_input2.grid(row=3, column=0, sticky=NW)

#create the text output boxes


textbox_output = Text(window, height=20, width=6)
textbox_output.grid(row=1, column=1, rowspan=5, sticky=E)

#create the button and link to the function


multiple_button = Button(window, text='Get Multiples', command=multiply )
multiple_button.grid(row=4, column=0, sticky=W)

#mandatory statement
window.mainloop()

Figure 16. GUI version of the multiples program

Learning Activity: Prime Numbers

A prime number is a number that is divisible only by itself and by 1.


If we look at the first 100 integers the highlighted ones are prime numbers.

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
This table can be used as test data for the prime numbers experiment below.
We are going to develop this application in a text/CLI based approach and a GUI
based application.

Prime Number - Text Based Solution

prime = True
number=int(input('Enter your number: '))
counter=2

while True:
modulus = number % counter
if modulus == 0:
prime = False
counter = counter + 1

if counter == number-1 or prime == False:


break

if prime == True:
print('your number is a prime number')

else:
print('your number is not a prime number')

Prime Number - GUI Based Solution

Figure 17. Testing Prime numbers

Develop the code below, add descriptive comments and test the application
against the prime number table above.

from Tkinter import *

def prime():
modulus_counter=0
number=int(textbox_input.get())
textbox_output.delete(0.0, END)

for counter in range(2, number):


modulus = number % counter
if modulus == 0:
modulus_counter = modulus_counter +1

if modulus_counter == 0:
textbox_output.insert(END, 'Prime number')
else:
textbox_output.insert(END, 'Not a prime number')

window = Tk()
window.title('Prime Numbers')

window.geometry('200x100')
window.configure(background='lightblue')

textbox_input = Entry(window, width=10)


textbox_input.grid(row=0, column=1, sticky=E)

textbox_output = Text(window, height=1, width=25)


textbox_output.grid(row=1, column=0, columnspan=2)

prime_button = Button(window, text='Prime?', command=prime)


prime_button.grid(row=0, column=0, sticky=W)

window.mainloop()
Learning Activity – message boxes

Message boxes are important tools as they can be used to update the user – for
example error messages and to confirm actions. Tkinter allows you to develop and
implement message boxes.

The application below also assigns the message box tkMessageBox as a shorter
and more usable form as box

Examine the code below and develop a flowchart that explains it. Then develop,
comment and test the application.

from Tkinter import *


import tkMessageBox as box

window = Tk()
window.title('Message box examples')

def dialog():
var = box.askyesno('Message Box', 'Proceed?')
if var ==1:
box.showinfo('Yes Box','Proceeding...')
else:
box.showwarning('No Box','Cancelling...')
btn = Button(window, text='click', command=dialog)
btn.pack(padx=150, pady=50)

window.mainloop()

Display message methods include:


● showinfo()
● showwarning()
● showerror()
● askquestion()
● asokcancel()
● askyesno
● askretrycancel

Now lets try a second task with message boxes. This one gathers an input, the
persons name and then adds this into a second box.

Figure 18. Message boxes using tkMessageBox.

Here is the code:

from Tkinter import *


import tkMessageBox as box

window = Tk()
window.title('Message box Inputs')
frame = Frame(window)
entry = Entry(frame)

def dialog():
box.showinfo('Greeting' , 'Welcome ' +entry.get())

btn = Button(frame, text='Enter your name ', command=dialog)


btn.pack(side = RIGHT, padx=5)
entry.pack(side = LEFT)
frame.pack(padx=20 , pady=20)
window.mainloop()

Learning activity – messagebox with list box

You can reuse the base code from the previous example to develop this solution.
The product is a selection from 5 items in a list and the selection then appears in a
message box.

Figure 19. Listbox GUI code and output.

Develop this solution, adjust the list items and the colours to suit. Add comments.

from Tkinter import *


import tkMessageBox as box

window = Tk()
window.title('Message box List Box')
frame = Frame(window)
listbox = Listbox(frame)

listbox.insert(1, 'Digital technology')


listbox.insert(2, 'Computer science')
listbox.insert(3, 'ITGS')
listbox.insert(4, 'Design technology')
listbox.insert(5, 'Digital Design')

def dialog():
box.showinfo('Selection' , 'your choice ' + listbox.get( listbox.curselection()
))

btn = Button(frame, text='Choose ', command=dialog)


btn.pack(side = RIGHT, padx=5 )
window.configure(background='blue')
listbox.configure(background='green')
listbox.pack(side = LEFT)
frame.pack(padx=30 , pady=30)
window.mainloop()
You can modify the code by using yscrollcommand – attaches to a vertical scroll bar
Text Boxes and Entry Boxes
Entry boxes allow you to create and manipulate entry from one line entry widgets.
Text boxes allow you to create containers/widgets for text in your program.
Labels are non interactive text or image widgets.

Learning activity Text and Entry boxes

Text Box

This code allows us to set the width of the text box and the height. Use this code to
create the simple app and then modify it. Add the program to your library of
development applications.

from tkinter import *

app = Tk()
app.title('formating textboxes')
app.geometry('400x300')
app.config(bg='#0000FF')

message ='''
Hi Student,

This is a method of
structuring and formatting
the text in the textboxes.

Keep calm and code,


KS Com Sci '''

text_box = Text(
app,
height=12,
width=40
)
text_box.pack(expand=True)
text_box.insert('end', message)
text_box.config(state='disabled')

app.mainloop()
Entry Box
Try this code and then add the relevant explanatory comments in the column beside
the code.

Figure 21 Entry Box - GUI - TKinter

Code Comment
import tkinter as tk

app = tk.Tk()
app.geometry("400x200")
app.title('Entry Box')
app.configure(background='blue')

entryExample = tk.Entry(app,
width=50)

entryExample.pack(side=tk.LEFT,
padx=10)

app.mainloop()

Interesting:
You can format the background colour using either background-“colour” or
bg=’colour’.

Checkboxes and radio buttons


This next section looks at implementing radio buttons and check boxes in the GUI.
These are frequently used tools in the development of applications.

Learning activity Radio Buttons

Enter this code, add suitable comments. Some of the code can be recycled from
previous learning activities.

from Tkinter import *


import tkMessageBox as box

window = Tk()
window.title('Radio Box')
frame = Frame(window)
book=StringVar()
radio_1 = Radiobutton(frame , text = 'McDonalds', variable = book, value =
"I'm lovin it")
radio_2 = Radiobutton(frame , text = 'KFC', variable = book, value = 'Finger
lickin good')
radio_3 = Radiobutton(frame , text = 'Wendys', variable = book, value = 'real
tasty burgers')
radio_1.select()

def dialog():
box.showinfo('Selection' , 'your choice ' + book.get())

btn = Button(frame, text='Choose ', command=dialog)


btn.pack(side = RIGHT, padx=5 )
radio_1.pack( side = LEFT)
radio_2.pack( side = LEFT)
radio_3.pack( side = LEFT)
frame.pack(padx=30 , pady=30)

window.mainloop()

Figure 22. Using radio buttons - I'm lovin it!

Learning activity – Check boxes


As we have done with the radio buttons exercise, we can reuse some of the code to
make this new iteration using checkboxes

Figure 23. Collecting information using check boxes


from Tkinter import *
import tkMessageBox as box

window = Tk()
window.title('Check Box')
frame = Frame(window)

var_1=IntVar()
var_2=IntVar()
var_3=IntVar()
var_4=IntVar()
var_5=IntVar()

sub_1 = Checkbutton( frame , text = 'ITGS' , variable = var_1 , onvalue = 1,


offvalue = 0 )
sub_2 = Checkbutton( frame , text = 'Computer science' , variable = var_2 ,
onvalue = 1, offvalue = 0 )
sub_3 = Checkbutton( frame , text = 'Design technology' , variable = var_3 ,
onvalue = 1, offvalue = 0 )
sub_4 = Checkbutton( frame , text = 'Visual arts' , variable = var_4 , onvalue =
1, offvalue = 0 )
sub_5 = Checkbutton( frame , text = 'Sports Science' , variable = var_5 ,
onvalue = 1, offvalue = 0 )

def dialog():
str = 'Your Choice:'
if var_1.get() == 1: str += '\n Information technology in a global society'
if var_2.get() == 1: str += '\n Computer Science HL'
if var_3.get() == 1: str += '\n Design technology SL'
if var_4.get() == 1: str += '\n Visual arts design'
if var_5.get() == 1: str += '\n Sports and exercise science'
box.showinfo('Selection' , str)

btn = Button(frame, text='Choose ', command=dialog)


btn.pack(side = RIGHT, padx=5 )
sub_1.pack( side = LEFT)
sub_2.pack( side = LEFT)
sub_3.pack( side = LEFT)
sub_4.pack( side = LEFT)
sub_5.pack( side = LEFT)
frame.pack(padx=30 , pady=30)

window.mainloop()

Adding images

IMPORTANT: tkinter supports the following image file types .gif, .pgm and .ppm
This code illustrates how to insert images into the GUI
from Tkinter import *

window = Tk()
window.title('Using images')

img = PhotoImage( file = 'phone.gif')


label = Label( window , image = img , bg = 'white')

small_img = PhotoImage.subsample( img , x = 2 , y = 2)


btn = Button(window , image = small_img)
txt = Text(window , width = 25 , height = 7)
txt.image_create('1.0' , image = small_img)
txt.insert('1.1' , 'phone time')

can = Canvas( window , width = 100 , height = 100, bg = 'linen')


can.create_image(( 50 , 50) , image = small_img )
can.create_line( 0 ,0 ,100, 100, width = 25 , fill = 'red')

label.pack(side = TOP )
btn.pack( side = LEFT , padx = 10)
txt.pack( side = LEFT)
can.pack( side = LEFT , padx = 10)

window.mainloop()

Figure 24. Inserting images into the GUI. Tkinter only supports .gif files

Learning activity: Combining different elements in GUI & quit button

This task will see you create a GUI environment that asks the users to select a radio
button and then display the content in a label. It will also include an image inserted in
the window using the .grid aspect of layout of the window.
The application will also include a quit button which uses the command
window.destroy to quit the application and close the window.
The original design and code saw the submit button above the radio buttons. A
revised design of the application is below.
Year_label Logo
Radio button
Radio button
Radio button
Radio button
Radio button
Radio button
Radio button
Submit button Quit Button
Develop this application and change the position of the submit button

from Tkinter import *

def change_year():
year_label.config(text = year.get())

window = Tk()
window.title('Combining several elements in a GUI')

year_label = Label(window , width = 25 , height = 3, text = ' ')


year_label.grid(row = 0, column = 0)

img = PhotoImage( file = 'dove.gif')


photo_label = Label( window , image = img , bg = 'white')
photo_label.grid(row = 0 , column = 1)

submit_button = Button(window , text = 'submit' , width = 10 ,


command=change_year )
submit_button.grid(row = 1 , column = 0)

year = StringVar()

year7radio = Radiobutton(window , text = 'Year 7' , variable=year ,


value='Year 7 - \n first year of the middle school')
year7radio.grid(row = 2 , column = 0)
year7radio.select()
year8radio = Radiobutton(window , text = 'Year 8' , variable=year ,
value='Year 8 - \n second year of the middle school')
year8radio.grid(row = 3 , column = 0)
year9radio = Radiobutton(window , text = 'Year 9' , variable=year ,
value='Year 9 - \n moving out of home rooms')
year9radio.grid(row = 4 , column = 0)
year10radio = Radiobutton(window , text = 'Year 10' , variable=year ,
value='Year 10 - \n Community project')
year10radio.grid(row = 5 , column = 0)
year11radio = Radiobutton(window , text = 'Year 11' , variable=year ,
value='Year 11 - \n NCEA Level 1')
year11radio.grid(row = 6 , column = 0)
year12radio = Radiobutton(window , text = 'Year 12' , variable=year ,
value='Year 12 - \n NCEA Level 2 or IB 1')
year12radio.grid(row = 7 , column = 0)
year13radio = Radiobutton(window , text = 'Year 13' , variable=year ,
value='Year 13 - \n NCEA Level 3 or IB 2')
year13radio.grid(row = 8 , column = 0)

quit_button = Button(window, text='Quit', width = 10 ,


command=window.destroy)
quit_button.pack(side=RIGHT)
quit_button.grid(row = 8 , column = 1)

window.mainloop()

Creating a tabs
Tabbed environments are common in many applications and can be created in
python using tKinter
import tkinter as tk
from tkinter import ttk

# intializing the window


window = tk.Tk()
window.title("TABS")

# configuring size of the window


window.geometry('600x400')

#Create Tab Control


TAB_CONTROL = ttk.Notebook(window)

#Tab1
TAB1 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB1, text='Tab 1')

#Tab2
TAB2 = ttk.Frame(TAB_CONTROL)
TAB_CONTROL.add(TAB2, text='Tab 2')
TAB_CONTROL.pack(expand=1, fill="both")

#Tab Name Labels


ttk.Label(TAB1, text="This is Tab 1").grid(column=0, row=0, padx=10,
pady=10)
ttk.Label(TAB2, text="This is Tab 2").grid(column=0, row=0, padx=10,
pady=10)

#Calling Main()
window.mainloop()

#Source:
https://djangocentral.com/creating-tabbed-widget-with-python-for-gui-appl

Figure 25 Usinng tKinter to create a tabbed environment

Terminology:

Window -This term has different meanings in different contexts, but in general it
refers to a rectangular area somewhere on your display screen.

Top-level window -A window that exists independently on your screen. It will be


decorated with the standard frame and controls for your system's desktop
manager. You can move it around on your desktop. You can generally resize it,
although your application can prevent this

Widget -The generic term for any of the building blocks that make up an
application in a graphical user interface.
Examples of widgets: buttons, radiobuttons, text fields, frames, and text labels.

Frame -In Tkinter, the Frame widget is the basic unit of organization for complex
layouts. A frame is a rectangular area that can contain other widgets.

child, parent - When any widget is created, a parent-child relationship is created.


For example, if you place a text label inside a frame, the frame is the parent of the
label.
Local and Global Variables

Resources:
Variable Scope – CIRCLE tutorial
https://cscircles.cemc.uwaterloo.ca/11b-how-functions-work/
Python Guru – Functions - http://thepythonguru.com/python-functions/
Python programming language – Global variables -
https://pythonprogramminglanguage.com/global-variables/

Purpose:

To develop understanding of local and global variables


To further develop skills in using Tkinter to develop GUI

A global variable is one that is defined outside of a function


A local variable is one that is defined within a function
A global variable can be accessed by any function within the program.
A local variable can only be used within the function it is named in

Learning Activity: A Simple Calculator in a GUI


This calculator will allow the user to enter two numbers and then select the operation
to be performed. The list of operations is simple - +, -, * and / .
Create the program using the code below.l

Figure 26. A Simple Gui Calculator


from Tkinter import *

#set global variables

operator=''

#functions
def set_A():
global operator
operator='A'

def set_S():
global operator
operator='S'

def set_M():
global operator
operator='M'

def set_D():
global operator
operator='D'

def evaluate():
number1 = float(textbox1.get())
number2 = float(textbox2.get())
textbox_ans.delete(0.0 , END)
if operator == 'A':
textbox_ans.insert(END , number1+number2)
elif operator =='S':
textbox_ans.insert(END , number1-number2)
elif operator =='M':
textbox_ans.insert(END , number1*number2)
elif operator =='D':
textbox_ans.insert(END , number1/number2)
else:
textbox_ans.insert(END , 'incorrect operator')

#Gui development
window = Tk()
window.title('GUI Calculator')

#labels for instructions


label1 = Label(window , text='First Number: ').grid(row=0 , column=0, columnspan=2
, sticky=W)
label2 = Label(window , text='Second Number: ').grid(row=0 , column=2 , sticky=W)
label3 = Label(window , text='Answer: ').grid(row=3 , column=2 , sticky=W)
#Textboxes for number entry
textbox1 = Entry(window, width = 10)
textbox1.grid(row = 1 , column = 0 , columnspan = 2 , padx=(0,5) , sticky=W)
textbox2 = Entry(window, width = 10)
textbox2.grid(row = 1 , column = 2 , sticky=W)

#Answer Box
textbox_ans = Text(window , width = 14, height = 1, bg='light green')
textbox_ans.grid(row = 4, column=2 , sticky=W)

#Buttons
button_add = Button(window, text='+', width=3, command=set_A)
button_add.grid(row=2 , column=0)
button_subtract = Button(window, text='-', width=3, command=set_S)
button_subtract.grid(row=2 , column=1)
button_multiply = Button(window, text='*', width=3, command=set_M)
button_multiply.grid(row=3 , column=0)
button_divide = Button(window, text='/', width=3, command=set_D)
button_divide.grid(row=3 , column=1)
button_equals = Button(window, text='=', width=3, command=evaluate)
button_equals.grid(row=4 , column=0)

window.mainloop()

Extension – add in the quit button

How could you add in the quit button to exit the program.
In the previous section we worked with radio buttons and added in a quit button to
exit the program – adapt the code to include the quit button on the right hand side of
the window at the bottom

quit_button = Button(window, text='Quit', width = 10 ,


command=window.destroy)
quit_button.pack(side=RIGHT)
quit_button.grid(row = 8 , column = 0)

Terminology:
Sort and Search
Resources:
Selection Sort
http://courses.cs.vt.edu/~csonline/Algorithms/Lessons/SimpleCardSort/index.html
http://courses.cs.vt.edu/~csonline/Algorithms/Lessons/SortingAlgorithms/index.html
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html
https://en.wikipedia.org/wiki/Selection_sort

Quick Sort
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheQuickSort.html
https://en.wikipedia.org/wiki/Quicksort
http://www.cosc.canterbury.ac.nz/mukundan/dsal/QSort.html
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheQuickSort.html

Insertion Sort
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheInsertionSort.html
https://en.wikipedia.org/wiki/Insertion_sort

Bubble Sort
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html
https://en.wikipedia.org/wiki/Bubble_sort

Merge Sort
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html
https://en.wikipedia.org/wiki/Merge_sort

Sequential or Linier Search


http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSequentialSearch.html

http://www.sorting-algorithms.com/
General resources
https://djangocentral.com/python/

Purpose:

To extend our understanding of searching and sorting


To understand and program:
● selection sort

Learning Activity:

Selection Sort

A selection sort is a sorting mechanism that compares each item against all other
items to sort. This can be time consuming since you must compare each object
against each other. So if we have 8 objects there are:

7 + 6 + 5 + 4 + 3 + 2 + 1 28 Comparisons

So for nObjects
1 + 2 + 3 + 4 +… n-1 = n(n-1)

Now try this yourself

def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location

temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp

alist = [54,26,93,17,77,31,44,55,20,17,43,59,21,45,0,110,83,1,4,56]
selectionSort(alist)
print(alist)

Figure 27. Selection Sort.

Here is a second selection sort program

# Selection Sorting function

#1: Select the minimum element of the list and swap it with the first element
#2: In every comparison, if any element is found smaller than the selected
element, then both are swapped.
#3: Repeat the same procedure with next element in the list until list is sorted.
def selection_sort(l):

for start in range(len(l)):


min_pos = start

for i in range(start, len(l)):


if l[i] < l[min_pos]:
min_pos = i
# swap values
(l[start], l[min_pos]) = (l[min_pos], l[start])

# Test input
l = [54, 26, 93, 17, 77, 31, 44, 55, 20]
selection_sort(l)
print(l)

#source: https://djangocentral.com/selection-sort-in-python/

Quick Sort
This is an example of recursion. The Quick sort starts by selecting a value, called the
PIVOT VALUE. This is often the first item on the list.

Then partition re-order the list or array so elements with a lesser value are to one
side and with a higher value are to the other side. This is called the partition
operation.

Recursively apply the above steps to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values.

Steps are:
1. Pick a Pivot value
2. Partition (Sort value to be greater or lesser than pivot)
3. Repeat in sub array of smaller values and sub array of greater values

Try this out:

Figure 28. QuickSort

def quickSort(alist):
quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):
if first<last:

splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):
pivotvalue = alist[first]

leftmark = first+1
rightmark = last

done = False
while not done:

while leftmark <= rightmark and alist[leftmark] <= pivotvalue:


leftmark = leftmark + 1

while alist[rightmark] >= pivotvalue and rightmark >= leftmark:


rightmark = rightmark -1

if rightmark < leftmark:


done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp

temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp

return rightmark

alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)

Insertion sort
The Insertion sort takes an item and inserts it into the correct position in the growing
sorted list. It repeats this process until there are no items left

Try this out…


Figure 29. Insertion Sort

def insertionSort(alist):
for index in range(1,len(alist)):

currentvalue = alist[index]
position = index

while position>0 and alist[position-1]>currentvalue:


alist[position]=alist[position-1]
position = position-1

alist[position]=currentvalue

alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

A second insertion sort program

#elements are compared and smaller element is placed on the left


#for each iteration element from the unsorted list is inserted at the appropriate
position in the sorted part.
#Process is repeated until the whole list is completed

def insertion_sort(seq):

for slice_end in range(len(seq)):


pos = slice_end
# inserting elements at correct position
while pos > 0 and seq[pos] < seq[pos - 1]:
(seq[pos], seq[pos - 1]) = (seq[pos - 1], seq[pos])
pos = pos - 1
# test input
l = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insertion_sort(l)
print(l)

#source: https://djangocentral.com/insertion-sort-in-python/

Bubble Sort

Bubble sort, (also called the sinking sort) is a sorting algorithm that repeatedly
works through the list to be sorted. It compares each pair of adjacent items and
rearranges or swaps them if they are in the wrong order. The process repeats until
no more passes are required.

Try this out:


def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp

alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)

Merge Sort
The merge sort works as follows:

1. Divide the unsorted list into sublists or subsets


2. Repeat the process until you get a series of single values – this is a sorted list
3. Repeatedly Merge sublists to produce new sorted sublists until there is only 1
sublist remaining. This will be the sorted list.

For example

Base list 38,21,52,7

First division 38, 21 52, 7

Second division 38 21 52 7

First merge (in order) 21, 38 7, 52

Final merge (ordered) 7, 21, 38, 52


Figure 30. Merge Sort

Try it out:
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

mergeSort(lefthalf)
mergeSort(righthalf)

i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1

while i < len(lefthalf):


alist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

Linier Search or Sequential Search

In the Linier Search we start at the first position in the array and compare the value
to the value being searched for. If the values do not match we compare the next
value.

Try this out

def sequentialSearch(alist, item):


pos = 0
found = False

while pos < len(alist) and not found:


if alist[pos] == item:
found = True
else:
pos = pos+1

return found

testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]


print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
Binary Search

The search starts with the array being sorted into order (You can select your sorting
method)
Then select the middle value. If the value is greater than or less than the middle
value then discard or ignore the irrelevant ½.
Repeat the process until the value being searched for matches a value in the list or
doesn’t match.

Try this out


def binarySearch(alist, item):
first = 0
last = len(alist)-1
found = False

while first<=last and not found:


midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1

return found

testlist = [0, 1, 2, 3, 8, 13, 17, 19, 32, 42,]


print(binarySearch(testlist, 3))
print(binarySearch(testlist, 19))
Terminology:
Read and write to files
Resources:
https://www.pythontutorial.net/python-basics/python-read-text-file/

W3 Schools
https://www.w3schools.com/python/python_file_handling.asp
https://www.w3schools.com/python/python_file_open.asp
https://www.w3schools.com/python/python_file_write.asp
https://www.w3schools.com/python/python_file_remove.asp

Purpose:

To extend load and save information to external files


To manipulate data stored in external text based files
Learning Activity:

Modes

Mode Description
“r” Open the file for reading text
“w” Open file for writing text
“a” Open file for appending text

In this example we have a text file called dog_breeds.txt. This file is saved in the
same location at the .py files that manipulate it.
The initial content of the file is:

(Please note: the content is irrelevant, it just needs to have something there to read)

Read file

#read from file

dogs = open("dog_breeds.txt", "r")


#select file to open and the mode to open it in

print(dogs.read())
#display the content on the screen

dogs.close()
#close the file
The output looks like this

To read a single ine in the file we can use a similar process

#read from file - line wise

dogs = open("dog_breeds.txt", "r")


#select file to open and the mode to open it in

print(dogs.readline())
#display the content on the screen
#you can read more lines by repeating the readline code

dogs.close()
#close the file

The output is the first line of the text file

Try repeating the readline() on a new line to read more content.

Try this:

dogs = open("dog_breeds.txt", "r")


for x in dogs:
print(x)

Write to file

# Writing to a file

dogs = open("dog_breeds.txt", "w")


#opens the file

dogs.write("pig dog \n")


dogs.write("cattle dog \n")
dogs.write("sheep dog \n")
dogs.write("german Shepherd \n")
dogs.write("hound dog \n")
dogs.write("large dog \n")
dogs.write("small dog \n")
#writes the content on new lines

dogs.close()
#closes the file

The output of the file looks like this:

It is important to note that this overwrites the content of the file. If we want to add
material to a file we have to use the append mode.
Add data to the file

Try this
#appending data to a file

dogs = open("dog_breeds.txt", "a")


#open the file in append mode

dogs.write("greyhound \n")
dogs.close()

dogs = open("dog_breeds.txt", "r")


print(dogs.read())
#reopens the file in read mode and prints the content

dogs.close()

the output looks like this:

Creating a new file


This is a new mode to add to the existing ones
Mode Description
“r” Open the file for reading text
“w” Open file for writing text
“a” Open file for appending text
“x” Create a file (will give an error message
if the file is already in existence)
Please note: both modes “a” and “w” will create files if they do not already exist.

Try this:

#Creating a file and adding data to a file

cats = open("cat_breeds.txt", "w")


#open the file in append mode

cats.write("smelly cat,\n")
cats.write("ugly cat,\n")
cats.write("silly cat,\n")
cats.write("mangy cat.\n")
cats.writelines(["big cat \n", "medium size but smelly cat \n", "small cat \n",
"dogs under knee hieght"])
cats.close()

cats = open("cat_breeds.txt", "r")


print(cats.read())
#reopens the file in read mode and prints the content

cats.close()
#closes the cat file

Again the output looks like this:


What dates is it?
Resources:
https://docs.python.org/3/library/datetime.html

W3 Schools
https://www.w3schools.com/python/python_datetime.asp

Purpose:

To import the datetime module


To include current date and time in the products being developed
Learning Activity:

Date & time now!

The first version of date and time to try is very accurate and contains information
down to the millisecond. This is very useful for data collecting but might not be as
useful for day to day use.

Try this

#date and time

import datetime

x = datetime.datetime.now()

print(x)

strftime method

The string format method allows us to select the elements of a date and time to
present.

Here are some of the variation that might be useful:

#date and time

import datetime

x = datetime.datetime.now()

print(x)
print(x.year)
print(x.strftime("%a"))
print(x.strftime("%A"))
#weekday formats - short and long formats
print(x.strftime("%b"))
print(x.strftime("%B"))
print(x.strftime("%m"))
#month formats short and long form and number
print(x.strftime("%y"))
print(x.strftime("%Y"))
#year formats short and full year
print(x.strftime("%H"))
print(x.strftime("%I"))
print(x.strftime("%M"))
print(x.strftime("%S"))
print(x.strftime("%p"))
#Time formats - 24 hour format, 12 hour format, minutes, seconds , Am/pm
print(x.strftime("%x"))
print(x.strftime("%X"))
#local version of date and time

Bringing it together Log file time.

Applications frequently have a log file that records when a user or the application
undertakes an action. These are often recording in text files or in more complex
versions in a database.

This example uses the datetime module to provide the date and time but when
writing to the log file the format must be a string. So the strftime or string format time
is used to take the datetime formatted data and convert it to a string.

Try this out:

#log file
import datetime
currenttime = datetime.datetime.now()
# Import datetime module and set date and time
print ("writing to a log file")
user = input("what is your name? ")
#Collect user information
logging = open("logfile.txt", "a")

logging.write("\n")
logging.write(user)
logging.write(" - ")
logging.write(currenttime.strftime("%a"))
logging.write(currenttime.strftime("%d"))
logging.write(currenttime.strftime("%b"))
logging.write(" - ")
logging.write(currenttime.strftime("%H"))
logging.write(currenttime.strftime("%M"))

logging.close()
Extension matplotlib
Resources:

https://matplotlib.org/
https://matplotlib.org/stable/users/index.html
https://numpy.org

W3 Schools
https://www.w3schools.com/python/matplotlib_intro.asp

Purpose:

To visualise data using the matplotlib module

Matplotlib is a module that can create visualisation of data in python. The module
needs to be installed on your computer.

To install the module go ensure you have pip installed and use this to install the
module

Use this command (in terminal on a mac or from the command prompt in a windows
based machine)

Pip install matplotlib

You can check the version of Matplotlib by using the following short
program/statements

import matplotlib
print(matplotlib.__version__)

Learning Activity: Plot and array of points – line graph

This exercise plots a series of points on a line graph

import matplotlib.pyplot as plt


import numpy as np
#import the two modules needed for this program
xpoints = np.array([0,3, 6, 9, 12, 15])
ypoints = np.array([0, 125, 250, 500, 1000, 2000])
#these are the arrays of points on the X and Y axis
plt.plot(xpoints, ypoints)
#plot the graph points
plt.show()
#show the graph

The finished graph looks like this

Figure 31 Using matplotlib to plot an array

Add a little style

You can alter the appearance of your graph by changing the line style and the line
color. We can also label the axis and add markers for each data point.

Use the existing code and change the plt.plot to this.

plt.plot(xpoints, ypoints, linestyle = 'dashed', color = 'green', marker=’*’)


#plot the graph points with colour and linestyle

plt.xlabel("Days of incubation")
plt.ylabel("Colony Growth")

You can also use hex colour values and colour the markers using mec = ‘#aaff00’
and adjust the size of the marker with ms=’5’. ms = marker size
plt.plot(xpoints, ypoints, linestyle = 'dashed', color = '#A2B4C6', marker='*',
mec = ‘#aaff00’, linewidth=’5’, ms=’10’)

Figure 32 Adding labels line style, point markers and colour to the graph

Line style Marker style


‘solid’ is = ‘-‘ ‘o’ Circle
‘dotted’ is = ‘:‘ ‘*’ Star
‘dashed’ is=’--' ‘s’ Square
‘dashdot’ is=’-.’ ‘D’ Diamond
‘none’ Is=’or’ ‘H’ Hexagon
‘>’ Triangle right
‘<’ Triangle left

Finally we can add a title to the graph using:

Plt.title(“graph title”)
Visualise your results

Try this code. This plots a maths formula y = x2

import matplotlib.pyplot as plt

pltX = []
pltY = []

for x in range(0,100):
pltX.append(x)
pltY.append(x*x)

plt.plot(pltX,pltY)
plt.title("Plot X vs X squared", loc=’left’)
plt.ylabel("x-squared")
plt.xlabel("x")
plt.grid(color='red', linestyle='--', linewidth=0.5)
plt.show()

Figure 33. using the math modules to plot a graph


Plotting several datasets on one graph
Its easy to plot multiple datasets on the same graph. It does help to change the
appearance of the lines to ensure they are discrete data sets.
Try this: (please note much of this is repeated code – reuse your last code)

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0,3, 6, 9, 12, 15])


ypoints = np.array([0, 125, 250, 500, 1000, 2000])
#these are the arrays of points on the X and Y axis – first line

plt.plot(xpoints, ypoints, linestyle = 'dashed', color = '#A2B4C6', marker='o',


mec='#00ff00', linewidth='2', ms='10')
#formats the first line

xpoints = np.array([0,1, 2, 3, 4, 5])


ypoints = np.array([0, 125, 250, 500, 1000, 2000])
#second line

plt.plot(xpoints, ypoints, linestyle = 'dashed', color = '#ff0000', marker='o',


mec='#0000ff', linewidth='2', ms='10')
#formats the second line

plt.title("Colony growth over time", loc='left')


plt.xlabel("Days of incubation")
plt.ylabel("Colony Growth")
plt.grid(color='red', linestyle='--', linewidth=0.5)
plt.show()

=
Figure 34 Plotting two lines on the same graph.
Scatter plots

Another function of the matplotlib is scatter plots or scattergrams. Much of the


formatting from the line graph is still valid in this example.. Try this out:

#scatterplots
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,9,2,3,0,1, 7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86,72, 21,99,56, 67])

plt.scatter(x, y)

plt.title("Scatterplot", loc='left')
plt.xlabel("X-axis values")
plt.ylabel("Y-axis values")
plt.grid(color='green', linestyle='--', linewidth=0.5)
plt.show()

Figure 35 A scattergram of a single dataset


Plotting two or more datasets in the same scatter plot
Having two datasets plotted in the same plot allows the opportunity for useful
comparisons. Note: s is the size of the points & Alpha is the transparency of the dot

import matplotlib.pyplot as plt


import numpy as np

#site one, distribution and frequency of limpets on transect line


x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])
y = np.array([0,0,0,1,11,86,103,87,20,0,0,1,3])
plt.scatter(x, y, color='blue', s=45, alpha=0.5)
#site two, distribution and frequency of oyster on transect line
x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])
y = np.array([0,0,0,0,0,0,5,95,94,100,79,112,9])
plt.scatter(x, y, color='red', s=10 )

plt.title("Distribution of Oyster and Limpets on rock platform", loc='left')


plt.xlabel("Transect position (m)")
plt.ylabel("Frequency per m2")
plt.grid(color='green', linestyle='--', linewidth=0.5)
plt.show()

Figure 36 Scatter plot with two datasets


Bar Graphs – vertical and Horizontal

Vertical bar graph


This graph also uses an array to colour each bar a different colour.
Note: In plt.bar the width refers to the width of the bars. Default height for width is 0.8

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["test 1", "Assignment", "test 2", "practical exam", "exam",


"exam2"])
y = np.array([65, 20, 71, 25, 80, 75])
colours = np.array(["red", "green", "blue", "purple"])

plt.bar(x, y, color=colours, width=0.5)


plt.title("Computer science grades", loc='left')
plt.xlabel("Assessment")
plt.ylabel("Average score as %")
plt.grid(color='blue', linestyle='--', linewidth=0.5)
plt.show()

Figure 37 Vertical bar graph using an array for colours


Horizontal bar graph

The Horizontal plot uses essentially the same code as the vertical bar graph with two
exceptions:
● plt.barh instead of plt.bar
● in the attributes of the horizontal bar use height instead of width for the size of
the bar. The default height for lines is 0.8

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["test 1", "Assignment", "test 2", "prac exam", "exam", "exam2"])


y = np.array([65, 20, 71, 25, 80, 75])
colours = np.array(["yellow", "black", "blue", "orange"])

plt.barh(x, y, color=colours, height=0.5)


plt.title("Computer science grades", loc='left')
plt.ylabel("Assessment")
plt.xlabel("Average score as %")
plt.grid(color='blue', linestyle='--', linewidth=0.5)
plt.show()

Figure 38 Horizontal bargraph.


Pie Graphs

Pie graphs are a popular visualization tool.


Note: startangle is where the graph starts – the graph below is 180o. Explode
pushes a segment or selection of segments a defined distance out from the graph,
Shadow is True or False

#pie graphs

import matplotlib.pyplot as plt


import numpy as np

y = np.array([20, 15, 25, 25, 15])


key = ["Ford","Mazda","Holden","Suzuki","BMW"]
graphexplode = [0, 0 , 0.2, 0, 0]
graphcolours = ["red","yellow","pink","blue","orange"]

plt.pie(y, labels = key, startangle = 180, explode = graphexplode, shadow =


True, colors = graphcolours)
plt.title("Popular car manufacturers in Queensland")
plt.show()

Figure 39 A Pie graph with one element exploded out. Colours are from an array and there is a shadow added to
the graph.
Add a Legend
Reuse the code above and lets add in the legend and then position it way from the
graph. We can also colour the background (called facecolor) and edgeor border of
the legend (called edgecolor). Shadows can also be added to the legend

Figure 40 pie graph with a legend. Legends have their own titles and can be positioned on the graph.

Code snippet – use previous code and modify by adding the plt.legend element
(highlighted)

plt.pie(y, labels = key, startangle = 180, explode = graphexplode, shadow =


True, colors = graphcolours)
plt.title("Popular car manufacturers in Queensland")
plt.legend(key, title = "Manufacturers", loc = 4, bbox_to_anchor=(0.8, -0.1,
0.5,0.5), shadow = True, facecolor = 'grey', edgecolor = 'red')
plt.show()
loc
loc refers to location. Location can be written as a string or as a location code:

‘upper left’ ‘upper center’ ‘upper right’


2 9 1
‘center left’ ‘center’ ‘center right’ ‘right’
6 10 7 5
‘lower left ‘lower center’ ‘lower right’
3 8 4
best position
0

bbox_to_anchor
bbox_to_anchor is used to position the legend in conjunction with loc.
The values are (x, y, width, height)
plt.legend(key, title = "Manufacturers", loc = 4, bbox_to_anchor=(0.8, -0.1,
0.5,0.5))

You can allow python to size the box and just specify the x and y position
bbox_to_anchor=(0.8, -0.1)

Histogram

Histograms show the frequency of different values. The x axis has the value and the
y axis has the frequency of the value.

import matplotlib.pyplot as plt


import numpy as np

x=np.array([1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,4,5,6,7,8,9,0,1,1,1,2,3,4,5,5,5,6,6,7,6,
6,7,7,8,9,8,7,6,6,6,1,4,8,5,1,3,5,5,5,4,8,4,2,6,5,9,5,4,7,1,2,5,3,3,3,3,3,3,3,3,3,
3,3,4,9,8,6,4,3,2,5,9,8,4,2,1,5,8,4,6,6,6,9,5,9,5,8,5,4,5,4,5,4,2,5,8,1,2,1,5,6,1,
7,1,5,3,8,5,4,1,2,1,5,1,5,1,4,1,9,1,9,2,2,2,2,4,5,6,4,5,6,4,5,6,8,9,5,6,9,5,6,9,8,
6,5,9,8,6,5,9,8,6,5,9,8,6,5,9,8,6,5,4,7,8,9,7,8,9,7,8,9,7,8,9,7,8,8,7,7])

plt.hist(x, color="grey", alpha=0.8)

plt.title("Random value distribution", loc='left')


plt.xlabel("Value")
plt.ylabel("Frequency")
plt.grid(color='red', linestyle='--', linewidth=0.5)
plt.show()
Figure 41 Histogram of frequency of values.

You might also like