Grade 13 ICT Resource Material Python
Grade 13 ICT Resource Material Python
Grade 13
Competency 9.6 and 9.7: Python programming
Reading Materials:
Introduction to Python
Python is a popular programming language. It was created in 1991 by Guido van Rossum.
It is used for:
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This
means that prototyping can be very quick.
Python can be treated in a procedural way, an object-orientated way or a functional way.
Python was designed to for readability, and has some similarities to the English language with influence
from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions
and classes. Other programming languages often use curly-brackets for this purpose.
Python Install
To check if you have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line (cmd.exe):
If you find that you do not have python installed on your computer, then you can download it for free from the
following website: https://www.python.org/downloads/
ex1.py
Python Comments
Comments start with a #, and Python will render the rest of the line as a comment:
Unlike other programming languages, Python has no command for declaring a variable.
Example 2
x=5
y = "John"
print(x)
print(y)
Example 3
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules
for Python variables:
Output Variables
Example 5
x=5
y = 10
print(x + y)
Example 6
x=5
y = "John"
print(x+y)
Python Numbers
int
float
complex
Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting.
Python is an object-orientated language, and as such it uses classes to define data types, including its
primitive types.
int() - constructs an integer number from an integer literal, a float literal (by rounding down to the
previous whole number), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the
string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float
literals
Example 7
Integers:
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
Example 8
Floats:
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
Example 9
Strings:
x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
Strings can be output to screen using the print function. For example: print("hello").
Example 10
a = "Hello, World!"
print(a[1])
print(a[2:5])
print(a.strip())
print(len(a))
print(a.lower())
print(a.upper())
print(a.replace("H", "J"))
print(a.split(","))
Command-line String Input
The following example asks for the user's name, then, by using the input() method, the program prints
the name to the screen:
Example 11
Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
is not Returns true if both variables are not the same object x is not y
not in Returns True if a sequence with the specified value is not x not in y
present in the object
Python Bitwise Operators
& AND Sets each bit to 1 if both bits are 1 (a & b) (means 0000 1100)
^ XOR Sets each bit to 1 if only one of two bits is 1 (a ^ b) = 49 (means 0011 0001)
~ NOT Inverts all the bits (~a ) = -61 (means 1100 0011 in
2's complement form due to a
signed binary number.
<< Zero fill Shift left by pushing zeros in from the right and
a << 2 = 240 (means 1111 0000)
left shift let the leftmost bits fall off
Operator Description
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
Sequential: default mode. Sequential execution of code statements (one line after another)
-- like following a recipe
Selection: used for decisions, branching -- choosing between 2 or more alternative paths.
In Python, these are the types of selection statements:
if
if-else
if-elif-else
Repetition: used for looping, i.e. repeating a piece of code multiple times in a row. In
Python, there are three types of loops:
while
for
Example 12
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation
Python relies on indentation, using whitespace, to define scope in the code. Other programming
languages often use curly-brackets for this purpose.
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
Example 13
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Example 14
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Python Loops
Example 15
i=1
while i < 6:
print(i)
i += 1
With the break statement we can stop the loop even if the while condition is true:
Example 16
i=1
while i < 6:
print(i)
if (i == 3):
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example 17
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Example 18
With the break statement we can stop the loop before it has looped through all the items:
Example 19
With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example 20
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example 21
def my_function():
print("Hello from a function")
my_function()
Parameters
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
Example 22
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Example 23
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all functions.
When you call a function, the variables declared inside it are brought into scope.
Example 25
total = 0; # This is global variable
# Function definition is here
def sum(arg1,arg2):
# Add both the parameters and return them
total=arg1+arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return total;
Data structures
o Strings
o Lists
o Tuples
o Dictionaries
Strings – Refer previous example 10 (In Competency 9.6 and 9.7 part)
List
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets.
Example 26
Create a List:
Example 27
Print the second item of the list:
Example 28
Change the second item:
Example 30
Check if "apple" is present in the list:
Example 31
Print the number of items in the list:
Example 34
The remove() method removes the specified item:
Example 35
The del keyword removes the specified index:
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
Example 37
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Example 38
Return the item in position 1:
Example 40
Iterate through the items and print the values:
Example 42
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Tuples are unchangeable, so you cannot remove items from it, but you can delete the
tuple completely.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of where it was found
Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries
are written with curly brackets, and they have keys and values.
Example 43
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Example 44
Get the value of the "model" key (There is also a method called get() that will give you the same
result:)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
x = thisdict.get("model")
print(x)
Example 45
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Example 46
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Example 47
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Example 48
You can also use the values() function to return values of a dictionary.
Loop through both keys and values, by using the items() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
print("-----------------")
for x, y in thisdict.items():
print(x, y)
Example 49
Check if "model" is present in the dictionary (Check if Key Exists).
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Example 50
Print the number of items in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Example 51
Adding an item to the dictionary is done by using a new index key and assigning
a value to it.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
Example 52
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example 53
The popitem() method removes the last inserted item.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example 54
The del keyword removes the item with the specified key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example 55
The clear() keyword empties the dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing the a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value
Python has several functions for creating, reading, updating, and deleting files.
Uses basic file operations (open, close, read write and append)
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
To open a file for reading it is enough to specify the name of the file:
f = open("n1.txt")
f = open("n1.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Assume we have the following file, located in the same folder as Python:
n1.txt
The open() function returns a file object, which has a read() method for reading the content of the
file:
Example 56
f = open("n1.txt", "r")
print(f.read())
f = open("n1.txt", "r")
print(f.read(5))
Read Lines
Example 58
f = open("n1.txt", "r")
print(f.readline())
Example 59
f = open("n1.txt", "r")
for x in f:
print(x)
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("n1.txt", "a")
f.write("Now the file has one more line!")
Example
f = open("n1.txt", "w")
f.write("Woops! I have deleted the content!")
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example 60
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("n1.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exist before you try to delete it:
Example
import os
if os.path.exists("n1.txt"):
os.remove("n1.txt")
else:
print("The file does not exist")
Delete Folder
Example
import os
os.rmdir("myfolder")
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
RDBMS
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows.
Python MySQL
MySQL Database
To be able experiment with the code examples, you should have MySQL installed on your
computer.
Or
Or
Python needs a MySQL driver to access the MySQL database. "MySQL Connector" driver can be used for
that. PIP can be used to install "MySQL Connector". PIP is a package manager for Python packages, or
modules. PIP is most likely already installed in Python environment (When installing a Python, select
“Customize installation” instead of “Install Now”. Then PIP will be installed automatically).
Navigate the command line to the location of Python's script directory, and type the
following to check PIP is installed.
If PIP is not installed, download and install it from this page: https://pypi.org/project/pip/
Navigate the command line to the location of Python's script directory, and type the following to
Download and install "MySQL Connector":
To test if the installation was successful, or if you already have "MySQL Connector" installed,
create a Python page with the following content. If the below code was executed with no errors,
"MySQL Connector" is installed and ready to be used.
import mysql.connector
Create Connection
Use the username and password of MySQL database to create a connection.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE student (
regNo VARCHAR(10) NOT NULL,
name VARCHAR(150) NOT NULL,
address VARCHAR(250),
contactNo VARCHAR(10), PRIMARY KEY(regNo))"
)
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
mycursor.execute("ALTER TABLE student ADD COLUMN dob DATE")
MySQL Drop Table
Example 65
Delete student table
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
mycursor.execute("DROP TABLE student")
Example 66
Insert a record in the "student" table
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
sql = "INSERT INTO student (regNo, name, address, contactNo, dob) VALUES (%s, %s, %s, %s, %s)"
val = ("1200", "John", "Highway 21", "0715623410", "2000-10-21")
mycursor.execute(sql, val)
Example 67
Insert Multiple Rows
To insert multiple rows into a table, use the executemany() method. The second parameter of
the executemany() method is a list of tuples, containing the data that want to insert.
sql = "INSERT INTO student (regNo, name, address, contactNo, dob) VALUES (%s, %s, %s, %s, %s)"
val = [
('1201', 'Peter', 'Lowstreet 4', '0715874510', '2000-06-21'),
('1202', 'William', 'Central st 954', '0775857410', '2000-03-11'),
('1203', 'Viola', 'Sideway 1633', '0710055210', '2000-08-09')
]
mycursor.executemany(sql, val)
mydb.commit()
Select all records from the "student" table, and display the result.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM student")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Example 69
Select only the regNo, name and address columns:
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Select with filter
When selecting records from a table, selection can be filtered by using the "WHERE" statement.
Example 70
Select record(s) where the birthday is “2000-09-09 “.
Example 71
Select records where the contactNo start with the"071"
mycursor.execute("SELECT name, contactNo FROM student WHERE contactNo LIKE '071%' ")
Use the ORDER BY statement to sort the result in ascending or descending order.
The ORDER BY keyword sorts the result ascending by default. To sort the result in descending
order, use the DESC keyword.
Example 72
Sort the result alphabetically by name.
Example 74
Overwrite the name column from "Viola" to "Mathias".
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
sql = "UPDATE student SET name='Mathias' WHERE name='Viola' "
mycursor.execute(sql)
mydb.commit()
MySQL Delete
Records can be deleted from an existing table by using the "DELETE FROM" statement.
Example 75
Delete any record where the address is "Park Lane 38".
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="school"
)
mycursor = mydb.cursor()
sql = "DELETE FROM student WHERE address=' Park Lane 38' "
mycursor.execute(sql)
mydb.commit()
Searching Techniques
Searching is the algorithmic process of finding a particular item in a collection of items. A search
typically answers either True or False as to whether the item is present. On occasion it may be modified to
return where the item is found.
In Python, there is a very easy way to ask whether an item is in a list of items. We use the in operator.
Sequential Search
When data items are stored in a collection such as a list, they have a linear or sequential relationship. Each
data item is stored in a position relative to the others. In Python lists, these relative positions are the index
values of the individual items. Since these index values are ordered, it is possible to visit them in sequence.
In this type of search, a sequential search is made over all items one by one. Every item is checked and if a
match is found then that particular item is returned, otherwise the search continues till the end of the data
structure.
Example 75
Write a function which implements sequential search. It should take a list and an element as a parameter,
and return true. If the element is not in the list, the function should return false. If the element is in the list
multiple times, the function should return true when the first match is found.
Bubble sort
The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that
are out of order. Each pass through the list places the next largest value in its proper place. In essence, each
item “bubbles” up to the location where it belongs.
The exchange operation, sometimes called a “swap,” is slightly different in Python than in
most other programming languages. Typically, swapping two elements in a list requires a
temporary storage location (an additional memory location). A code fragment such as
temp = alist[i]
alist[i] = alist[j]
alist[j] = temp
It will exchange the ith and jth items in the list. Without the temporary storage, one of the
values would be overwritten. In Python, it is possible to perform simultaneous assignment.
The statement a,b=b,a will result in two assignment statements being done at the same time
(see Figure 2). Using simultaneous assignment, the exchange operation can be done in one
statement.
bubbleSort(alist)