0% found this document useful (0 votes)
19 views108 pages

Programming 512 Student Guide

The document is a learner guide for the Programming 512 module at Richfield Graduate Institute of Technology, covering key programming concepts such as lists, tuples, dictionaries, object-oriented programming, GUI development, and database interfacing. It outlines the structure of the IT qualification programs, emphasizing the integration of theoretical knowledge with practical skills to prepare students for various IT roles. The guide includes learning outcomes and detailed content for each chapter, aimed at advancing students' expertise in Python programming.

Uploaded by

b4wb5s6dy5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views108 pages

Programming 512 Student Guide

The document is a learner guide for the Programming 512 module at Richfield Graduate Institute of Technology, covering key programming concepts such as lists, tuples, dictionaries, object-oriented programming, GUI development, and database interfacing. It outlines the structure of the IT qualification programs, emphasizing the integration of theoretical knowledge with practical skills to prepare students for various IT roles. The guide includes learning outcomes and detailed content for each chapter, aimed at advancing students' expertise in Python programming.

Uploaded by

b4wb5s6dy5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STUDENT GUIDE

FACULTY OF INFORMATION TECHNOLOGY

PROGRAMMING 512
Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education
Act, [Link] Certificate No. 2000/HE07/008

FACULTY OF INFORMATION TECHNOLOGY

LEARNER GUIDE
MODULE: PROGRAMMING 512

PREPARED ON BEHALF OF
RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD

RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD

Registration Number: 2000/000757/07

All rights reserved; no part of this publication may be reproduced in any form or by any means, including photocopying
machines, without the written permission of the Institution.
Gaddis, T. (2021). Starting
out with Python. 5th Global
Ed. United Kingdom:
Pearson Education. ISBN:
9781292408637

2
Table of Contents
Chapter One: Lists and Tuples .......................................................................................................... 7

1.1 Introduction ...................................................................................................................... 7

1.2 Two Dimensional Lists ..................................................................................................... 23

1.3 Tuples .............................................................................................................................. 26

1.4 Review Questions ............................................................................................................ 29

2 Chapter Two : Dictionaries and Sets ........................................................................................... 31

2.1 Introduction .................................................................................................................... 31

2.2 Introduction to Dictionaries ............................................................................................. 32

2.3 Sets .................................................................................................................................. 40

2.4 Review Questions ............................................................................................................ 50

3 Chapter Three : Object Oriented Programming (OOP) .............................................................. 55

3.1 Procedural and Object-Oriented Programming ................................................................ 55

3.2 Hiding Attributes ............................................................................................................. 64

3.3 Inheritance ...................................................................................................................... 65

3.4 Polymorphism ................................................................................................................. 72

3.5 Review Questions ............................................................................................................ 74

4 Chapter Four: Graphical User Interface (GUI) – Programming ................................................... 75

4.1 Introduction to Tkinter ..................................................................................................... 75

4.2 Basic Concepts................................................................................................................. 77

4.3 Event-driven programming in Tkinter ............................................................................. 78

4.4 Using the TkinterModule ................................................................................................. 79

4.5 Configuring widget properties ......................................................................................... 81

4.6 Organizing Widgets with Frames ..................................................................................... 85

4.7 Organizing Widgets with Frames ..................................................................................... 86

4.8 Getting Input with the EntryWidget ................................................................................. 88

3
4.9 Listbox Widgets................................................................................................................ 90

4.10 Review Questions .............................................................................................................. 7

5 Chapter Five: Interfacing with Databases .................................................................................. 9

5.1 Introduction into Databases............................................................................................... 9

5.2 Tables and Rows .............................................................................................................. 10

5.3 Creating a Table ............................................................................................................... 13

5.4 Deleting a Table ............................................................................................................... 14

5.5 Adding data to a table ..................................................................................................... 15

5.6 Inserting the values of variables ...................................................................................... 17

5.7 Querying Data with the SQL SELECTStatement ................................................................ 18

5.8 Updating exiting rows ...................................................................................................... 19

5.9 Review Questions ............................................................................................................ 20

6 References ............................................................................................................................... 21

4
The Information Technology (IT) qualification at Richfield College is a dynamic and future-focused
program designed to equip students with advanced technical, analytical, and problem-solving skills.
At the core of the qualification is a commitment to academic excellence, industry alignment, and
innovation, fostering graduates who are proficient in addressing modern technological challenges.
This qualification strategically integrates theoretical knowledge with practical applications,
preparing students for various roles in the IT sector. The IT program is structured to address the
growing complexity of the evolving technological landscape.

The Higher certificate in Information Technology (HCIT) program is a foundational stepping-stone for
students who wish to pursue further studies or enter the workforce. Graduates of this program are
well-prepared to articulate to the Diploma in IT (DIT) or the Bachelor of Science in IT (BSc IT)
qualifications, providing a seamless transition for those seeking to deepen their knowledge and skills
in specialized IT areas. Additionally, the program equips students with the essential competencies
for entry-level IT roles such as IT Support Technicians, Junior Web/ System Developers, IT
Administrators, etc.

The Diploma in Information Technology (DIT) is a comprehensive and practical program designed to
build a strong foundation in IT principles while equipping students with the hands-on skills required
to meet industry demands. Focused on both theoretical knowledge and applied learning, this
qualification prepares students for intermediate-level roles in IT and serves as a stepping-stone for
further academic progression or specialization. Graduates of this program are well-prepared to
articulate to the Bachelor of Science in IT (BSc IT) qualification. The curriculum covers programming,
networking, database management, system analysis etc., ensuring graduates possess the
competencies to solve real-world IT challenges effectively.

The Bachelor of Science in IT (BSc IT) program is structured to address the growing complexity of the
evolving technological landscape. Through carefully curated modules, students gain a deep
understanding of software development, database management, cloud computing, cybersecurity, IT
management, artificial intelligence, machine learning, networking etc. Graduates of this program are
well-prepared to articulate to the Bachelor of Science Honours in IT qualification. The curriculum is

5
designed to bridge the gap between academic learning and real-world applications, thus fostering
innovation and an entrepreneurial mindset. Students are encouraged to participate in research and
practical learning.

The programming focus within the IT qualification exemplifies academic innovation and professional
alignment. By integrating a diverse range of programming languages with practical application, the
curriculum prepares students to excel in the rapidly evolving tech industry. The program aligns with
industry courses from globally recognized leading tech giants, such as Oracle, AWS, IBM, etc. ensures
that graduates possess the credentials to validate their expertise in software development and
cloud-based technologies. This blend of foundational knowledge, practical experience, and industry-
standard courses prepares students for immediate employment and establishes a strong basis for
long-term career advancement in software development.

Programming 512 builds on the foundational knowledge acquired in Programming 511, advancing
students' expertise in Python by introducing intermediate and advanced programming concepts.
This module covers essential topics such as data structures (lists, tuples, dictionaries, and sets),
Object-Oriented Programming (OOP), Graphical User Interface (GUI) development with Tkinter, and
interfacing with databases. These areas equip students with the skills to manage and manipulate
data efficiently, design reusable and modular software, create interactive applications, and integrate
Python with database systems. This module is designed to prepare students for more complex
programming tasks, fostering the technical proficiency needed to build versatile and robust
solutions.

6
Chapter One: Lists and Tuples

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Able to demonstrate the purpose of lists to store data

• How to iterate over a list, searching for items in a list, and calculating
the sum and average of items in a list.

• Demonstrate an understanding and the ability to use slicing and several


list methods.

• Ability to implement One and Two dimensional lists within a given


context

• Understanding of Tuples

• Able to perform Tuple Assignment, Packing and Unpacking

1.1 Introduction
A sequence is an object that holds multiple items of data, stored one after the other. You can perform
operations on a sequence to examine and manipulate the items stored in it. The items that are in a
sequence are stored one after the other. Python provides various ways to perform operations on
the items that are stored in a sequence.

In this chapter, we will look at two of the fundamental sequence types: lists and tuples. Both lists
and tuples are sequences that can hold various types of data. The difference between lists and
tuples is simple: a list is mutable, which means that a program can change its contents, but a tuple is
immutable, which means that once it is created, its contents cannot be changed. We will explore
some of the operations that you may perform on these sequences, including ways to access and
manipulate their contents.
1.1.1 Introduction to Lists
A list is an object that contains multiple data items. Lists are mutable, which means that their
contents can be changed during a program’s execution. Lists are dynamic data structures, meaning
that items may be added to them or removed from them. You can use indexing, slicing, and various
methods to work with lists in a program A list is an object that contains multiple data items. Each item
that is stored in a list is called an element. Here is a statement that creates a list of integers:

even_numbers = [2, 4, 6, 8, 10]

The items that are enclosed in brackets and separated by commas are the list elements.

The following is another example:

names = ['Molly', 'Steven', 'Will', 'Alicia', 'Adriana']

This statement creates a list of five strings. After the statement executes, the name variable will
reference the list.

A list can hold items of different types, as shown in the following example:

info = ['Alicia', 27, 1550.87]

This statement creates a list containing a string, an integer, and a floating-point number. After the
statement executes, the info variable will reference the list. You can use the print function to display
an entire list, as shown here:

numbers = [5, 10, 15, 20] print(numbers)

In this example, the print function will display the elements of the list like this:

[5, 10, 15, 20]

1.1.2 Iterating over a List with the for loop


Many of the same programming techniques also apply to lists. For example, you can iterate over a
list with the for loop, as shown here:
numbers = [99, 100, 101, 102]

for n in numbers:

print(n)

If we run this code, it will print:


99

100

101

102

1.1.3 Indexing
Another way that you can access the individual elements in a list is with an index. Each element in a
list has an index that specifies its position in the list. Indexing starts at 0, so the index of the first
element is 0, the index of the second element is 1, and so forth. The index of the last element in a
list is 1 less than the number of elements in the list. For example, the following statement creates a
list with 4 elements:

my_list = [10, 20, 30, 40]

The indexes of the elements in this list are 0, 1, 2, and 3. We can print the elements of the list with
the following statement:

print(my_list[0], my_list[1], my_list[2], my_list[3])

The following loop also prints the elements of the list:

index = 0

while index < 4:

print(my_list[index]) index += 1

You can also use negative indexes with lists to identify element positions relative to the end of the
list. The Python interpreter adds negative indexes to the length of the list to determine the element
position. The index −1 identifies the last element in a list, −2 identifies the next to last element, and
so forth. The following code shows an example:

my_list = [10, 20, 30, 40]

print(my_list[−1], my_list[−2], my_list[−3], my_list[−4])

In this example, the print function will display:

40 30 20 10

An IndexErrorexception will be raised if you use an invalid index with a list.

1.1.4 Lists are Mutable


Lists in Python are mutable, which means their elements can be changed. Consequently, an
expression in the form list[index]can appear on the left side of an assignment operator.

numbers = [1, 2, 3, 4, 5] print(numbers)

numbers [0] = 99 print(numbers)

The statement in line 2 will display:


[1, 2, 3, 4, 5]

The statement in line 3 assigns 99 to numbers [0]. This changes the first value in the list to 91. When
the statement in line 4 executes, it will display:

[99, 2, 3, 4, 5]

When you use an indexing expression to assign a value to a list element, you must use a valid index
for an existing element or an IndexErrorexception will occur.
The statement in line 3 creates the variable NUM_DAYS, which is used as a constant for the number
of days. The statement in line 8 creates a list with five elements, with each element assigned the value

