Programming 512 Student Guide
Programming 512 Student Guide
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
LEARNER GUIDE
MODULE: PROGRAMMING 512
PREPARED ON BEHALF OF
RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD
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
3
4.9 Listbox Widgets................................................................................................................ 90
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:
• How to iterate over a list, searching for items in a list, and calculating
the sum and average of items in a list.
• Understanding of Tuples
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:
The items that are enclosed in brackets and separated by commas are the list elements.
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:
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:
In this example, the print function will display the elements of the list like this:
for n in numbers:
print(n)
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:
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:
index = 0
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:
40 30 20 10
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]
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:
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:
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)
Run the code to slice the list omitting the start value:
print(numbers[: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.
[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]
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:
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]
another example:
my_list = ['beta', 'alpha', 'delta', 'gamma'] print('Original order:', my_list) my_list.sort()
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]
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]]
scores[0][1]
scores[0][2]
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]
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
In fact, tuples support all the same operations as lists, except those that change the contents of the
list. Tuples support the following:
• Slicing expressions
• The in operator
number_tuple = (1, 2, 3)
number_list = list(number_tuple)
print(number_list)
Output
[1, 2, 3]
print(str_tuple)
Output
('one', 'two', 'three')
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":
print(yellow) print(red)
Output:
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
Output
apple banana
Review Questions
numbers[2] = 99
print(numbers)
numbers = [1, 2, 3, 4, 5]
numbers[2] = 99
print(numbers)
numbers = list(range(3))
print(numbers)
numbers = [10] * 5
print(numbers)
for n in numbers:
print(n)
numbers = [1, 2, 3, 4, 5]
print(numbers[−2])
numbers1 = [1, 2, 3]
print(numbers2)
print(numbers3)
numbers1 = [1, 2, 3]
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.
• Use methods like get(), keys(), values(), and items() for manipulation
and retrieval.
• Define sets, their characteristics, and how they differ from other data
structures.
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.
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.
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
• 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'.
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:
• Line 7 tries to delete the element with the key 'Chris' again. Because the element no longer exists, a
KeyErrorexception is raised.
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.
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].
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.
You can use the for loop in the following general format to iterate over all the keys in a dictionary:
for var in dictionary:
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 5 prints the key variable, followed by the value that is associated with that key.
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.
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!
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'.
• 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.
• 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:
• 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.
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 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().
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.
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:
• 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:
• 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:
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
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:
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.1 An element in a dictionary has two parts. What are they called?
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
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]
print(len(stuff))
for k in stuff:
print(k)
2.10 What is the difference between the dictionary methods pop and popitem?
which each element contains a name from the names list as its key, and the length
'Joanne':'704-555−3333', 'Kurt':'919-555−3333'}
containing the elements of phonebook that have a value starting with '919'.
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?
2.22 After the following statement executes, what elements will be stored in the
myset set?
2.23 After the following statement executes, what elements will be stored in the
myset set?
2.25 After the following statement executes, what elements will be stored in the
myset set?
[Link]([1, 2, 3])
2.26 After the following statement executes, what elements will be stored in the
52
myset set?
[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?
set3 = [Link](set2)
2.30 After the following code executes, what elements will be members of set3?
set3 = [Link](set2)
2.31 After the following code executes, what elements will be members of set3?
set3 = [Link](set2)
2.32 After the following code executes, what elements will be members of set3?
set3 = [Link](set1)
2.33 After the following code executes, what elements will be members of set3?
set3 = set2.symmetric_difference(set2)
54
3 Chapter Three : Object Oriented Programming (OOP)
LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:
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
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.
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):
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):
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
def toss(self):
if [Link](0, 1) == 0:
[Link] = 'Heads'
else:
[Link] = 'Tails'
61
29 return [Link]
30
32 def main():
34 my_coin = Coin()
35
38
41 my_coin.toss()
42
45
47 main()
Program Output
Program Output
Program Output
Output
my_coin = Coin()
The expression Coin()that appears on the right side of the = operator causes two things to happen:
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'.
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.
Line 44 executes next. This statement calls my_coin.get_sideup() to display the side of the coin that
is facing up.
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():
34 my_coin = Coin() 35
41 my_coin.toss()
42
46 my_coin.sideup = 'Heads' 47
53 main()
Program Output
I am tossing the coin ... This side is up: Heads Program Output
I am tossing the coin ... This side is up: Heads Program Output
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.
4 class Automobile:
35
36 def get_model(self):
38
39 def get_mileage(self):
41
42 def get_price(self):
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
_doors = doors
attribute.
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.
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:
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):
print('Mileage:', my_car.get_mileage())
print('Price:', my_car.get_price())
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.
self.a=a
def method1(self):
print(self.a*2)
def method2(self):
print(self.a+'!!!')
class Child(Parent):
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())
Program Output
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.
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
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.
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:
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 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).
• 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.
• 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.
• 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.
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.
- 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.
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.
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
#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
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.
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
# Example of configuring widget properties during widget creation label = [Link](root, text="Hello, Tkinter!")
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
root = [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!".
_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.
Output:
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
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.
[Link]
Output:
1. When a program runs in a text-based environment, such as a command line interface, what
4. If you create two widgets and call their pack methods with no arguments, how will the widgets be
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:
• Ability to insert, modify and delete database records using SQLite and
Python
• Able to create new databases and tables using Python and SQLite
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
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.
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:
• 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).
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
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.
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]')
Code Extract:(add_table.py)
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:
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:
UPDATE Table
WHERE Criteria
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.
4. What SQL data types correspond with the following Python types?
5. What are the relational operators in SQL for the following comparisons?
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]
Tony, G., 2021. Starting Out with Python. Fifth Edition ed. s.l.:Pearson.
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.
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.