Python For Computer Science
Python For Computer Science
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
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
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.
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
Terminology:
Operating system: the software that supports a computer's basic functions, such
as scheduling tasks, executing applications, and controlling peripherals
For example
student_names
i=i+1
print(“computational thinking”)
Purpose:
This first tutorial will start with printing text on the screen and developing an
understanding or syntax, errors and debugging.
Learning Activity:
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.
If you are using a text editor save the file with the file extension .py – for example
print.py
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")
We can alter the appearance of the input by using the following methods:
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')
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!")
So we can make it more efficient by defining another function. This one is called
happy
def happy():
print("Happy birthday to you!")
def happy():
print("Happy birthday to you!")
■ def singFred():
happy()
happy()
print("Happy birthday, dear Fred...")
happy()
■ >>> 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()
■ def main():
singFred()
print()
singLucy()
def happy():
print("Happy birthday to you!")
def sing(person):
happy()
happy()
print("Happy birthday, dear", person + ".“)
happy()
>>> 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
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.
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.
Speed Calculator
uphillDistance = 4
print('Uphill Distance =\t', uphillDistance)
uphillTime = 72
print('Uphill Time =\t', uphillTime)
Speed = Distance/Time
Speed = float(Speed)
print('Speed = Distance/Time')
print(Speed,'=',Distance,' / ', Time)
speed()
#sets variables.
a=9
b = 14
c=3
d=6
#prints variables.
Power function
Using pow(x, Y) returns x to the power of y or Xy
#Square root
import math
d = math.sqrt(64)
print("the square root of 64 is ", d )
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
#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('\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.
a=5
b=7
c=2
d=9
e = 17
f = 12
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
import math
def area_of_circle(r):
a = r**2 * math.pi
return a
print (area_of_circle(1))
Extension:
import math
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 : "))
calcCircle()
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.
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.
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
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 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.
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.
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
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')
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.
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
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
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
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.
if studentname.isalpha() == False:
print("please enter your name")
else:
print("next statement or task on completing the test")
#isnumeric() returns true if only numbers are in the string and false is one or more
characters are not numeric
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
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")
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.
now = datetime.now()
response = ""
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
#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('\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')
Another one
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 ')
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:
Usually F0 = 0 and F1 = 1
Here are two variations of code used to generate the Fibonacci numbers. Use this
code to output the first 21 number in the sequence.
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
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
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%
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
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%
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
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.
print(random.randint(1, 100))
#Random range(start value, stop value)
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.
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.
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.
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:
#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')
if a == True or b == True:
print('at least one input is true')
else:
print('both inputs are false')
#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)
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.
Lists or Arrays have an index which starts with 0 and the data is associated with this
index value.
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.
#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
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]]
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')
This activity is an iterative process that will after several iterations produce a multi
dimensional array.
Iteration one
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)
volume()
Iteration two
Index 0 1 2 3 4
0 7 14 3 101 17
1 5 6 3 3 12
#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)
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()).
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 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)
#insert items
thirdlist = ["teachers", "students", "alumni", "support staff", "admin staff"]
thirdlist.insert(2, "other people")
print(thirdlist)
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
#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')
#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')
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']
]
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']
]
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.
# 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)
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)
def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum
print(listsum([1,3,5,7,9]))
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.
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"]
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 #
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')
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.
Set is a restricted list of unique values, so you can not repeat the values. A set
uses {} brackets
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
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.
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
window = Tk()
window.title('colours and frames')
window.mainloop()
#calculate multiples
#imports GUI module
from tkinter import *
textbox_output.delete(0.0, END)
#mandatory statement
window.mainloop()
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 = True
number=int(input('Enter your number: '))
counter=2
while True:
modulus = number % counter
if modulus == 0:
prime = False
counter = counter + 1
if prime == True:
print('your number is a prime number')
else:
print('your number is not a prime number')
Develop the code below, add descriptive comments and test the application
against the prime number table above.
def prime():
modulus_counter=0
number=int(textbox_input.get())
textbox_output.delete(0.0, END)
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')
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.
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()
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.
window = Tk()
window.title('Message box Inputs')
frame = Frame(window)
entry = Entry(frame)
def dialog():
box.showinfo('Greeting' , 'Welcome ' +entry.get())
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.
Develop this solution, adjust the list items and the colours to suit. Add comments.
window = Tk()
window.title('Message box List Box')
frame = Frame(window)
listbox = Listbox(frame)
def dialog():
box.showinfo('Selection' , 'your choice ' + listbox.get( listbox.curselection()
))
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.
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.
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.
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’.
Enter this code, add suitable comments. Some of the code can be recycled from
previous learning activities.
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())
window.mainloop()
window = Tk()
window.title('Check Box')
frame = Frame(window)
var_1=IntVar()
var_2=IntVar()
var_3=IntVar()
var_4=IntVar()
var_5=IntVar()
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)
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')
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
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
def change_year():
year_label.config(text = year.get())
window = Tk()
window.title('Combining several elements in a GUI')
year = StringVar()
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
#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")
#Calling Main()
window.mainloop()
#Source:
https://djangocentral.com/creating-tabbed-widget-with-python-for-gui-appl
Terminology:
Window -This term has different meanings in different contexts, but in general it
refers to a rectangular area somewhere on your display screen.
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.
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:
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')
#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()
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
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
http://www.sorting-algorithms.com/
General resources
https://djangocentral.com/python/
Purpose:
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)
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)
#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):
# 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
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:
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
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
def insertion_sort(seq):
#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.
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)
Merge Sort
The merge sort works as follows:
For example
Second division 38 21 52 7
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
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
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.
return found
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.
return found
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:
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
print(dogs.read())
#display the content on the screen
dogs.close()
#close the file
The output looks like this
print(dogs.readline())
#display the content on the screen
#you can read more lines by repeating the readline code
dogs.close()
#close the file
Try this:
Write to file
# Writing to a file
dogs.close()
#closes the file
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.write("greyhound \n")
dogs.close()
dogs.close()
Try this:
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.close()
#closes the cat file
W3 Schools
https://www.w3schools.com/python/python_datetime.asp
Purpose:
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
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.
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
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.
#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:
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)
You can check the version of Matplotlib by using the following short
program/statements
import matplotlib
print(matplotlib.__version__)
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.
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
Plt.title(“graph title”)
Visualise your results
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 34 Plotting two lines on the same graph.
Scatter plots
#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()
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
#pie graphs
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)
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.
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])