0. Line 11 creates a variable named index and assigns the value 0 to it. The loop in lines 16 through
19 iterates 5 times. The first time it iterates, index references the value 0, so the statement in line
18 assigns the user’s input to sales[0]. The second time the loop iterates, index references the value
1, so the statement in line 18 assigns the user’s input to sales[1].
1.1.5 Concatenating Lists
To concatenate means to join two things together. You can use the + operator to concatenate two
lists. Here is an example:

list1 = [1, 2, 3, 4]

list2 = [5, 6, 7, 8]

list3 = list1 + list2

After this code executes, list1 and list2 remain unchanged, and list3 references the following list:

[1, 2, 3, 4, 5, 6, 7, 8]

The following interactive mode session also demonstrates the += operator used for list
concatenation:

girl_names = ['Joanne', 'Karen', 'Lori'] girl_names += ['Jenny', 'Kelly'] print(girl_names)

After the code is executed below is the output:


['Joanne', 'Karen', 'Lori', 'Jenny', 'Kelly']

1.1.6 List Slicing


A slicing expression selects a range of elements from a sequence. A slice is a span of items that are
taken from a sequence. When you take a slice from a list, you get a span of elements from within
the list. To get a slice of a list, you write an expression in the following general format:
list_name[start : end]

In the general format, start is the index of the first element in the slice, and end is the index marking
the end of the slice. The expression returns a list containing a copy of the elements from start up to
(but not including) end. For example, suppose we create the following list:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

The following statement uses a slicing expression to get the elements from indexes 2 up to, but

not including, 5:

mid_days = days[2:5]

After this statement executes, the mid_daysvariable references the following list:

['Tuesday', 'Wednesday', 'Thursday']

If you leave out the start index in a slicing expression, Python uses 0 as the starting index.
numbers = [1, 2, 3, 4, 5] print(numbers)

Output before slicing:


[1, 2, 3, 4, 5]

Run the code to slice the list omitting the start value:
print(numbers[:3])

1.1.7 Output after the slice


[1, 2, 3]

Notice line 4 sends the slice numbers [:3] as an argument to the print function. Because the starting
index was omitted, the slice contains the elements from index 0 up to 3. If you leave out both the
start and end index in a slicing expression, you get a copy of the entire list.

numbers = [1, 2, 3, 4, 5] print(numbers)

[1, 2, 3, 4, 5]
print(numbers[:]) [1, 2, 3, 4, 5]

Slicing expressions can also have step value, which can cause elements to be skipped in the list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(numbers)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(numbers[1:8:2]) [2, 4, 6, 8]

1.1.8 Finding Items in Lists with the in Operator


You can search for an item in a list using the in operator. In Python, you can use the in operator to
determine whether an item is contained in a list. Here is the general format of an expression written
with the in operator to search for an item in a list:

item in list

In the general format, item is the item for which you are searching, and list is a list. The expression
returns true if item is found in the list, or false otherwise.
The program gets a product number from the user in line 9 and assigns it to the search variable. The
if statement in line 12 determines whether search is in the prod_nums list. You can use the not in
operator to determine whether an item is not in a list. Here is an example:

if search not in prod_nums:

print(search, 'was not found in the list.') else:

print(search, 'was found in the list.')

1.1.9 List Methods and Useful Built-in Functions


Lists have numerous methods that allow you to work with the elements that they contain. Python
also provides some built-in functions that are useful for working with lists. Lists have numerous
methods that allow you to add elements, remove elements, change the ordering of elements, and
so forth.

The append Method

The append method is commonly used to add items to a list. The item that is passed as an argument
is appended to the end of the list’s existing elements.
The appendmethod
Notice the statement in line 6:

name_list = []

This statement creates an empty list (a list with no elements) and assigns it to the name_list variable.
Inside the loop, the append method is called to build the list. The first time the method is called, the
argument passed to it will become element 0. The second time the method is called, the argument
passed to it will become element 1. This continues until the user exits the loop.

Sometimes you need to know not only whether an item is in a list, but where it is located. The index

method is useful in these cases. You pass an argument to the index method, and it returns the index
of the first element.
The elements of the food list are displayed in line 11, and in line 14, the user is asked which item he
or she wants to change. Line 18 calls the index method to get the index of the item. Line 21 gets the
new value from the user, and line 24 assigns the new value to the element holding the old value.

The insertMethod

The insert method allows you to insert an item into a list at a specific position. You pass two

arguments to the insert method: an index specifying where the item should be inserted and the item
that you want to insert.
The sortmethod

The sort method rearranges the elements of a list so they appear in ascending order (from the lowest
value to the highest value). Here is an example:
my_list = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]

print('Original order:', my_list) my_list.sort()

print('Sorted order:', my_list)

When this code runs, it will display the following:


Original order: [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]

Sorted order: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

another example:
my_list = ['beta', 'alpha', 'delta', 'gamma'] print('Original order:', my_list) my_list.sort()

print('Sorted order:', my_list)

When this code runs, it will display the following:


Original order: ['beta', 'alpha', 'delta', 'gamma']

Sorted order: ['alpha', 'beta', 'delta', 'gamma']

The removemethod

The remove method removes an item from the list. You pass an item to the method as an argument,
and the first element containing that item is removed. This reduces the size of the list by one element.
All elements after the removed element are shifted one position toward the beginning of the list. A
ValueErrorexception is raised if the item is not found in the list.
The reverse method

The reverse method simply reverses the order of the items in the list. Here is an example:
my_list = [1, 2, 3, 4, 5] print('Original order:', my_list) my_list.reverse() print('Reversed:', my_list)
This code will display the following:
Original order: [1, 2, 3, 4, 5]

Reversed: [5, 4, 3, 2, 1]

1.1.10 Passing a List as an Argument to a Function


You can easily pass a list as an argument to a function. This gives you the ability to put many of the
operations that you perform on a list in their own functions. When you need to call these functions,
you can pass the list as an argument The function in this program accepts a list as an argument and
returns the total of the list’s elements.
1.1.11 Returning a List from a Function
A function can return a reference to a list. This gives you the ability to write a function that creates
a list and adds elements to it, then returns a reference to the list so other parts of the program can
work with it. The code in the program below shows an example. It uses a function named get_values
that gets a series of values from the user, stores them in a list, then returns a reference to the list.
1.2 Two Dimensional Lists
A two-dimensional list is a list that has other lists as its elements. Two-dimensional lists are useful
for working with multiple sets of data. For example, suppose you are writing a grade-averaging
program for a teacher. The teacher has three students, and each student takes three exams during the
semester. One approach would be to create three separate lists, one for each student. Each of these
lists would have three elements, one for each exam score.
This approach would be cumbersome, however, because you would have to separately process each
of the lists. A better approach would be to use a two-dimensional list with three rows (one for each
student) and three columns (one for each exam score),

When processing the data in a two-dimensional list, you need two subscripts: one for the rows, and
one for the columns. For example, suppose we create a two-dimensional list with the following
statement:
scores = [[0, 0, 0],

[0, 0, 0],

[0, 0, 0]]

The elements in row 0 are referenced as follows:


scores[0][0]

scores[0][1]

scores[0][2]

The elements in row 1 are referenced as follows:


scores[1][0]

scores[1][1]

scores[1][2]
And, the elements in row 2 are referenced as follows:
scores[2][0]

scores[2][1]

scores[2][2]

Programs that process two-dimensional lists typically do so with nested loops.


1.3 Tuples
A tuple is an immutable sequence, which means that its contents cannot be changed. A tuple is a
sequence, very much like a list. The primary difference between tuples and lists is that tuples are
immutable. That means once a tuple is created, it cannot be changed. When you create a tuple, you
enclose its elements in a set of parentheses, as shown below.

my_tuple = (1, 2, 3, 4, 5) print(my_tuple)

Output
(1, 2, 3, 4, 5)

The following session shows how a for loop can iterate over the elements in a tuple:
names = ('Holly', 'Warren', 'Ashley') for n in names:

print(n)

Output

Holly Warren Ashley

In fact, tuples support all the same operations as lists, except those that change the contents of the
list. Tuples support the following:

• Subscript indexing (for retrieving element values only)

• Methods such as index

• Built-in functions such as len, min, and max

• Slicing expressions

• The in operator

• The + and * operators


Tuples do not support methods such as append, remove, insert, reverse, and sort.

1.3.1 List or Tuple?


If the only difference between lists and tuples is immutability, you might wonder why tuples exist.
One reason that tuples exist is performance. Processing a tuple is faster than processing a list, so
tuples are good choices when you are processing lots of data, and that data will not be modified.
Another reason is that tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified (accidentally or
otherwise) by any code in your program. Additionally, there are certain operations in Python that
require the use of a tuple. As you learn more about Python, you will encounter tuples more
frequently.

1.3.2 Converting between Lists and Tuples


You can use the built-in list() function to convert a tuple to a list, and the built-in tuple()

function to convert a list to a tuple.

number_tuple = (1, 2, 3)

number_list = list(number_tuple)

print(number_list)

Output

[1, 2, 3]

Code for a tuple


str_list = ['one', 'two', 'three'] str_tuple = tuple(str_list)

print(str_tuple)

Output
('one', 'two', 'three')

1.3.3 Packing and Unpacking Tuple


When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

fruits = ("apple", "banana", "cherry") print(fruits)

But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":

fruits = ("apple", "banana", "cherry") green, yellow, red) = fruits print(green)

print(yellow) print(red)

Output:

apple banana cherry

The number of variables must match the number of values in the tuple, if not, you must use an asterisk
to collect the remaining values as a list.

Using Asterisk*

If the number of variables is less than the number of values, you can add an *to the variable name
and the values will be assigned to the variable as a list:

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry") (green, yellow, *red) = fruits

print(green) print(yellow) print(red)

Output
apple banana

['cherry', 'strawberry', 'raspberry']

Review Questions

1.1 What will the following code display?


numbers = [1, 2, 3, 4, 5]

numbers[2] = 99

print(numbers)

1.4 Review Questions


1.1 What will the following code display?

numbers = [1, 2, 3, 4, 5]

numbers[2] = 99

print(numbers)

1.2 What will the following code display?

numbers = list(range(3))

print(numbers)

1.3 What will the following code display?

numbers = [10] * 5

print(numbers)

1.4 What will the following code display?

numbers = list(range(1, 10, 2))

for n in numbers:

print(n)

1.5 What will the following code display?

numbers = [1, 2, 3, 4, 5]

print(numbers[−2])

1.6 How do you find the number of elements in a list?

1.7 What will the following code display?

numbers1 = [1, 2, 3]

numbers2 = [10, 20, 30]

numbers3 = numbers1 + numbers2


print(numbers1)

print(numbers2)

print(numbers3)

1.8 What will the following code display?

numbers1 = [1, 2, 3]

numbers2 = [10, 20, 30]

numbers2 += numbers1

print(numbers1)

print(numbers2)
2 Chapter Two : Dictionaries and Sets

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Explain what dictionaries are, their purpose, and how they differ from
other Python data structures.

• Create dictionaries with key-value pairs and access values using keys.

• Add, update, and delete key-value pairs in dictionaries.

• Use methods like get(), keys(), values(), and items() for manipulation
and retrieval.

• Iterate through keys, values, and items using loops.

