ICTPRG549 - Learner Resource - Topic 3
ICTPRG549 - Learner Resource - Topic 3
Learner Resource
Disclaimer Statement:
PLEASE NOTE that by clicking on a link you may be directed to a third party’s site.
You should respect the intellectual property on that site. You may be leaving the Melbourne Polytechnic website.
Melbourne Polytechnic does not endorse a linked site or guarantee the accuracy or currency of any information
contained on the third party linked site.
Acknowledgments
National training packages attributed as ‘© Commonwealth of Australia 2013’
Training packages are copied and communicated under Creative Commons
Attribution-Non Derivative 3.0 Australia (CC BY-ND 3.0 AUS) license.
Images/illustrations
All images are individually attributed within document.
Page 2 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
Contents
Unit Descriptor ........................................................................................................................................ 5
Application .......................................................................................................................................... 5
Elements and performance criteria .................................................................................................... 6
Required Skills and Knowledge................................................................................................................ 7
Introduction............................................................................................................................................. 8
About this Learner Resource ............................................................................................................... 8
Glossary ................................................................................................................................................... 9
Topic 1: Introduction to Object-Oriented Programming ....................................................................... 10
1.1 Software Requirements Specification ......................................................................................... 10
1.2 Computer Programs .................................................................................................................... 12
Interpreters................................................................................................................................... 12
Compilers ...................................................................................................................................... 12
Expressions and statements ......................................................................................................... 13
Numbers ....................................................................................................................................... 14
Truth and Falsity – Boolean Values............................................................................................... 15
Operator Description .................................................................................................................... 15
Types of Value or Expression ......................................................................................................... 16
Common Problems ........................................................................................................................ 16
Binary Files.................................................................................................................................... 18
Make Utility .................................................................................................................................. 18
Stability Testing ............................................................................................................................ 19
Topic 2: Graphical User Interfaces ......................................................................................................... 21
2.1 Tkinter ......................................................................................................................................... 24
Tkinter Widgets ............................................................................................................................ 24
Interaction Widgets (Controls) ..................................................................................................... 24
Layout Widgets ............................................................................................................................. 29
Topic 3: Loops and Data Storage ........................................................................................................... 32
3.1 Loops ........................................................................................................................................... 32
While Loop.................................................................................................................................... 33
Python “Break” and “Continue” Statements ................................................................................ 34
“Else” Clause ................................................................................................................................. 36
Page 3 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
3.2 Data Storage Lists........................................................................................................................ 39
Indexing Lists ................................................................................................................................ 40
Accessing List Content .................................................................................................................. 41
Len() Function................................................................................................................................ 41
Removing Elements from a List .................................................................................................... 41
Topic 4: Divide Multiple Source Code into Functions ............................................................................ 43
4.1 Functions ..................................................................................................................................... 43
Source of Functions ....................................................................................................................... 44
Creating a Function....................................................................................................................... 44
Parameterised Functions .............................................................................................................. 45
4.2 Keyword Argument Passing ........................................................................................................ 48
4.3 Return Instruction ....................................................................................................................... 49
Return Without an Expression ...................................................................................................... 49
Return With an Expression ........................................................................................................... 50
4.4 Python and MySQL ...................................................................................................................... 51
Insert Values into MySQL Table .................................................................................................... 56
Python MySQL Order By (Sort) ...................................................................................................... 58
Order By DESC............................................................................................................................... 58
4.5 Database Transactions ................................................................................................................ 59
4.6 Testing and Debugging ................................................................................................................ 59
References ............................................................................................................................................. 61
Page 4 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
Unit Descriptor
Application
This unit describes the skills and knowledge required to undertake intermediate level programming
tasks using an object-oriented programming language.
It applies to software developers in a variety of fields who are required to produce programs in
object-oriented languages.
No licensing, legislative or certification requirements apply to this unit at the time of publication.
1 Build applications
1.1 Determine and document program requirements according to object-orientated
programming specifications
1.2 Divide multiple source-code files into logical units and packages and collect data in internal
storage
1.3 Implement internal data-sorting and searching facilities according to object-orientated
programming specifications
1.4 Employ integrated-development environment facilities and make files to automate program
building
1.5 Use facilities in specific language for persisting objects to binary files and confirm program
stability
The candidate must demonstrate the ability to complete the tasks outlined in the elements,
performance criteria and foundation skills of this unit, including evidence of the ability to:
• design and build at least one simple application program from a problem scenario and
program specification.
The candidate must be able to demonstrate knowledge to complete the tasks outlined in the
elements, performance criteria and foundation skills of this unit, including knowledge of:
Page 7 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
Topic 3: Loops and Data Storage
3.1 Loops
Iteration means executing the same block of code over and over, potentially many times. A
programming structure that implements iteration is called a loop.
Page 32 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
In programming, there are two types of iteration, indefinite and definite:
1. With indefinite iteration, the number of times the loop is executed isn’t specified explicitly
in advance. Rather, the designated block is executed repeatedly as long as some condition is
met.
2. With definite iteration, the number of times the designated block will be executed is
specified explicitly at the time the loop starts.
WHILE LOOP
Let’s see how Python’s while statement is used to construct loops. We’ll start simple and embellish
as we go.
while <expr>:
<statement(s)>
<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the
loop. This is denoted with indentation, just as in an if statement.
The controlling expression, <expr>, typically involves one or more variables that are initialised prior
to starting the loop and then modified somewhere in the loop body.
When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop
body is executed. Then <expr> is checked again, and if still true, the body is executed again. This
continues until <expr> becomes false, at which point program execution proceeds to the first
statement beyond the loop body.
>>> n = 5
2>>> while n > 0:
3... n -= 1
4... print(n)
In this example:
• n is initially 5. The expression in the while statement header on line 2 is n > 0, which is true,
so the loop body executes. Inside the loop body on line 3, n is decremented by 1 to 4, and
then printed.
• When the body of the loop has finished, program execution returns to the top of the loop at
line 2, and the expression is evaluated again. It is still true, so the body executes again,
and 3 is printed.
Page 33 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
• This continues until n becomes 0. At that point, when the expression is tested, it is false, and
the loop terminates. Execution would resume at the first statement following the loop body,
but there isn’t one in this case.
Note that the controlling expression of the while loop is tested first, before anything else happens. If
it’s false to start with, the loop body will never be executed at all:
>>> n = 0
>>> while n > 0:
... n -= 1
... print(n)
...
In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is
already false, so the loop body never executes.
Here’s another while loop involving a list, rather than a numeric comparison:
When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty.
In this example, a is true as long as it has elements in it. Once all the items have been removed with
the .pop() method and the list is empty, a is false, and the loop terminates.
• The Python break statement immediately terminates a loop entirely. Program execution
proceeds to the first statement following the loop body.
• The Python continue statement immediately terminates the current loop iteration.
Execution jumps to the top of the loop, and the controlling expression is re-evaluated to
determine whether the loop will execute again or terminate.
Page 34 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
The distinction between break and continue is demonstrated in the following diagram:
While <expr>:
<statement>
<statement>
break
<statement>
<statement>
continue
<statement>
<statement>
<statement>
Here’s a script file called break.py that demonstrates the break statement:
1n = 5
2while n > 0:
3 n -= 1
4 if n == 2:
5 break
6 print(n)
7print('Loop ended.')
C:\Users\john\Documents>python break.py
4
3
Loop ended.
When n becomes 2, the break statement is executed. The loop is terminated completely, and
program execution jumps to the print() statement on line 7.
The next script, continue.py, is identical except for a continue statement in place of the break:
1n = 5
2while n > 0:
3 n -= 1
4 if n == 2:
5 continue
6 print(n)
7print('Loop ended.')
Page 35 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
The output of continue.py looks like this:
C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.
This time, when n is 2, the continue statement causes termination of that iteration. Thus, 2 isn’t
printed. Execution returns to the top of the loop, the condition is re-evaluated, and it is still true. The
loop resumes, terminating when n becomes 0, as previously.
“ELSE” CLAUSE
Python allows an optional else clause at the end of a while loop. This is a unique feature of Python,
not found in most other programming languages. The syntax is shown below:
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
The <additional_statement(s)> specified in the else clause will be executed when the while loop
terminates.
About now, you may be thinking, “How is that useful?” You could accomplish the same thing by
putting those statements immediately after the while loop, without the else:
while <expr>:
<statement(s)>
<additional_statement(s)>
In the latter case, without the else clause, <additional_statement(s)> will be executed after
the while loop terminates, no matter what.
When <additional_statement(s)> are placed in an else clause, they will be executed only if the loop
terminates “by exhaustion”—that is, if the loop iterates until the controlling condition becomes
false. If the loop is exited by a break statement, the else clause won’t be executed.
Page 36 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
Consider the following example:
>>> n = 5
>>> while n > 0:
... n -= 1
... print(n)
... else:
... print('Loop done.')
...
4
3
2
1
0
Loop done.
In this case, the loop repeated until the condition was exhausted: n became 0, so n > 0 became false.
As the loop lived out its natural life, so to speak, the else clause was executed. Now observe the
difference here:
>>> n = 5
>>> while n > 0:
... n -= 1
... print(n)
... if n == 2:
... break
... else:
... print('Loop done.')
...
4
3
2
This loop is terminated prematurely with break, so the else clause isn’t executed.
• Think of the header of the loop (while n > 0) as an if statement (if n > 0) that gets executed
over and over, with the else clause finally being executed when the condition becomes false.
• Think of else as though it were no break, in that the block that follows gets executed if there
wasn’t a break.
When might an else clause on a while loop be useful? One common situation is if you are searching a
list for a specific item. You can use break to exit the loop if the item is found, and the else clause can
contain code that is meant to be executed if the item isn’t found:
Page 37 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
>>> a = ['foo', 'bar', 'baz', 'qux']
>>> s = 'corge'
>>> i = 0
>>> while i < len(a):
... if a[i] == s:
... # Processing for item found
... break
... i += 1
... else:
... # Processing for item not found
... print(s, 'not found in list.')
...
corge not found in list.
Note: The code shown above is useful to illustrate the concept, but you’d actually be very unlikely to
search a list that way.
First of all, lists are usually processed with definite iteration, not a while loop. Definite iteration is
covered in the next tutorial in this series.
Secondly, Python provides built-in ways to search for an item in a list. You can use the in operator:
Source: Real Python (2021) Python while” Loops (Indefinite Iteration), John Sturz, Retrieved from:
https://realpython.com/python-while-loop/
• For loop
• While loop
• Indefinite iteration
• Definite iteration
• A Python break statement
• A Python continue statement
• Else Clause
Page 38 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
3.2 Data Storage Lists
You may have to read, store, process, and print dozens, maybe hundreds, perhaps even thousands
of numbers.
What then?
Will you have to spend long hours writing statements like the one below?
var1 = int(input())
var2 = int(input())
var3 = int(input())
var4 = int(input())
var5 = int(input())
If you don't think that this is a complicated task, then take a piece of paper and write a program
that:
You should find that you don't have enough paper to complete the task. You've learned how to
declare variables that are able to store one value at a time. Such variables are sometimes
called scalars by analogy with mathematics. All the variables you've used so far are actually scalars.
Think of how convenient it would be to declare a variable that could store more than one value. For
example, a hundred, or a thousand or even ten thousand. It would still be one and the same
variable, but very wide and capacious. Sounds appealing? Perhaps, but how would it handle such a
container full of different values? How would it choose just the one you need?
What if you could just number them? And then: give me the value number 2; assign the value
number 15; increase the value number 10000.
Let's create a variable called numbers; it's assigned with not just one number, but is filled with a list
consisting of five values (note: the list starts with an open square bracket and ends with a closed
square bracket; the space between the brackets is filled with five numbers separated by commas).
numbers=[10,5,7,2,1]
Page 39 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
Numbers is a list consisting of five values, all of them numbers. This statement creates a list of
length equal to five (as in there are five elements inside it).
The elements inside a list may have different types. Some of them may be integers, others floats.
Python has adopted a convention stating that the elements in a list are always numbered starting
from zero. This means that the item stored at the beginning of the list will have the number zero.
Since there are five elements in our list, the last of them is assigned the number four.
INDEXING LISTS
How do you change the value of a chosen element in the list?
Let's assign a new value of 111 to the first element in the list. We do it this way:
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # Printing original list content.
numbers[0] = 111
print("New list content: ", numbers) # Current list content.
And now we want the value of the fifth element to be copied to the second element:
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # Printing original list content.
numbers[0] = 111
print("\nPrevious list content:", numbers) # Printing previous list content.
The value inside the brackets which selects one element of the list is called an index, while the
operation of selecting an element from the list is known as indexing.
We're going to use the print() function to print the list content each time we make the changes. This
will help us follow each step more carefully and see what's going on after a particular list
modification.
Note: all the indices used so far are literals. Their values are fixed at runtime, but any expression can
be the index, too. This opens up lots of possibilities.
Page 40 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
ACCESSING LIST CONTENT
Each of the list's elements may be accessed separately. For example, it can be printed:
print(numbers[0]) # Accessing the list's first element.
Assuming that all of the previous operations have been completed successfully, the snippet will
send 111 to the console.
As you can see in the editor, the list may also be printed as a whole - just like here:
print(numbers) # Printing the whole list.
As you've probably noticed before, Python decorates the output in a way that suggests that all the
presented values form a list. The output from the example snippet above looks like this:
output
[111, 1, 7, 2, 1]
LEN() FUNCTION
The length of a list may vary during execution. New elements may be added to the list, while others
may be removed from it. This means that the list is a very dynamic entity.
If you want to check the list's current length, you can use a function named len() (its name comes
from length).
The function takes the list's name as an argument, and returns the number of elements currently
stored inside the list (in other words - the list's length).
Look at the last line of code in the editor, run the program and check what value it will print to the
console. Can you guess?
Page 41 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource
You can't access an element which doesn't exist - you can neither get its value nor assign it a value.
Both of these instructions will cause runtime errors now:
print(numbers[4])
numbers[4] = 1
Add the snippet above after the last line of code in the editor, run the program and check what
happens.
Note: we've removed one of the list's elements - there are only four elements in the list now. This
means that element number four doesn't exist.
Source: NetAcad, Cisco Network Academy, Programming Essentials in Python, Module 3.4 Lists
Page 42 of 61
Melbourne Polytechnic
ICTPRG549 Apply intermediate object-oriented language skills
Learner Resource