• Define sets, their characteristics, and how they differ from other data
structures.

• Create sets and perform operations such as union, intersection,


difference, and symmetric difference.

• Ensure sets contain unique elements and use membership tests.

• Use add() and remove() to modify set contents.

2.1 Introduction
Sets and dictionaries are ideal data structures to be used when your data has no intrinsic order but
does have a unique object that can be used to reference it (the reference object is normally a string
but can be any hashable type). This reference object is called the “key,” while the data is the “value.”
Dictionaries and sets are almost identical, except that sets do not actually contain values: a set is
simply a collection of unique keys. As the name implies, sets are very useful for doing set operations.
2.2 Introduction to Dictionaries
In Python, a dictionary is an object that stores a collection of data. Each element that is stored in a
dictionary has two parts: a key and a value. In fact, dictionary elements are commonly referred to
as key-value pairs. When you want to retrieve a specific value from a dictionary, you use the key
that is associated with that value.

For example, suppose each employee in a company has an ID number, and we want to write a
program that lets us look up an employee's name by entering that employee's ID number. We could
create a dictionary in which each element contains an employee ID number as the key, and that
employee's name as the value. If we know an employee's ID number, then we can retrieve that
employee's name.

Another example would be a program that lets us enter a person's name and gives us that person's
phone number. The program could use a dictionary in which each element contains a person's name
as the key, and that person's phone number as the value. If we know a person's name, then we can
retrieve that person's phone number.

2.2.1 Creating a Dictionary


You can create a dictionary by enclosing the elements inside a set of curly braces ({}). An element
consists of a key, followed by a colon, followed by a value. The elements are separated by commas.
The following statement shows an example:
phonebook = {'Chris': '555-1111', 'Katie':'555-2222','Joanne':'555-3333'}

This statement creates a dictionary and assigns it to the phonebook variable. The dictionary contains
the following three elements:

• The first element is 'Chris':'555−1111'. In this element, the key is 'Chris' and the value is

'555−1111'.

• The second element is 'Katie':'555−2222'. In this element, the key is 'Katie' and the value is
'555−2222'.
• The third element is 'Joanne':'555−3333'. In this element, the key is 'Joanne' and the value is
'555−3333'. In this example, the keys and the values are strings. The values in a dictionary can be
objects of any type, but the keys must be immutable objects. For example, keys can be strings,
integers, floating- point values, or tuples. Keys cannot be lists or any other type of immutable
object.

2.2.2 Retrieving a value from a Dictionary


The elements in a dictionary are not stored in any particular order. For example, look at the following
interactive session in which a dictionary is created, and its elements are displayed:

Like lists, tuples and strings, dictionaries are not sequences. As a result, you cannot use a numeric
index to retrieve a value by its position from a dictionary. Instead, you use a key to retrieve a value.
To retrieve a value from a dictionary, you simply write an expression in the following general format:
dictionary_name[key]

In the general format, dictionary_name is the variable that references the dictionary, and key is a
key. If the key exists in the dictionary, the expression returns the value that is associated with the
key. If the key does not exist, a KeyError exception is raised. The following interactive session
demonstrates:
Line 1 creates a dictionary containing names (as keys) and phone numbers (as values).

• In line 2, the expression phonebook['Chris'] returns the value from the phonebook dictionary that is
associated with the key 'Chris'. The value is displayed in line 3.

• In line 3, the expression phonebook['Joanne'] returns the value from the phonebook dictionary that
is associated with the key 'Joanne'. The value is displayed in line 5.

• In line 4, the expression phonebook['Katie'] returns the value from the phonebook dictionary that is
associated with the key 'Katie'. The value is displayed in line 7.

• In line 6, the expression phonebook['Kathryn'] is entered. There is no such key as 'Kathryn' in the
phonebook dictionary, so a KeyErrorexception is raised.

2.2.3 Using the in and not in Operators to Test for a Value in a Dictionary
The KeyError exception is raised if you try to retrieve a value from a dictionary using a nonexistent
key. To prevent such an exception, you can use the in operator to determine whether a key exists
before you try to use it to retrieve a value. The following interactive session demonstrates:

The if statement in line 2 above determines whether the key 'Chris' is in the phonebook dictionary.
If it is, the statement in line 3 displays the value that is associated with that key. You can also use
the not in operator to determine whether a key does not exist, as demonstrated in the following
session:
2.2.4 Adding Elements to an Existing Dictionary
Dictionaries are mutable objects. You can add new key-value pairs to a dictionary with an assignment
statement in the following general format: dictionary_name[key] = value

In the general format, dictionary_name is the variable that references the dictionary, and key is a
key. If key already exists in the dictionary, its associated value will be changed to value. If the key
does not exist, it will be added to the dictionary, along with value as its associated value. The following
interactive session demonstrates:

Line 1 creates a dictionary containing names (as keys) and phone numbers (as values).

• The statement in line 2 adds a new key-value pair to the phonebook dictionary.

Because there is no key 'Joe' in the dictionary, this statement adds the key 'Joe', along with its

associated value '555−0123'.

• The statement in line 3 changes the value that is associated with an existing key. Because the key
'Chris' already exists in the phonebook dictionary, this statement changes its associated value to
'555−4444'.

• Line 4 displays the contents of the phonebook dictionary.

2.2.5 Deleting Elements


You can delete an existing key-value pair from a dictionary with the del statement. Here is the general
format: del dictionary_name[key]

In the general format, dictionary_name is the variable that references the dictionary, and key is a
key. After the statement executes, the key and its associated value will be deleted from the
dictionary. If the key does not exist, a KeyError exception is raised. The following interactive session
demonstrates:

Let’s take a closer look at the session:

• Line 1 creates a dictionary

• Line 4 deletes the element with the key 'Chris',

• Line 7 tries to delete the element with the key 'Chris' again. Because the element no longer exists, a
KeyErrorexception is raised.

Getting the number of Elements in a dictionary

You can use the built-in lenfunction to get the number of elements in a dictionary. The following
interactive session demonstrates:

• Line 1 creates a dictionary with two elements and assigns it to the phonebook variable.

• Line 2 calls the lenfunction passing the phonebook variable as an argument. The function returns
the value 2, which is assigned to the num_itemsvariable.

• Line 3 passes num_itemsto the print function. The function’s output is shown below line
3.

2.2.6 Mixing Data Types in a Dictionary


The keys in a dictionary must be immutable objects, but their associated values can be any type of
object. For example, the values can be lists, as demonstrated in the following interactive session. In
this session, we create a dictionary in which the keys are student names, and the values are lists of
test scores.

Let’s take a closer look at the session. This statement in lines 1 through 4 creates a dictionary and
assigns it to the test_scoresvariable. The dictionary contains the following four elements:

• The first element is 'Kayla': [88, 92, 100].In this element, the key is 'Kayla'and the value is the list
[88, 92, 100].

• The second element is 'Luis': [95, 74, 81].In this element, the key is 'Luis'and the value is the list [95,
74, 81].

• The third element is 'Sophie': [72, 88, 91].In this element, the key is 'Sophie'and the value is the list
[72, 88, 91].

• The fourth element is 'Ethan':[70, 75, 78].In this element, the key is 'Ethan'and the value is the list
[70, 75, 78].

2.2.7 Creating an Empty Dictionary

Sometimes, you need to create an empty dictionary and then add elements to it as the program
executes. You can use an empty set of curly braces to create an empty dictionary, as demonstrated
in the following interactive session:
• The statement in line 1 creates an empty dictionary and assigns it to the phonebook variable.

• Lines 2 through 4 add key-value pairs to the dictionary, and the statement in line 5 displays the

dictionary’s contents.

• You can also use the built-in dict()method to create an empty dictionary, as shown in the following
statement: phonebook = dict()

• After this statement executes, the phonebook variable will reference an empty dictionary.

2.2.8 Using the for Loop to Iterate over a Dictionary

You can use the for loop in the following general format to iterate over all the keys in a dictionary:
for var in dictionary:

statement statement etc.

In the general format, var is the name of a variable and dictionary is the name of a dictionary. This
loop iterates once for each element in the dictionary. Each time the loop iterates, var is assigned a
key. The following interactive session demonstrates

• Lines 1 create a dictionary with three elements and assign it to the phonebook variable

• Line 2 contains a forloop that iterates once for each element of the phonebook dictionary. Each time
the loop iterates, the key variable is assigned a key.

• Line 3 prints the value of the key variable


• Lines 4 contain another forloop that iterates once for each element of the phonebook dictionary,
assigning a key to the key variable.

• Line 5 prints the key variable, followed by the value that is associated with that key.

2.2.9 Some Dictionary methods


Dictionary objects have several methods. In this section, we look at some of the more useful Ones

2.3 Sets
2.3.1 Introduction to sets
A set is an object that stores a collection of data in the same way as mathematical sets. Here are
some important things to know about sets:

• All the elements in a set must be unique. No two elements can have the same value.

• Sets are unordered, which means that the elements in a set are not stored in any particular order.

• The elements that are stored in a set can be of different data types.

2.3.2 Creating a Set


To create a set, you must call the built-in set function. Here is an example of how you create an empty
set: myset = set()

After this statement is executed, the myset variable will reference an empty set. You can also pass
one argument to the set function. The argument that you pass must be an object that contains
iterable elements, such as a list, a tuple, or a string. The individual elements of the object that you
pass as an argument become elements of the set. Here is an example: myset = set(['a', 'b', 'c'])
In this example, we are passing a list as an argument to the set function. After this statement is
executed, the mysetvariable references a set containing the elements 'a', 'b',and 'c'.

If you pass a string as an argument to the set function, each individual character in the string becomes
a member of the set. Here is an example: myset = set('abc'). After this statement is executed, the
mysetvariable will reference a set containing the elements: 'a', 'b', and 'c'.

Sets cannot contain duplicate elements. If you pass an argument containing duplicate elements to
the set function, only one of the duplicated elements will appear in the set. Here is an example:
myset

= set('aaabc')

The character 'a' appears multiple times in the string, but it will appear only once in the set. After
this statement is executed, the myset variable will reference a set containing the elements 'a', 'b', and
'c'.

What if you want to create a set in which each element is a string containing more than one character?
For example, how would you create a set containing the elements 'one', 'two', and 'three'? The
following code does not accomplish the task, because you can pass no more than one argument to
the set function:
# This is an ERROR!

myset = set('one', 'two', 'three')

The following does not accomplish the task either:


# This does not do what we intend. myset = set('one two three')

After this statement executes, the mysetvariable will reference a set containing the elements 'o',
'n', 'e', ' ', 't', 'w', 'h', and 'r'. To create the set that we want, we must pass a list containing the strings
‘one’, ‘two’,and ‘three’as an argument to the set function. Here is an example:
# OK, this works.
myset = set(['one', 'two', 'three'])

After this statement executes, the mysetvariable will reference a set containing the elements
'one', 'two', and 'three'.

2.3.3 Getting the number of elements in a set


As with lists, tuples, and dictionaries, you can use the len function to get the number of elements in
a set. The following interactive session demonstrates:

2.3.4 Adding and Removing


Sets are mutable objects, so you can add items to them and remove items from them. You use the
add method to add an element to a set. The following example demonstrates:

• The statement in line 1 creates an empty set and assigns it to the mysetvariable.

• The statements in lines 2 through 4 add the values 1, 2, and 3 to the set.

• Line 5 displays the contents of the set

• The statement in line 7 attempts to add the value 2 to the set. The value 2 is already in the set,
however. If you try to add a duplicate item to a set with the add method, the method does not raise
an exception. It simply does not add the item.
You can add a group of elements to a set all at one time with the update method. When you call the
update method as an argument, you pass an object that contains iterable elements, such as a list, a
tuple, string, or another set. The individual elements of the object that you pass as an argument
become elements of the set. The following interactive session demonstrates:

• The statement in line 1 creates a set containing the values 1, 2, and 3.

• Line 2 adds the values 4, 5, and 6.

The following session shows another example:

• Line 1 creates a set containing the values 1, 2, and 3 and assigns it to the set1variable.

• Line 2 creates a set containing the values 8, 9, and 10 and assigns it to the set2variable.

• Line 3 calls the [Link], passing set2as an argument.

You can remove an item from a set with either the remove method or the discard method. You pass
an item that you want to remove as an argument to either method, and that item is removed. The
only difference between the two methods is how they behave when the specified item is not found
in the set. The remove method raises a KeyError exception, but the discard method does not raise an
exception. The following interactive session demonstrates:
• Line 1 creates a set with the elements 1, 2, 3, 4, and 5.

• Line 2 displays the contents of the set

• Line 3 calls the removemethod to remove the value 1 from the set.

• Line 5 calls the discardmethod to remove the value 5 from the set.

• Line 7 calls the discardmethod to remove the value 99 from the set. The value is not found in the set,
but the discardmethod does not raise an exception.

• Line 8 calls the removemethod to remove the value 99 from the set. Because the value is not in the
set, a KeyErrorexception is raised, as shown in below the output.

You can clear all the elements of a set by calling the clearmethod. The following interactive session
demonstrates:

• The statement in line 3 calls the clear method to clear the set.
• Notice in line 5 that when we display the contents of an empty set, the interpreter displays

set().

2.3.5 Using the for loop to iterate over a Set


You can use the for loop in the following general format to iterate over all the elements in a set:

for var in set:

statement statement etc.

In the general format, var is the name of a variable and set is the name of a set. This loop iterates once
for each element in the set. Each time the loop iterates, var is assigned an element. The following
interactive session demonstrates:

• Lines 2 through 3 contain a forloop that iterates once for each element of the mysetset. Each time
the loop iterates, an element of the set is assigned to the valvariable.

• Line 3 prints the value of the valvariable.

2.3.6 Using the in and not in Operators to Test for a Value in a Set
You can use the in operator to determine whether a value exists in a set. The following interactive
session demonstrates:

• The if statement in line 2 determines whether the value 1 is in the mysetset. If it is, the statement
in line 3 displays a message.
You can also use the not in operator to determine if a value does not exist in a set, as demonstrated
in the following session:

2.3.7 Finding the Union of Sets


The union of two sets is a set that contains all the elements of both sets. In Python, you can call the
union method to get the union of two sets. Here is the general format: [Link](set2). In the
general format, set1 and set2 are sets. The method returns a set that contains the elements of both
set1and set2. The following interactive session demonstrates:

• The statement in line 3 calls the set1 object’s union method, passing set2 as an argument.

• The method returns a set that contains all the elements of set1 and set2 (without duplicates, of
course). The resulting set is assigned to the set3 variable.

You can also use the | operator to find the union of two sets. Here is the general format of an
expression using the | operator with two sets: set1 | set2. In the general format, set1 and set2 are
sets. The expression returns a set that contains the elements of both set1 and set2. The following
interactive session demonstrates:

2.3.8 Finding the intersection of Sets


The intersection of two sets is a set that contains only the elements that are found in both sets. In
Python, you can call the intersection method to get the intersection of two sets. Here is the general
format: [Link](set2. In the general format, set1 and set2 are sets. The method returns a
set that contains the elements that are found in both set1 and set2. The following interactive session
demonstrates:

• The statement in line 3 calls the set1 object’s intersection method, passing set2 as an argument.

• The method returns a set that contains the elements that are found in both set1 and set2. The
resulting set is assigned to the set3 variable.

• You can also use the & operator to find the intersection of two sets. Here is the general format of an
expression using the & operator with two sets: set1 & set2

• In the general format, set1 and set2 are sets. The expression returns a set that contains the elements

that are found in both set1 and set2. The following interactive session demonstrates:
2.3.9 Finding the Difference of Sets
The difference of set1 and set2 is the elements that appear in set1 but do not appear in set2. In
Python, you can call the difference method to get the difference of two sets. Here is the general
format:

[Link](set2). In the general format, set1 and set2 are sets. The method returns a set that
contains the elements that are found in set1 but not in set2. The following interactive session
demonstrates:

You can also use the − operator to find the difference between two sets. Here is the general format of
an expression using the − operator with two sets: set1 − set2. In the general format, set1 and set2
are sets. The expression returns a set that contains the elements that are found in set1but not in
set2. The following interactive session demonstrates:

2.3.10 Finding the Symmetric Difference of Sets


The symmetric difference of two sets is a set that contains the elements that are not shared by the
sets. In other words, it is the elements that are in one set but not in both. In Python, you can call the
symmetric difference method to get the symmetric difference of two sets. Here is the general
format: set1.symmetric_difference(set2)

In the general format, set1 and set2 are sets. The method returns a set that contains the elements that
are found in either set1 or set2 but not both sets. The following interactive session demonstrates:

48
You can also use the ˆ operator to find the symmetric difference of two sets. Here is the general
format

of an expression using the ˆ operator with two sets:

set1 ˆ set2

In the general format, set1 and set2 are sets. The expression returns a set that contains the elements
that are found in either set1 or set2, but not both sets. The following interactive session
demonstrates:

2.3.11 Finding Subsets and Supersets


Suppose you have two sets, and one of those sets contains all of the elements of the other set. Here
is an example:

set1 = set([1, 2, 3, 4])

set2 = set([2, 3])

In this example, set1 contains all the elements of set2, which means that set2 is a subset of set1. It also
means that set1 is a superset of set2. In Python, you can call the issubset method to determine
whether one set is a subset of another. Here is the general format: [Link](set1)

In the general format, set1 and set2 are sets. The method returns True if set2 is a subset of set1.
Otherwise, it returns False. You can call the issuperset method to determine whether one set is a
superset of another. Here is the general format: [Link](set2)

49
In the general format, set1 and set2 are sets. The method returns True if set1 is a superset of set2.
Otherwise, it returns False. The following interactive session demonstrates:

You can also use the <= operator to determine whether one set is a subset of another and the >=
operator to determine whether one set is a superset of another. Here is the general format of an
expression using the <= operator with two sets: set2 <= set1

In the general format, set1 and set2 are sets. The expression returns True if set2 is a subset of set1.
Otherwise, it returns False. Here is the general format of an expression using the >= operator with
two sets: set1 >= set2. In the general format, set1 and set2 are sets. The expression returns True if
set1 is a subset of set2. Otherwise, it returns False. The following interactive session demonstrates:

2.4 Review Questions

2.1 An element in a dictionary has two parts. What are they called?

2.2 Which part of a dictionary element must be immutable?

50
2.3 Suppose 'start' : 1472 is an element in a dictionary. What is the key? What is

the value?

2.4 Suppose a dictionary named employee has been created. What does the following

statement do?

employee['id'] = 54321

2.2 Sets 515

2.5 What will the following code display?

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

print(stuff[3])

2.6 How can you determine whether a key-value pair exists in a dictionary?

2.7 Suppose a dictionary named inventory exists. What does the following statement do?

del inventory[654]

2.8 What will the following code display?

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

print(len(stuff))

2.9 What will the following code display?

stuff = {1 : 'aaa', 2 : 'bbb', 3 : 'ccc'}

for k in stuff:

print(k)

2.10 What is the difference between the dictionary methods pop and popitem?

2.11 What does the items method return?

2.12 What does the keys method return?

2.13 What does the values method return?

2.14 Assume the following list exists:

names = ['Chris', 'Katie', 'Joanne', 'Kurt']

Write a statement that uses a dictionary comprehension to create a dictionary in

which each element contains a name from the names list as its key, and the length

of that name as its value.


51
2.15 Assume the following dictionary exists:

phonebook = {'Chris':'919-555−1111', 'Katie':'828-555−2222',

'Joanne':'704-555−3333', 'Kurt':'919-555−3333'}

Write a statement that uses a dictionary comprehension to create a second dictionary

containing the elements of phonebook that have a value starting with '919'.

2.16 Are the elements of a set ordered or unordered?

2.17 Does a set allow you to store duplicate elements?

2.18 How do you create an empty set?

2.19 After the following statement executes, what elements will be stored in the myset set?

myset = set('Jupiter')

2.20 After the following statement executes, what elements will be stored in the

myset set?

myset = set(25)

2.21 After the following statement executes, what elements will be stored in the

myset set?

myset = set('www xxx yyy zzz')

2.22 After the following statement executes, what elements will be stored in the

myset set?

myset = set([1, 2, 2, 3, 4, 4, 4])

2.23 After the following statement executes, what elements will be stored in the

myset set?

myset = set(['www', 'xxx', 'yyy', 'zzz'])

2.24 How do you determine the number of elements in a set?

2.25 After the following statement executes, what elements will be stored in the

myset set?

myset = set([10, 9, 8])

[Link]([1, 2, 3])

2.26 After the following statement executes, what elements will be stored in the
52
myset set?

myset = set([10, 9, 8])

[Link]('abc')

2.27 What is the difference between the remove and discard methods?

2.28 How can you determine whether a specific element exists in a set?

2.29 After the following code executes, what elements will be members of set3?

set1 = set([10, 20, 30])

set2 = set([100, 200, 300])

set3 = [Link](set2)

2.30 After the following code executes, what elements will be members of set3?

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = [Link](set2)

2.31 After the following code executes, what elements will be members of set3?

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = [Link](set2)

2.32 After the following code executes, what elements will be members of set3?

set1 = set([1, 2, 3, 4])

set2 = set([3, 4, 5, 6])

set3 = [Link](set1)

2.33 After the following code executes, what elements will be members of set3?

set1 = set(['a', 'b', 'c'])

set2 = set(['b', 'c', 'd'])

set3 = set2.symmetric_difference(set2)

2.34 Look at the following code:

set1 = set([1, 2, 3, 4])

set2 = set([2, 3])


53
Which of the sets is a subset of the other?

Which of the sets is a superset of the other?

54
3 Chapter Three : Object Oriented Programming (OOP)

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Distinguish between two programming methods, procedural and


object-oriented programming.

• Learn how to create and work with classes

• Understand the concept of inheritance and its implementation

3.1 Procedural and Object-Oriented Programming


Procedural programming is a method of programming that focuses on creating procedures that
operate on the program's data. The earliest programming languages were procedural, meaning a
program was made of one or more procedures. These procedures perform specific tasks, such as
gathering input, performing calculations, reading, or writing files, and displaying output. The focus
of procedural programming is on creating procedures that operate on the program's data, but the
separation of data and code can lead to problems as the program becomes larger and more complex.

Object-oriented programming (OOP) is centered on creating objects, which are software entities
that contain both data and procedures. An object's data attributes are variables that reference data,
and its methods are functions that perform operations on the object's data attributes. The object is
a self- contained unit that consists of data attributes and methods that operate on the data
attributes.

55
3.1.1 Object Reusability

In addition to solving the problems of code and data separation, the use of OOP has also been
encouraged by the trend of object reusability. An object is not a stand-alone program but is used by
programs that need its services.

3.1.2 Classes
Before an object can be created, it must be designed by a programmer. The programmer determines
the data attributes and methods that are necessary, then creates a class. A class is code that specifies
the data attributes and methods of a particular type of object. Think of a class as a “blueprint” from
which objects may be created. It serves a similar purpose as the blueprint for a house. The blueprint
itself is not a house but is a detailed description of a house. When we use the blueprint to build an
actual house, we could say we are building an instance of the house described by the blueprint. If
we so desire, we can build several identical houses from the same blueprint. Each house is a
separate instance of the house described by the blueprint.

So, a class is a description of an object’s characteristics. When the program is running, it can use the
class to create, in memory, as many objects of a specific type as needed. Each object that is created
from a class is called an instance of the class.

56
3.1.3 Class Definitions

To create a class, you write a class definition. A class definition is a set of statements that define a
class’s methods and data attributes. Let’s look at a simple example. Suppose we are writing a program
to simulate the tossing of a coin. In the program, we need to repeatedly toss the coin and each time
determine whether it landed heads up or tails up. Taking an object-oriented approach, we will write
a class named Coin that can perform the behaviours of the coin.

1 import random
2

3 # The Coin class


simulates a coin
that can
# The init method
initializes the # sideup

def init (self):


[Link] = 'Heads'

# The toss method generates a


random number # in the range of
0 through 1. If the number # is
0, then sideup is set to 'Heads'.
# Otherwise, sideup
is set to 'Tails'.

def toss(self):

if [Link](0, 1) == 0:
[Link] = 'Heads'
else:

[Link] = 'Tails'

In line 1, we import the random module. This is necessary because we use the randint function to
generate a random number. Line 6 is the beginning of the class definition. It begins with the keyword
class, followed by the class name, which is Coin, followed by a colon.

57
The same rules that apply to variable names also apply to class names. However, notice that we started
the class name, Coin, with an uppercase letter. This is not a requirement, but it is a widely used
convention among programmers. This helps to easily distinguish class names from variable names
when reading code.

The Coin class has three methods:

• The init method appears in lines 11 through 12.

• The toss method appears in lines 19 through 23.

• The get_sideup method appears in lines 28 through 21.

Except for the fact that they appear inside a class, notice these method definitions look like any other
function definition in Python. They start with a header line, which is followed by an indented block
of statements. Take a closer look at the header for each of the method definitions (lines 11, 19, and
28) and notice each method has a parameter variable named self:
Line 11: def init (self):

Line 19: def toss(self):

Line 28: def get_sideup(self):

The self parameter is required in every method of a class. Recall from our earlier discussion on
object-oriented programming that a method operates on a specific object’s data attributes. When
a method executes, it must have a way of knowing which object’s data attributes it is supposed to
operate on. That’s where the self parameter comes in. When a method is called, Python makes the
selfparameter reference the specific object that the method is supposed to operate on.

Let’s look at each of the methods. The first method, which is named _ _init_ _, is defined in lines 11
through 12:
def init (self):

[Link] = 'Heads'

58
Most Python classes have a special method named _ _init_ _, which is automatically executed when
an instance of the class is created in memory. The _ _init_ _ method is commonly known as an initializer
method because it initializes the object’s data attributes. (The name of the method starts with two
underscore characters, followed by the word init, followed by two more underscore characters.)

Immediately after an object is created in memory, the _ _init_ _ method executes, and the self
parameter is automatically assigned the object that was just created. Inside the method, the
statement in line 12 executes:
[Link] = 'Heads'

This statement assigns the string 'Heads' to the sideup data attribute belonging to the object that
was just created. As a result of this _ _init_ _ method, each object we create from the Coin class will
initially have a sideup attribute that is set to 'Heads'.

59
The toss method appears in lines 19 through 23:

def toss(self):

if [Link](0, 1) == 0: [Link] = 'Heads'

else:

[Link] = 'Tails'

This method also has the required self parameter variable. When the toss method is called, self will
automatically reference the object on which the method is to operate. The toss method simulates
the tossing of the coin. When the method is called, the if statement in line 20 calls the [Link]
function to get a random integer in the range of 0 through 1. If the number is 0, then the statement
in line 21 assigns 'Heads' to [Link]. Otherwise, the statement in line 23 assigns 'Tails' to
[Link].

Here is the complete code for the tossing of a coin, the following code contains a main() method
which creates an instance of a Coin class prints out the side facing up (Head or Tail). Keep in mind
that, the main()method is outside the class

60
1 import random
2

3 # The Coin class


simulates a coin
that can
# The init method
initializes the # sideup

def init (self):


[Link] = 'Heads'

# The toss method generates a


random number # in the range of
0 through 1. If the number # is
0, then sideup is set to 'Heads'.
# Otherwise, sideup
is set to 'Tails'.

def toss(self):

if [Link](0, 1) == 0:
[Link] = 'Heads'
else:
[Link] = 'Tails'

61
29 return [Link]

30

31 # The main function.

32 def main():

33 # Create an object from the Coin class.

34 my_coin = Coin()

35

36 # Display the side of the coin that is facing up.

37 print('This side is up:', my_coin.get_sideup())

38

39 # Toss the coin.

40 print('I am tossing the coin ...')

41 my_coin.toss()

42

43 # Display the side of the coin that is facing up.

44 print('This side is up:', my_coin.get_sideup())

45

46 # Call the main function.

47 main()

Program Output

This side is up: Heads

I am tossing the coin ...

This side is up: Tails

Program Output

This side is up: Heads

I am tossing the coin ...

This side is up: Heads

Program Output

This side is up: Heads

I am tossing the coin ...


This side is up: Tails

Output

The statement in line 34:

my_coin = Coin()

The expression Coin()that appears on the right side of the = operator causes two things to happen:

1. An object is created in memory from the Coin class.

2. The Coin class’s init method is executed, and the self parameter is automatically set to the
object that was just created. As a result, that object’s sideup attribute is assigned the string 'Heads'.

The next statement to execute is line 37:


print('This side is up:', my_coin.get_sideup())

This statement prints a message indicating the side of the coin that is facing up. Notice the following
expression appears in the statement:
my_coin.get_sideup()

This expression uses the object referenced by my_coin to call the get_sideup method. When the
method executes, the self parameter will reference the my_coin object. As a result, the method
returns the string 'Heads'.

Notice we did not have to pass an argument to the sideup method, even though it has the self
parameter variable. When a method is called, Python automatically passes a reference to the calling
object into the method’s first parameter. As a result, the self parameter will automatically reference
the object on which the method is to operate.

Lines 40 and 41 are the next statements to execute:

print('I am tossing the coin ...') my_coin.toss()


The statement in line 41 uses the object referenced by my_coin to call the toss method. When the
method executes, the self parameter will reference the my_coin object. The method will randomly
generate a number, then use that number to change the value of the object’s sideup attribute.

Line 44 executes next. This statement calls my_coin.get_sideup() to display the side of the coin that
is facing up.

3.2 Hiding Attributes


An object’s data attributes should be private, so that only the object’s methods can directly access
them. This protects the object’s data attributes from accidental corruption. However, in the Coin
class that was shown in the previous example, the sideup attribute is not private. It can be directly
accessed by statements that are not in a Coin class method.

Lines 1 through 30 are omitted. These lines are the same as lines 1 through 30 in the
second example
31# The main function.

32 def main():

33 # Create an object from the Coin class.

34 my_coin = Coin() 35

36 # Display the side of the coin that is facing up.

37 print('This side is up:', my_coin.get_sideup()) 38

39 # Toss the coin.

40 print('I am tossing the coin ...')

41 my_coin.toss()

42

43 # But now I'm going to cheat! I'm going to

44 # directly change the value of the object's

45 # sideup attribute to 'Heads'.

46 my_coin.sideup = 'Heads' 47

48 # Display the side of the coin that is facing up.

49 print('This side is up:', my_coin.get_sideup()) 50

51 # Call the main function.

52 if _ _name_ _ == '_ _main_ _':

53 main()
Program Output

This side is up: Heads

I am tossing the coin ... This side is up: Heads Program Output

This side is up: Heads

I am tossing the coin ... This side is up: Heads Program Output

This side is up: Heads

I am tossing the coin ... This side is up: Heads

Line 34 creates a Coin object in memory and assigns it to the my_coin variable. The statement in line
37 displays the side of the coin that is facing up, then line 41 calls the object’s toss method. Then,
the statement in line 46 directly assigns the string 'Heads' to the object’s sideup attribute:

my_coin.sideup = 'Heads'

Regardless of the outcome of the toss method, this statement will change the my_coin object’s
sideup attribute to 'Heads'. As you can see from the three sample runs of the program, the coin
always lands heads up!

If we truly want to simulate a coin that is being tossed, then we don’t want code outside the class
to be able to change the result of the toss method. To prevent this from happening, we need to make
the sideup attribute private. In Python, you can hide an attribute by starting its name with two
underscore characters. If we change the name of the sideup attribute to sideup, then code outside
the Coin class will not be able to access it.

3.3 Inheritance
3.3.1 Inheritance and the “Is a” Relationship

When one object is a specialized version of another object, there is an “is a” relationship between
them. For example, a grasshopper is an insect. Here are a few other examples of the “is a”
relationship:

• A poodle is a dog.

• A car is a vehicle.

• A flower is a plant.

• A rectangle is a shape.
• A football player is an athlete.

When an “is a” relationship exists between objects, it means that the specialized object has all the
characteristics of the general object, plus additional characteristics that make it special. In object-
oriented programming, inheritance is used to create an “is a” relationship among classes. This allows
you to extend the capabilities of a class by creating another class that is a specialized version of it.

Inheritance involves a superclass and a subclass. The superclass is the general class, and the subclass
is the specialized class. You can think of the subclass as an extended version of the superclass. The
subclass inherits attributes and methods from the superclass without any of them having to
be rewritten. Furthermore, new attributes and methods may be added to the subclass, and that is
what makes it a specialized version of the superclass.

Note: Superclasses are also called base classes, and subclasses are also called derived classes. Either
set of terms is correct.

Let’s look at an example of how inheritance can be used. Suppose we are developing a program that
a car dealership can use to manage its inventory of used cars. The dealership’s inventory includes
three types of automobiles: cars, pickup trucks, and sport-utility vehicles (SUVs). Regardless of the
type, the dealership keeps the following data about each automobile:

• Make

• Year model

• Mileage

• Price

Each type of vehicle that is kept in inventory has these general characteristics, plus its own specialized
characteristics. For cars, the dealership keeps the following additional data:

• Number of doors (2 or 4)

For pickup trucks, the dealership keeps the following additional data:
• Drive type (two-wheel drive or four-wheel drive)

And for SUVs, the dealership keeps the following additional data:

• Passenger capacity

In designing this program, one approach would be to write the following three classes:

• A Car class with data attributes for the make, year model, mileage, price, and the number of doors.

• A Truck class with data attributes for the make, year model, mileage, price, and the drive type.

• An SUV class with data attributes for the make, year model, mileage, price, and the passenger
capacity.

This would be an inefficient approach, however, because all three of the classes have many common
data attributes. As a result, the classes would contain a lot of duplicated code. In addition, if we
discover later that we need to add more common attributes, we will have to modify all three classes.
A better approach would be to write an Automobile superclass to hold all the general data about an
automobile, then write subclasses for each specific type of automobile.

1 # The Automobile class holds general data

2 # about an automobile in inventory. 3

4 class Automobile:

5# The _ _init_ _method accepts arguments for the

6# make, model, mileage, and price. It initializes

7 # the data attributes with these values. 8

9 def _ _init_ _(self, make, model, mileage, price):

10 self._ _make = make

11 self._ _model = model

12 self._ _mileage = mileage

13 self._ _price = price 14

15 # The following methods are mutators for the

16 # class's data attributes. 17

18 def set_make(self, make):

19 self._ _make = make 20

21 def set_model(self, model):

22 self._ _model = model 23

24 def set_mileage(self, mileage):

25 self._ _mileage = mileage 26

27 def set_price(self, price):

28 self._ _price = price 29

30 # The following methods are the accessors

31 # for the class's data attributes. 32


33 def get_make(self):

34 return self._ _make

35

36 def get_model(self):

37 return self._ _model

38

39 def get_mileage(self):

40 return self._ _mileage

41

42 def get_price(self):

43 return self._ _price

44

The Automobile class’s _ _init_ _method accepts arguments for the vehicle’s make, model,
mileage, and price. It uses those values to initialize the following data attributes:

• _ _make

• _ _model

• _ _mileage

• _ _price

(You would recall that a data attribute becomes hidden when its name begins with two underscores.)
The methods that appear in lines 18 through 28 are mutators for each of the data attributes, and
the methods in lines 33 through 43 are the accessors.

The Automobile class is a complete class from which we can create objects. If we wish, we can write a
program that imports the vehicle module and creates instances of the Automobile class. However,
the Automobile class holds only general data about an automobile. It does not hold any of the
specific pieces of data that the dealership wants to keep about cars, pickup trucks, and SUVs. To
hold data about those specific types of automobiles, we will write subclasses that inherit from the
Automobile class.
# The Car class represents
a car. It is a subclass
# of the Automobile class.

class Car(Automobile):
# The _ _init_ _ method accepts
arguments for the

# car's make, model,

def _ _init_ _(self, make, model, mileage, price, doors):

# Call the superclass's _ _init_ _ method and pass

# the required arguments. Note that we also have

# to pass self as an argument.

Automobile._ _init_ _(self, make, model,


mileage, price)

# Initialize the _ _doors attribute. self._

_doors = doors

# The set_doors method is the

mutator for the # _ _doors

attribute.

def set_doors(self, doors):

self._ _doors = doors

# The get_doors method is the

accessor for the # _ _doors


Take a closer look at the first line of the class declaration, in line 48:
class Car(Automobile):

This line indicates that we are defining a class named Car, and it inherits from the Automobile class.
The Car class is the subclass, and the Automobile class is the superclass. If we want to express the
relationship between the Car class and the Automobile class, we can say that a Car is an Automobile.
Because the Car class extends the Automobile class, it inherits all the methods and data attributes
of the Automobile class.

Look at the header for the _ _init_ _method in line 52:


def init (self, make, model, mileage, price, doors):

Notice in addition to the required self parameter, the method has parameters named make, model,
mileage, price, and doors. This makes sense because a Car object will have data attributes for the
car’s make, model, mileage, price, and number of doors. Some of these attributes are created by
the Automobile class, however, so we need to call the Automobile class’s _ _init_ _ method and pass
those values to it. That happens in line 56:

Automobile. init__(self,make, model, mileage, price)

This statement calls the Automobile class’s _ _init_ _ method. Notice the statement passes the self
variable, as well as the make, model, mileage, and price variables as arguments. When that method
executes, it initializes the _ _make, _ _model, _ _mileage, and _ _price data attributes. Then, in line
59, the _ _doors attribute is initialized with the value passed into the doors parameter: self. doors
= doors

The set_doors method, in lines 64 through 65, is the mutator for the _ _doors attribute, and the

get_doors method, in lines 70 through 71, is the accessor for the _ _doors attribute.

def main(self):

my_car = Car('Audi', 2007, 12500, 21500, 4)

# Display the car's data.


print('Make:', my_car.get_make())
print('Model:', my_car.get_model())

print('Mileage:', my_car.get_mileage())
print('Price:', my_car.get_price())

print('Number of doors:', my_car.get_doors())

# Call the main function.

if name == '_ _main_ _':


Source: (Gaddis, 2021)

We create an instance of the Car class, passing 'Audi' as the car’s make, 2007 as the car’s model,
12,500 as the mileage, 21,500.0 as the car’s price, and 4 as the number of doors. The resulting object
is assigned to the my_carvariable.

We then called the object’s get_make, get_model, get_mileage, and get_price methods. Even
though the Car class does not have any of these methods, it inherits them from the Automobileclass.

To check your understanding thus far: Complete the code for pickup truck and SUVs following the
steps in the Car class.

3.4 Polymorphism
The term polymorphism refers to an object’s ability to take different forms. It is a powerful feature
of object-oriented programming. Let’s look at the two polymorphic behaviours:

1. The ability to define a method in a superclass, then define a method with the same name in a

subclass. When a subclass method has the same name as a superclass method, it is often said
that the subclass method overrides the superclass method.

2. The ability to call the correct version of an overridden method, depending on the type of object

that is used to call it. If a subclass object is used to call an overridden method, then the subclass’s
version of the method is the one that will execute. If a superclass object is used to call an
overridden method, then the superclass’s version of the method is the one that will execute.

Here is a simple example of method overriding.


class Parent:

def init (self,a):

self.a=a

def method1(self):

print(self.a*2)

def method2(self):

print(self.a+'!!!')

class Child(Parent):

def init (self,a,b):

self.a=a

self.b=b

def method1(self):

print(self.a*7)

def method3(self):

print(self.a+self.b)

p=Parent('hi')

c=Child('hi','bye')

print('Parent method1:',p.method1())

print('Parent method2:',p.method2())

print()

print('Child method1:',c.method1())

print('Child method2:',c.method2())

print('Child method3:',c.method3())

Source: (Gaddis, 2021)

Program Output

Parent method1: hihi

Parent method2: hi!!!

Child method1: hihihihihihihi

Child method2: hi!!!

Child
We seemethod3: hibyeabove that the child has overridden the parent’s method1, causing it to
in the example
now repeat the string seven times. The child has inherited the parent’s method2, so it can use it
without having to define it. The child also adds some features to the parent class, namely a new
variable b and a new method, method3.

3.5 Review Questions


TRUE/FALSE

1. A mutator method has no control over the way that a class's data attributes are modified.

2. In a UML diagram the first section holds the list of the class's methods.

3. Object-oriented programming allows us to hide the object's data attributes from code that is

outside the object.

4. Procedures operate on data items that are separate from the procedures.

5. All instances of a class share the same values of the data attributes in the class.

6. All class definitions are stored in the library so that they can be imported into any program.

7. The self-parameter is required in every method of a class.

8. A class can be thought of as a blueprint that can be used to create an object.

9. An object is a stand-alone program but is used by programs that need its service.
4 Chapter Four: Graphical User Interface (GUI) – Programming

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Distinguish between two programming methods, procedural and


object-oriented programming.

• Learn how to create and work with classes

• Understand the concept of inheritance and its implementation.

4.1 Introduction to Tkinter

Tkinter is the standard GUI (Graphical User Interface) library that comes bundled with Python. It
provides a simple yet powerful way to create desktop applications with interactive graphical
elements. Tkinter is based on the Tk GUI toolkit, originally developed for the TCL (Tool Command
Language) programming language, and it has been widely adopted as the go-to choice for GUI
development in the Python community.

As a part of the Python standard library, Tkinter is available on most platforms that support Python,
making it highly accessible to developers across different operating systems. Its integration with
Python's syntax and object-oriented nature allows developers to build intuitive and responsive GUI
applications using familiar Python code.

Tkinter offers a range of built-in widgets, such as buttons, labels, entry fields, menus, and more,
which can be easily combined and customized to create sophisticated user interfaces. The library
also provides geometry managers to help with layout management, ensuring widgets are arranged
properly within windows and frames.

Since Tkinter follows an event-driven programming paradigm, applications built with it respond to
user actions and events, such as button clicks or key presses. Developers can define functions, known
as callbacks, to handle these events, enabling dynamic and interactive user experiences.

With Tkinter's straightforward learning curve and extensive documentation, it is an excellent choice
for both beginners looking to dive into GUI programming and experienced developers seeking a
quick and efficient way to create desktop applications with Python. Its simplicity, native integration
with Python, and cross-platform support make Tkinter a reliable and widely used toolkit for graphical
user interface development in Python.

Tkinter in Python Standard Library

Tkinter became a part of the Python standard library with the release of Python 1.4 in 1997. This
integration made Tkinter readily available to all Python users without the need for additional
installations (Gaddis, 2021).

4.1.1 Advantages of using Tkinter for GUI development


• Simple and Easy to Learn: it provides a straightforward and intuitive API, making it easy for
beginners to get started with GUI programming. Its simplicity and clear syntax allow developers to
quickly create basic user interfaces without a steep learning curve.

• Bundled with Python: It doesn’t require installation of additional dependencies or third-party


libraries to use it. It comes pre-installed with Python, ensuring consistent availability across
platforms.

• Cross-Platform Support: Its applications can run on various operating systems, including Windows,
macOS, and Linux, without any modifications. This cross-platform compatibility is a significant
advantage for developers aiming to reach a wide audience.
• Native Look and Feel: Its widgets are styled to match the native look and feel of the underlying
operating system. This means that applications created blends seamlessly with the user's
environment, enhancing user experience and familiarity.

• Extensive Documentation and Community Support: It has a plethora of documentation, tutorials,


and community support. It provides a vast array of resources to help them learn, troubleshoot, and
optimize their Tkinter-based projects.

• Rapid Prototyping and Development: It's simplicity and high-level abstractions allow for quick
prototyping and development of GUI applications. This is particularly advantageous for projects that
require a fast turnaround time.

• Wide Range of Widgets: It offers a variety of built-in widgets, such as buttons, labels, entry fields,
menus, and more. These widgets can be easily customized and combined to create sophisticated
user interfaces.

• Event-Driven Programming: It follows an event-driven programming paradigm, enabling developers


to create responsive and interactive applications. It can be used to define callbacks that respond to
user actions, such as button clicks or key presses.

• Open Source and Free: It is open source and free to use, making it a cost-effective choice for GUI
development in Python projects.

• Suitable for Small to Medium-Sized Projects: It is well-suited for small to medium-sized applications
and projects. It provides a balance between simplicity and functionality, making it an excellent choice
for quick, straightforward GUI development.

4.2 Basic Concepts


Understanding widgets and containers

Tkinter widgets and containers are fundamental components used to build graphical user interfaces.
Understanding the distinction between widgets and containers is essential for effective GUI
development.

Widgets:

- Widgets are the building blocks of a Tkinter GUI. They represent the various graphical elements that
users interact with, such as buttons, labels, entry fields, checkboxes, and more.
- Each widget is a graphical entity with its own properties, behaviour, and appearance.

- Widgets can display information, receive user input, or trigger actions through events and
callbacks.

- Some common methods available for widgets include configuring their appearance (e.g., setting
text, colour, font), attaching event handlers, and managing their position within the GUI.

Containers:

- They are also known as layout managers and are used to organize and arrange widgets within a
window or frame.

- Containers define the positioning and sizing rules for placing widgets, ensuring that they appear
correctly within the GUI.

- It provides three primary layout managers: “pack”, “grid”, and “place”.

- The “pack” geometry manager organizes widgets in a linear fashion, stacking them either
horizontally or vertically.

- The “grid” geometry manager arranges widgets in rows and columns within a table-like structure.

- The “place” geometry manager allows for precise manual placement of widgets, specifying their
exact coordinates.

For more information in Tkinter objects and methods please use the
following link(s):
1. [Link]
4.3 Event-driven programming in Tkinter

Event-driven programming is an important concept which is a GUI library based on the Tk GUI toolkit.
In an event-driven programming paradigm, the flow of the program is determined by events or user
actions rather than following a sequential execution from the beginning to the end of the code.
Events are generated when users interact with the graphical elements (widgets) of the GUI, such as
clicking a button, pressing a key, or moving the mouse. The Tkinter application waits for these events
to occur, and when they do, specific functions called "event handlers" or "callbacks" are executed to
respond to those events.
4.3.1 How does event-driven programming work?
1. Event Binding: To handle events, Tkinter allows developers to bind functions (event handlers) to

specific events that a widget can trigger. For example, you can bind a function to a button widget's
"click" event, so when the button is clicked, the associated function is executed.

2. Main Event Loop: After setting up event bindings and creating the GUI, Tkinter enters the main event

loop. This loop continuously waits for events to occur, such as mouse clicks or keypresses.

3. Event Dispatching: When an event occurs, it dispatches the event to the corresponding widget that

generated it. The widget then checks if there are any bound functions for that particular event.

4. Callback Execution: If a bound function is found for the event, it is executed. These callback
functions can perform various actions, such as updating the GUI, processing user input, or triggering
other functions.

5. Advantages of Event-driven programming

1. Responsiveness: Since the program's flow is based on user actions, the GUI remains responsive even

during long-running operations. This prevents the application from freezing and allows users to
interact with the interface at any time.

2. Modular Code: Event-driven programming encourages writing modular code, where each function

handles specific events or functionalities. This makes the code more organized and easier to
maintain.

3. Asynchronous Behaviour: Events can occur at any time, and the application responds to them as
they happen. This asynchronous behaviour allows for smooth multitasking and concurrent event
handling.

4. User Interaction: Event-driven programming is well-suited for GUI development, as it allows for the
creation of interactive applications that respond dynamically to user input.

4.4 Using the TkinterModule


In Python, you can use the tkinter module to create simple GUI programs. Python does not have GUI
programming features built into the language itself. However, it comes with a module named tkinter
that allows you to create simple GUI programs. The name “tkinter” is short for “Tk interface.” It is
named this because it provides a way for Python programmers to use a GUI library named Tk. Many
other programming languages use the Tklibrary as well.
4.4.1 Setting up Tkinter and creating a window
Setting up Tkinter and creating a window is the first step in building graphical user interfaces (GUIs)
using Tkinter. It involves importing the Tkinter module, creating the main window, and customizing
its properties. Here's a brief overview of the process:

1. Import the Tkinter Module: To use Tkinter, you need to import the tkinter module in your Python

script. You can use the alias tk to make it easier to reference Tkinter's classes and functions.
#python

import tkinter as tk

Create the Main Window: The main window is the foundation of your GUI. It is created using the

Tk()constructor. This window acts as the parent container for other widgets.
#python

root = [Link]()

2. Customize the Window: After creating the main window, you can customize its properties, such as

the title, size, and background colour.

#python

[Link]("My Tkinter Window") # Set the title of the window [Link]("400x300") # Set the window size (width
x height) [Link](bg="white")# Set the background color of the window

3. Start the Main Event Loop: The main event loop is essential for Tkinter applications to respond to user
interactions and events. It starts by calling the mainloop() method on the main window. #python
[Link]()

Putting it all together, a simple Tkinter program to create a basic window looks like this:
#python

import tkinter as tk

# Create the main window root = [Link]()

# Customize the window [Link]("My Tkinter Window") [Link]("400x300") [Link](bg="white")

# Start the main event loop [Link]()

When you run this script, a window with the specified title, size, and background colour will appear.
NB: Remember that the mainloop()function is a blocking call, which means it will keep the window
running and responsive to user interactions until the window is closed or the program is terminated.

The following code extract is from the prescribed textbook, you are required to test the code in your
IDE.

Code Extract: empty_window.py Source: (Gaddis, 2021)

4.5 Configuring widget properties


Each widget in Tkinter has various properties that can be customized to control its appearance,
behaviour, and interactions.

1. Using the Constructor Arguments: When creating a widget, you can pass specific arguments to the
widget's constructor to set initial properties. The constructor arguments vary depending on the
widget type. For example, to set the text of a “Label”, you can use the “text” argument, and to set
the width of an “Entry”, you can use the “width” argument.
#python

import tkinter as tk root = [Link]()

# Example of configuring widget properties during widget creation label = [Link](root, text="Hello, Tkinter!")

entry = [Link](root, width=20)

[Link]() [Link]() [Link]()

2. Using the configure() Method: After creating a widget, you can use the configure()method

to change its properties dynamically. The configure() method takes the name of the property
you want to change and the new value.
#python

import tkinter as tk

def change_text(): [Link](text="Button clicked!")

root = [Link]()

label = [Link](root, text="Hello, Tkinter!") [Link]()

button = [Link](root, text="Click me!", command=change_text) [Link]()

[Link]()

In the above example, when the button is clicked, the change_text()function is called, which
uses the configure()method to change the text of the label to "Button clicked!".

Displaying Text with Label Widgets


A label can be created in the UI in Python using the Labelclass. The Labelconstructor requires the top-
level window object and options parameters. Option parameters are similar to the Buttonobject.

from tkinter import * window=Tk()

lbl=Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16))

[Link](x=60, y=50) [Link]('Hello Python') [Link]("300x200+10+10") [Link]()

Source : (Teacher, 2023)

Source: (Gaddis, 2021)


The MyGUIclass in this program is very similar to the one you saw previously in example. The _

_init_ _ method builds the GUI when an instance of the class is created. Line 8 creates a root widget and

assigns it to self.main_window. The following statement appears in lines 12 and 13: [Link] = [Link]
(self.main_window, text= 'Hello World!')

This statement creates a Label widget and assigns it to [Link]. The first argument inside the
parentheses is self.main_window, which is a reference to the root widget. This simply specifies that we
want the Label widget to belong to the root widget. The second argument is text= 'Hello World!'. This
specifies the text that we want to be displayed in the label (Gaddis, 2021).

The following code extract creates a GUI window with two labels.

Source: (Gaddis, 2021)


4.6 Organizing Widgets with Frames
A Frame is a container that can hold other widgets. You can use Frames to organize the widgets in
a window. A Frame is a container. It is a widget that can hold other widgets. Frames are useful for
organizing and arranging groups of widgets in a window. For example, you can place a set of widgets
in one Frame and arrange them in a particular way, then place a set of widgets in another Frame
and arrange them in a different way (Gaddis, 2021). This is demonstrated in the example below:

Programming 512 – Study


Guide
Source: (Gaddis, 2021)

Output:

Figure 4.1 – GUI Layout Source: (Gaddis, 2021)

4.7 Organizing Widgets with Frames


You use the Button widget to create a standard button in a window. When the user clicks a button, a
specified function or method is called. An info dialog box is a simple window that displays a message
to the user and has an OK button that dismisses the dialog box. You can use the [Link]
module’s showinfofunction to display an info dialog box (Gaddis, 2021).

A Button is a widget that the user can click to invoke an action. When you create a Button widget you
can specify the text that is to appear on the face of the button and the name of a callback function. A
callback function is a function or method that executes when the user clicks the button. A callback

function is also regarded as an event handler because it handles the event that occurs when the user
clicks a button (Gaddis, 2021). This is demonstrated by the following example on shown in the
prescribed textbook.
Learn how to implement an Exit button using Tkinder and the
destroy( ) non- class method
[Link]
button

4.8 Getting Input with the EntryWidget


An input widget is a rectangular area in which the user can provide an input into an application. To
achieve this, we use the Entry widget's get method to accept the data entered into the widget by the
user. The get method returns a string, so it will have to be converted to the appropriate data type if
the Entry widget is used for numeric input (Gaddis, 2021). This is demonstrated in the following
example:
Source: (Gaddis, 2021)
Output:

Ensure that you cover the following key widgets or Tkinder components using the links provided.
These are critical components that are covered in the prescribed textbook and required for this
module.

Learn the following key concepts by clicking on the following links:


Using Tkinder labels as output:

[Link]

Using Radio buttons: [Link]


buttons-in- [Link]

Using Check Buttons: [Link]

4.9 Listbox Widgets


A Listboxwidget displays a list of itemsZ and allows the user to select an item from the list.
Source : (Gaddis, 2021)

Output:

4.10 Review Questions

1. When a program runs in a text-based environment, such as a command line interface, what

determines the order in which things happen?

2. What does a widget’s pack method do?

3. What does the tkinter module’s mainloop function do?

4. If you create two widgets and call their pack methods with no arguments, how will the widgets be

arranged inside their parent widget?

5. How do you specify that a widget should be positioned as far left as possible inside its parent widget?
6. How do you retrieve data from an Entry widget?

7. How can you use a StringVar object to update the contents of a Label widget?

8. How can you use an IntVar object to determine which Radiobutton has been selected in a group of

Radiobuttons?

9. How can you use an IntVar object to determine whether a Checkbutton has been selected?
5 Chapter Five: Interfacing with Databases

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Demonstrate an understanding of key database concepts

• Ability to insert, modify and delete database records using SQLite and
Python

• Able to create new databases and tables using Python and SQLite

• Able to search for specific data within a database table using an


appropriate programming language

5.1 Introduction into Databases


A database management system (DBMS) is software that manages large amounts of data. If an
application needs to store only a small amount of data, conventional files work well. These types of
files are not viable, however, when a sizable amount of data must be stored and manipulated. Several
businesses keep heaps of data items in files. When a conventional file holds this much data, regular
tasks such as searching, inserting, and deleting become difficult to achieve.

When developing applications that work with large volumes of data, developers elect a database
management system instead of traditional files. A database management system (DBMS) is software
that is specifically designed to store, retrieve, and manipulate large amounts of data in an organized
and efficient manner. An application developed in Python, or another language can be written to
use a DBMS to manage its data. Rather than retrieving or manipulating the data directly, the
application can send instructions to the DBMS. The DBMS carries out those instructions and sends the
results back to the application.
This is illustrated in figure 5.1.

Figure 5.1

5.1.1 What is SQL?


SQL stands for Structured Query Language and is a standard language for working with DBMSs. It
was originally developed by IBM in the 1970s. Since then, most database software vendors have
adopted SQL as the language for interacting with their DBMS. This module uses simple SQL
statements to link your application to a SQL database.

5.1.2 The Python SQLite connector


There are many DBMSs in use today, and Python can interrelate with several of them. Some of the
most common include MySQL, Oracle, Microsoft SQL Server, and SQLite. For this module we will
employ SQLite. SQLite is easy to use and is automatically installed on your system when you install
Python. To use SQLite in Python, you must import the sqlite3 module with the following statement:
import sqlite3

5.2 Tables and Rows


A database management system (DBMS) stores data in an organised manner into one or more
related tables (collection of tables). The data that is stored in a table is organized into rows and
columns. A row is a complete set of data about a single item and is also referred to as a record. The
data that is stored in a row is divided into columns. Each column holds an individual piece of data
about the item also referred to as a field. For example, suppose we are developing a contact list
application and we want to store a list of names and phone numbers in a database (Gaddis, 2021).
We originally store the following list:

Name Contact Number


Tom Sawyer 031-3077123

Mary Jane 011-7068979

Peter Parker 012-5007811

Each column i.e., “Name” and “Contact Number” is referred to as a field. Therefore, in the above
table we have two fields Name and Contact Number respectively. We also have three rows or
specifically records.

Column Data Types

Ensure that you refer to the prescribed textbook for more information on the
structure of the database.
When creating a database table, you must specify the data types of the columns/fields. However,
the data types that can be selected are not Python data types. These are data types provided by the
DBMS. Since we will be using SQLite in this module, we will choose from the data types provided by
this DBMS as listed below:

• Null. The value is a NULL value.

• Integer. The value is a signed integer, stored in 0, 1, 2, 3, 4, 6, or 8 bytes depending on the


magnitude of the value.

• Real. The value is a floating-point value, stored as an 8-byte IEEE floating point number.

• Text. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).

• Blob. The value is a blob of data, stored exactly as it was input.

5.2.1 Primary Key

A primary key refers to a column in a relational database table that is unique for each record. This is
a unique identifier such as a serial number, ID number, or vehicle identification number (VIN). A
relational database can have only one primary key. Each record of data must have a primary key value,
for us to reference or uniquely identify it.
Figure 5.2 - Primary Key

Source: Invalid source specified.

Opening and Closing a Database Connection with SQLite

Before you can work with a database, you must connect to the database. When you are finished
working with the database, you must close the connection. The typical process of using an SQLite
database can be summarized with the following pseudocode:

• Connect to the database: An SQLite database is stored in a file on the system’s disk. This step
establishes a connection between the program and a specific database file. If the database file does
not exist, it will be created.

• Get a cursor for the database: A cursor is an object that is able to access and manipulate the data in
a database.

• Perform operations on the database: Once you have a cursor, you can access and modify the data in
the database as needed. You can use the cursor to retrieve data, insert new data, update existing
data, and delete data.

• Commit changes to the database: When you make changes to a database, those changes aren’t
actually saved in the database until you commit them. After performing any operations that modify
the contents of a table, be sure to commit those changes to the database.

• Close the connection to the database: When you are finished using the database, you should close
the connection.

To connect to a database, we call the sqlite3module’s connect function. The following

interactive sessions shows an example:

>>> import sqlite3

>>> conn = [Link]('[Link]')


Code Extract:(sqlite_skeleton.py)

Specifying the Database’s Location on Disk

When you pass a file name that does not contain a path as an argument to the connectfunction, the
DBMS assumes the file’s location is the same as that of the program. For example, suppose a
program is located in the following folder on a Windows computer (Gaddis, 2021):
C:\Users\Hannah\Documents\Python

If the program is running and it executes the following statement, the file [Link] created in
the same folder: [Link]('[Link]')

If you want to open a connection to a database file in a different location, you can specify a path as
well as a filename in the argument that you pass to the connect function. If you specify a path in a
string literal (particularly on a Windows computer), be sure to prefix the string with the letter r. Here
is an example: [Link](r'C:\Users\Hannah\temp\[Link]')

5.3 Creating a Table


Once you have created a new database using the sqlite3 module’s connect function, you must add
one or more tables to the database. To add a table, you will use the SQL statement CREATE TABLE.
Here is the general syntax of the CREATE TABLEstatement (Gaddis, 2021):

CREATE TABLE TableName (ColumnName1 DataType1, ColumnName2 DataType2, etc...)


In the general format, TableName is the name of the table that you are creating. ColumnName1 is the
name of the first column, and DataType1 is the SQL data type for the first column. ColumnName2 is
the name of the second column, and DataType2 is the SQL data type for the second column. This
sequence repeats for all the columns in the table. For example, look at the following SQL statement:
CREATE TABLE Inventory (ItemName TEXT, Price REAL)

Code Extract:(add_table.py)

5.4 Deleting a Table


If you need to delete a table, you can use the SQL statement DROP TABLE. The general syntax of the

DROP TABLEstatement: DROP TABLE TableName

In the general format, TableName is the name of the table that you are deleting. After this statement
executes, the table and all of the data it contains will be deleted. For example, assuming cur is a
Cursorobject, here is an example of how you would delete a table named Temp:

>>> [Link]('DROP TABLE Temp')


DROP TABLE IF EXISTS TableName

>>> [Link]('DROP TABLE IF EXISTS Temp')

5.5 Adding data to a table


You use the INSERT statement in SQL to insert a new row into a table. Once you have created a
database file, and created one or more tables in the database, you can add rows to the table(s). In
SQL, the INSERT statement is used to insert a row into a database table. Here is the general syntax
(Gaddis, 2021):

INSERT INTO TableName (ColumnName1, ColumnName2, etc...) VALUES (Value1, Value2, etc...)

Assuming cur is a Cursor object for the [Link] database, here is an example that inserts a row
into the Inventorytable:

[Link]('''INSERT INTO Inventory (ItemID, ItemName, Price) VALUES (1, "Cooldrink", 7.50)''')
Code Extract:(insert_record.py)
5.6 Inserting the values of variables
Often you will need to insert the values of variables into the columns of a database table. For example,
you might need to write a program that gets values from the user, and then inserts those values into
a row. To accomplish this, SQLite allows you to write an SQL statement in which question marks
appear as placeholders for values. For example, look at the following string containing an INSERT
statement: '''INSERT INTO Inventory (ItemName, Price) VALUES (? ?)'''

Code Extract:(insert_variables.py)
5.7 Querying Data with the SQL SELECTStatement
The SELECTstatement is used in SQL to retrieve data from a database.

In this section, we use the SELECT statement to retrieve rows from a table. In our examples, we will
work with a sample database. The database contains data from a fabricated company that sells
gourmet chocolate products. The database is named [Link], and it contains a Products table
with the following columns:

Products Table:

ProductID - INTEGER PRIMARY KEY NOT NULL

Description - TEXT UnitCost — REAL RetailPrice — REAL UnitsOnHand — INTEGER

Code Extract :(get_descriptions_prices.py)


5.8 Updating exiting rows
You use the UPDATE statement in SQL to change the value of an existing row. You use the DELETE
statement to delete rows from a table. In SQL, the UPDATE statement is used to change the contents
of an existing row in a table. Using our [Link] database as an example, suppose the price of
chocolate truffles changes. To update the price in the database, we could use an UPDATE statement
to change the RetailPrice column for that row in the Products table. Here is the syntax of the UPDATE
statement (Gaddis, 2021):

UPDATE Table

SET Column = Value

WHERE Criteria

Code Extract: (product_price_updater.py)


NB: Refer to the prescribed textbook for a detailed discussion on
updating existing records/rows within
a table
Additional Reading: As part of database connectivity, it is important that you
research the following:

• Handling Database Exceptions

• What is relational data?


5.9 Review Questions
•Primary and Foreign keys
1. If you are writing an application to store the customer and inventory records for a large business,

why would you not want to use traditional text or binary files?

2. When we speak of database organization, we speak of such things as rows, tables, and columns.

Describe how the data in a database is organized into these conceptual units.

3. What is a primary key?

4. What SQL data types correspond with the following Python types?

Int, float, str

5. What are the relational operators in SQL for the following comparisons?

Greater-than, Less-than, Greater-than or equal-to, Less-than or equal-to Equal-to, Not equal-to


6 References

Brian, H., 2022. A Practical Introduction to Python Programming. First Edition ed. s.l.:Independently
Published.

Gaddis, T., 2021. Starting Out with Python, Global Edition. 5th ed. s.l.:Pearson International
Content. Teacher, T., 2023. TutorialsTeacher. [Online]

Available at: [Link] [Accessed


25 July 2023].

Tony, G., 2021. Starting Out with Python. Fifth Edition ed. s.l.:Pearson.

Matthes, E. (2021) Python Crash Course: A Hands-On, Project-Based Introduction to Programming.


3rd ed. No Starch Press.

Zelle, J. (2022) Python Programming: An Introduction to Computer Science. 4th ed. Franklin, Beedle
& Associates.

Severance, C.R. (2021) Python for Everybody: Exploring Data in Python 3. 2nd ed. CreateSpace
Independent Publishing Platform.

Sweigart, A. (2023) Beyond the Basic Stuff with Python: Best Practices for Writing Clean Code. 1st
ed. No Starch Press.

Saha, D. (2022) Python Programming and Numerical Methods: A Guide for Engineers and
Scientists. 1st ed. Academic Press.

Gupta, S. and Chopra, R. (2021) Core Python Programming. 3rd ed. BPB Publications.

Shaw, Z.A. (2020) Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly
Beautiful World of Computers and Code. 1st ed. Addison-Wesley.

Maruch, S. and Maruch, D. (2021) Python Programming for Beginners. 1st ed. Wiley.

Bader, D. (2021) Python Tricks: A Buffet of Awesome Python Features. 2nd ed. Addison-Wesley
Professional.

Summerfield, M. (2020) Programming in Python 3: A Complete Introduction to the Python


Language. 2nd ed. Addison-Wesley.

Guttag, J. (2021) Introduction to Computation and Programming Using Python: With Application to
Computational Modeling and Understanding Data. 3rd ed. MIT Press.
Beazley, D.M. and Jones, B.K. (2021) Python Cookbook: Recipes for Mastering Python 3. 3rd ed.
O'Reilly Media.

Moore, M. (2021) Mastering GUI Programming with Python: Develop Impressive Cross-Platform
GUI Applications with PyQt. 2nd ed. Packt Publishing.

Wood, A. (2022) Python for Data Analysis: Data Wrangling with Pandas, NumPy, and SQL. 2nd ed.
O'Reilly Media.
Programming 512 offers a solid foundation in Python, positioning it as a versatile tool for software
development, data science, and emerging technologies. Python’s prominence as a fundamental
language in the 21st century makes this module essential for students aspiring to thrive in
programming and technology-driven fields. The skills acquired in this module lay the groundwork
for future endeavors in areas such as machine learning, artificial intelligence, and automation,
ensuring that students are well-prepared to navigate and excel in the rapidly evolving technological
landscape.

In your second year, you will embark on a journey of learning other programming languages and
technologies, including Internet Programming, which blends PHP, HTML, CSS, and SQL, as well as
C++. In addition, you will engage with other specialized modules such as Machine Learning, Big Data,
and the Internet of Things (IoT), broadening your skill set and preparing you for the demands of
emerging technologies and advanced software development.

The IT qualification at Richfield College stands as a beacon of academic innovation and professional
readiness. It equips students with the skills and credentials necessary for thriving in the IT industry.
By combining foundational knowledge, practical expertise, and global recognition, the program not
only prepares students for immediate employment but also sets them on a trajectory for long-term
career success.

You might also like