Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

module 1 — intro to python

history
— invented in netherlands 1991 by guido van rossum
— conceived in late 1980s and its implementation started december 1989

— guido van rossum is fan of “monty python’s flying circus”, famous tv show in netherlands

— named after monty python open sourced from the beginning


what is python programming
— easy to lead
— powerful programming language
— efficient high-level data structures and simple but effective approach to object-oriented programming
— elegant syntax and dynamic typing, together with its interpreted nature
— ideal language for scripting and rapid applications development in many areas on most platforms

difference between program and scripting language

program

— is executed (e. the source is first compiled, and the result of that compilation is expected)
— a “program” in general is, a sequence of instructions written so that a computer can perform
certain task

scripting

— is interpreted
— a “script” is code written in a scripting language, type of programming language in which we can
write code to control another software application

features of python
— simple and minimalistic

— easy to learn
— free and open source (FLOSS)

(free/libre and open source software) freely distribute copies of this software, red the software’s source
code, make changes to it, use pieces of it in new free programs

— high-level language

programs in python, doesn’t have to remember the system architecture or to manage the memory
— portable

can run on a wide variety of hardware platforms and the same interface on all platform
— interpreted

python is executed line by line at a time, just like c, c++, java there is no need to compile python code
this makes it easier to debug the code. source code of python is converted into an immediate form
called bytecode

module 1 — intro to python 1


— object-oriented

one of the key features of python is object-oriented programming; supports object oriented language
and concepts of classes, objects encapsulations
— embeddable

python code in a source code in a different language like c++; this allows to integrate scripting
capabilities into the program of the other language
— extensive libraries

python has a large standard library which provides rich set of module and functions; there are many
libraries present in python for such as regular expressions, unit-testing, web browsers

installation and getting started

modern algorithm

— analytics and artificial intelligence are becoming popular and in demand in today’s technology, in this
cases python provides several libraries that can process and analyze data on the fly, some prebuilt
libraries like numpy for scientific computation, spicy for advanced computing and pybrain for machine
learning that is connected to AI

interpreted language

— not compiled like java

— code is written and the directly executed by an interpreter


— type commands into interpreter and see immediate results

python interpreter

— allows you to type commands one-at-a-time and see results

— great way to explore python’s syntax


— repeat previous command: alt + P (windows)

module 1 — intro to python 2


idle

— integrated development and learning environment, integrated development environment provided with
python; an IDE combines a program editor and a language environment as a convenience to the
programmer

python shell

— interactive environment that allows you to type in some python code and execute it immediately; it is a
great way to get started with python
— >>> symbol is called a prompt; it means that python is waiting for you to give it some instructions

anatomy of a python program

import statement — used to import code from modules that are part of a standard python distribution

namespace — by default, every python module has its own private namespace, accessible by using
<modulename>.<name>; thus, different modules can use the same names without causing name
clashes

block structure — readability of python program is generally enhanced by the fact that code is
broken up into blocks by certain python constructions

interactive shell — with interactive interpreter, it is easy to check python commands; interpreter can
be invoked by typing the command “python” without any parameter followed by the “return” key at the
shell prompt

write and run python — there are 2 ways of using phyton to run your program - using the interactive
interpreter prompt or using source file

print() function prints the specified message to the screen, or other standard output device

print(object(s), separator=separator, end=end, file=file, flush=flush)

1. open a terminal window

2. change directory to where you saved the file, for example, cd/tmp/py

3. run the program by entering the command python hello.py

— using anaconda navigator — desktop graphical user interface (GUI) included in anaconda
distribution that allows users to launch applications and manage conda packages, environment and
channels without using command-line commands

— using visual studio code — an IDE from microsoft; used to develop computer programs, as well
as websites, web apps, web services, and mobile apps

module 1 — intro to python 3


module 2 — fundamentals
data types

comments — any text to the right of # symbol; useful as notes for the reader of the program
— use as many useful comments as you can in your program to explain

assumptions

important decisions

important details

problems you’re trying to solve

problems you’re trying to overcome

numeric

integer: positive or negative whole numbers (without a fractional part)

>>> print(10)
10
>>> type (10)
<class 'int'>

float: any real number with a floating point representation in which a fractional component is
denoted by a decimal symbol or scientific notation

>>> print (4,2)


4,2
>>> type (4,2)
<class 'float'>

complex number: specified as <real part>+<imaginary part>j

>>> 2+3j
(2+3j)
>>> type (2+3j)
<class 'complex'>

boolean — data with one of two built-in values true or false

>>> print (10>9)


True
>>> print (10==9)
False
>>> print (10<9)
False

string — sequence of character data; string type is called str

— string literals may be delimited using either single or double quotes; all the characters between the
opening delimiter and matching closing delimiter are part of the string

module 2 — fundamentals 1
>>> print ("I am string.")
I am string.
>>> type ("I am string.")
<class 'str'>

sequence type

string collection of one or more characters put in single or double quotes

list ordered collection of one or more data items, not necessarily of the same type, put in square
brackets

tuple ordered collection of one or more data items, not necessarily of the same type, put in
parentheses

dictionary — unordered collection of data in a key: value pair form; collection of such pairs is
enclosed in curly brackets (ex. {1:”Steve”, 2:”Bill”, 3:”Ram”, 4:”Farha”}

type() function — in-built function type() to ascertain the data type of a certain value; for ex, enter
type(1234) in python shell and it will return <class ‘int’> which means 1234 is an integer value

>>> type(1234)
<class 'int'>

>>> type (55.50)


<class'float'>

>>> type (6+4j)


<class'complex'>

>>> type ("hello")


<class'str'>

>>> type ([1,2,3,4])


<class'list'>

mutable vs immutable

mutable objects have field that can be changed

immutable objects have no fields that can be changed after the object is created

strings are immutable; once you have created a string, you cannot change it

objects of built-in type (int, float, bool, str, tuple, unicode) are immutable

objects of built-in type (list, set, dict) are mutable

custom classes are generally mutable

assignments
— evaluates the expressions list (remember that this can be a single expressions or comma-separated
list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to
right

module 2 — fundamentals 2
numeric types

— there are 3 distincts numeric types: integers, floating point numbers, and complex numbers
— in addition, booleans are a subtype of integers
— integers have unlimited precision

— floating point numbers are usually implemented using double in C

different operations that supports the numeric types (except complex)

module 2 — fundamentals 3
python operators and expression

— in python, operators are special symbols that designate that some sort of computation should be
performed; the values that an operator acts on are called operands; operators are used to perform
operations on variables and values

— the + operator adds the operands a and b together, an operand can be either a literal value or a
variable that references an object

— sequence of operands and operators, like a + b - 5, is called an expression. python supports many
operators for combining data objects into expression

arithmetic operators — numeric values to perform common mathematical operations

module 2 — fundamentals 4
assignment operators — assign values to variables

comparison operators — used to compare two values

module 2 — fundamentals 5
logical operators — used to combine conditional statements

identity operators — compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location

— python provides two operators, is and is not that determine whether the given operands have the same
identity — that is, refer to the same object. this is not the same thing as equality, which means the two
operands refer to objects that contain the same data but are not necessarily the same object

module 2 — fundamentals 6
membership operators — test if a sequence is presented in an object

bitwise operators — compare (binary) numbers

— used to perform bitwise calculations on integers; integers are first converted into binary and then
operations are performed on bit-by-bit; hence the name bitwise operators; then the result is returned in

module 2 — fundamentals 7
decimal format
— python bitwise operators work only on integer

a = 10
b = 4

print ("a & b = ", a & b)


print ("a|b = ", a | b)
print (~a =", ~a)
print ("a^b =", a^b)

error messages
— understanding what the different types of errors are and when you are likely to encounter them can
help a lot
— once you know why, they become more easier to fix

— syntax error; python couldn’t figure out how to read your program

python control statements

if

conditional expressions

— x = true_value if condition else false_value


— lazy evaluation:

first, condition is evaluated

if true, true_value is evaluated and returned

if false, false_value is evaluated and returned

💡 use of indentation for blocks

💡 Colon (:) after boolean expression

module 2 — fundamentals 8
— used to check a condition
— if the condition is true, we run a block of statements (if-block)

— else we process another block of statements (else block)


— the else clause is optional

for

— range() function returns a list of numbers from 0 up to but not including the number we pass to it;
defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a

module 2 — fundamentals 9
third parameter: range (2,30,3): (increment sequence with 3)
— range(5) returns [0,1,2,3,4]

for x in range(5):
print x

— xrange() returns an iterator that provides the same functionality more efficiently

— for..in statement is another looping statement which iterates over a sequence of objects i.e. go through
each item in a sequence

for i in range (1,5);


print (i)
else:
print ('The loop is over')

while loop

— execute a set of statements as long as a condition is true

i = 1
while i < 6:
print(i)
i += 1

continue and break statement

continue — stop the current iteration of the loop and continue with the next

fruits = ["apple","banana","cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

break — stop the loop before it has looped through all the items

fruits = ["apple","banana","cherry"]
for x in fruits:
print(x)
if x == "banana":
break

module 2 — fundamentals 10
module 3 — string and file handling
python strings

string literals are surrounded by either single quotation marks, or double quotation marks

#you can use double or single quotes


print ("Hello")
print ('Hello')

printing literal string

a = "Hello"
print (a)

assign string to variable and display

a = """lorem ipsum dolor sit amet,


consectetur adipiscing elit"""
print (a)

a = '''lorem ipsum dolor sit amet,


consectetur adipiscing elit'''
print (a)

declaring string in multiline

string as array

— strings in python are arrays of bytes representing unicode characters

— python does not have a character data type

— a single character is simply a string with a length of 1


— square brackets can be used to access elements of the string

a = "Hello, World!"
print(a[1])

#output
e

accessing each character using array

string: slicing

— slicing a string the return value is a range of characters

module 3 — string and file handling 1


b = "Hello, World!"
print (b[2:5])

#output
llo

get the characters from position 2 to position 5 (not included 5)

b = "Hello, World!"
print (b[-5:-2])

#output
orl

get characters from position 5 to position 2, starting the count from the end of the string

string: length

— get the length of a string, use the len() function

a ="Hello, World!"
print(len(a))

#output
13

the len() function returns the length of a string

string: strip()

— removes any whitespace from the beginning or end

a = " Hello, World! "


print (a.strip())

#output
Hello, World!

string: lower()

— return the string in lower case

a = " Hello, World! "


print (a.lower())

#output
hello, world!

string: upper()

— returns the string in upper case

module 3 — string and file handling 2


a = " Hello, World! "
print (a.upper())

#output
HELLO WORLD!

string: replace

— replace string with another string

a = " Hello, World! "


print (a.replace("H", "J"))

#output
Jello, World

string: split()

— splits string into substrings if it finds instances of separator

a = " Hello, World! "


b = a.split(,)
print b

#output
['Hello', 'World']

string methods

method description

capitalize() converts first character to upper case

casefold() converts string into lower case

center() returns a centered string

count() returns the number of times a specified value occurs in a string

encode() returns an encoded version of the string

endswith() returns true if the string ends with a specified value

expandtabs() sets the tab size of the string

find() searches the string for a specified value and returns the position of where it was found

format() formats specified values in a string

format_map() formats specified values in a string

index() searches the string for a specified value and returns the position of where it was found

isalnum() returns true if all characters in the string are alphanumeric

isalpha() returns true if all characters in the string are in alphabet

isdecimal() returns true if all characters in the string are decimal

isdigit() returns true if all characters in the string are digits

isidentifier() returns true if the string is an identifier

islower() returns true if all characters in the string are lowercase

module 3 — string and file handling 3


method description

isprintable() returns true if all characters in the string are printable

isnumeric() returns true if all characters in the string are numeric

isspace() returns true if all characters in the string are whitespaces

istitle() returns true if the string follows the rules of a title

isupper() returns true if all characters in the string are upper case

join() joins the elements of an iterable to the end of the string

ljust() returns a left justified version of the string

lower() converts a string into lowercase

lstrip() returns a left trim version of the string

maketrans() returns a translation table to be used in translations

partition() returns a tuple where the string is parted into three parts

replace() returns a string where a specified value is replaces with a specified value

searches the string for a specified value and returns the last positions where it was
rfind()
found
searches the string for a specified value and returns the last position where it was
rindex()
found
rlust() returns a right justified version of the string

rpartition() returns a tuple where the string is parted into three parts

rsplit() splits the string at a specified separator, and returns a list

rstrip() returns a right trim version of the string

split() splits the string at the specified separator, and returns a list

splitlines() split the string at line breaks and returns a list

startswith() returns true if the string starts with the specified value

strip() returns a trimmed version of the string

swapcase() swaps cases, lower case becomes upper case and vice versa

title() converts the first character of each word to upper case

translate() returns a translated string

upper() converts a string into upper case

zfill() fills the string with a specified number of 0 values at the beginning

check string

— to check if a certain phrase or character is present in a string, we can use the keywords in or not in

txt = "The rains in spain stays mainly in the plain"


x = "ain" in txt
print (x)

#output
True

check if the phrase “ain” is present in the following text

module 3 — string and file handling 4


txt = "The rains in spain stays mainly in the plain"
x = "ain" not in txt
print (x)

#output
False

check if the phrase “ain” is NOT present in the following text

string concatenation

— to concatenate, or combine, two strings you can use the + operatos

a = "Hello"
b = "World"
c = a + b
print (c)

#output
HelloWorld

merge variable a with variable b into variable c

a = "Hello"
b = "World"
c = a + " " + b
print (c)

#output
Hello World

to add a space between the, add a “ “

string format

— the format() method takes the passed arguments, formats them, and places them in the string where
the placeholders {} are:

age = 36
txt = "My name is John and I am {}"
print(txt.format(age))

#output
My name is John and I am 36

use the format() method to insert numbers into strings

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars"
print (myorder.format(quantity, itemno, price))

#output
I want 3 pieces of items 567 for 49.95 dollars

module 3 — string and file handling 5


the format() method takes unlimited number of arguments, and are placed into the respective
placeholders

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print (myorder.format(quantity, itemno, price))

#output
I want to pay 49.95 dollars for 3 pieces of item 567

you can use index numbers {0} to be sure the arguments are placed in the correct placeholders

escape character

— to insert characters that are illegal in a string, use an escape character

— an escape character is a backslash \ followed by the character you want to insert


— an example of an illegal character is a double quote inside a string that is surrounded by double quotes

txt = "We are the so-called "Vikings" from the north"


#You will get an error if you use double quotes inside
#a string that is surrounded by double quotes

to fix this problem, use the escape character\”

txt = "We are the so-called \"Vikings\" from the north"


print (txt)

#output
We are the so-called "Vikings" from the north.

code result

\’ single quote

\\ backslash

\n new line

\r carriage return

\t tab

\b backspace

\f form feed

\ooo octal value

\xhh hex value

python file handling file IO

file i/o operations

— a physical file must be mapped to a built-in file object with the help of built-in function open()

file object = open(filename[,access mode][,buffersize])

module 3 — string and file handling 6


— in the open() method the first parameter is the name of a file including its path

— the access mode parameter is an optional parameter which decides the purpose of opening a file e.g.
read, write, append, etc

— the optional buffersize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means
line buffered and other positive values indicate the buffer size

— a negative buffersize uses the default value. if a file cannot be opened, then OSError or its subtype is
raised

file I/O parameters

access modes description

r reading only

rb reading only in binary format

r+ both reading and writing

rb+ reading and writing in binary format

w writing only

wb writing only in binary format

w+ writing and reading

wb+ writing and reading in binary format

a appending

ab appending in binary format

a+ appending and reading

ab+ appending and reading in binary format

writing to a file

f= open ("D:\myfile.txt,"w")
f.write("Hello! Learn Python on TutorialsTeacher")
f.close()

— the f=open(”myfile.txt”,”w”) statement opens myfile.txt in write mode, the open() method returns the
file object and assigns it to a variable f.
— “w” specifies that the file should be writable

— we have to put certain data in the file


— the f.write(”Hello! Learn Python on TutorialsTeacher,” stores a string in the file
— in the end, f.close() closes the file object

lines = ["Hello world.\n", "Welcome to TutorialsTeacher.\n"]


f=open("D:\myfile.txt", "w")
f.writelines(lines)
f.close()

module 3 — string and file handling 7


— the writelines() method used to save the contents of a list object in a file; since the newline character is
not automatically written to the file, it must be provided as a part of the string

reading from a file

readline() reads the character starting from the current reading position up to a newline character

read(chars) reads the specified number of characters starting from the current position

readlines() reads all lines until the end of file and returns a list object

reading: file iterator

— the file object has an inbuilt iterator; the following program read the given file line by line until
StopIteration is raised, ie the end of the file is reached

f = open("myfile.txt, "r")
while True:
try:
line = next(f)
print (line)
except StopIteration
break
f.close()

f = open ("myfile.txt", "r")


for line in f:
print(line)
f.close()

read file using the for loop

append text to a file

— the “w” mode will always treat the file as a new file
— in other words, an existing file opened with “w” mode will lose its earlier contents
— in order to add more data to existing file use the “a” or “a+” mode

f = open("D:\myfile.txt", "a+")
f.write("Additional Content.")
line = f.readline()
f.close()

append or read a file

module 3 — string and file handling 8


— opening a file with “w” mode or “a” mode can only be written into and cannot be read from
— similarly “r” mode allows reading only and not writing
— in order to perform simultaneous read/append operations, use “a+” mode

— to read or write at a specific position, use the seek() function to set the current read/write position

f.seek (offset, from)


from parameter
0: offset calculated from the beginning
1: offset calculated from the current position
2: offset calculated from the end

assuming that myfile.txt contains “Hello World” text, the following example demonstrates the seek()
method

f=open ("D:\myfile.txt","r+")
f.seek(6,0)
lines = f.readlines()
for line in lines:
print(line)
f.close()

#output
"World"

reading and writing to a binary file

— the open() function opens a file in text format by default


— to open a file in binary format, add “b” to the mode parameter

— hence the “rb” mode opens the file in binary format for reading
— while the “wb” mode opens the file in binary format for writing
— unlike text mode files, binary files are not human readable

— when opened using any text editor, the data is unrecognizable

f= open("binfile.bin","wb")
num = [5, 10, 15, 20, 25]
arr = bytearray(num)

module 3 — string and file handling 9


f.write(arr)
f.close()

the code stores a list of numbers in a binary file; the list is first converted in a byte array before writing; the
built-in function bytearraye() returns a byte representation of the object

f=open("binfile.bin","rb")
num=list(f.read())
print(num)
f.close()

to read the binary file, the output of the read() method is casted to a list using the list() function

method description

file.close() closes file

file.flush() flushes internal buffer

next(file) returns next line from the file each time it is called

file.read([size]) reads specified number of bytes from the file

file.readline() reads one entire line from the file

file.readlines() reads until EOF and returns list containing the lines

file.seek(offset, from) sets the file’s current position

file.tell() returns the file’s current position

file.write(str) writes a string to the file; there is no return value

module 3 — string and file handling 10


module 4 — collections
python list and tuples

python collections (arrays)

list - ordered and changeable - allows duplicate members - square brackets [ ]

tuple - ordered and unchangeable - allows duplicate members - round bracket ( )

set - unordered and unindexed - no duplicate members - curly brackets { }

- unordered, changeable and indexed - no duplicate members - curly


dictionary
brackets { }

choosing a collection
— it is useful to understand the properties of that type
— choosing the right type for particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security

list

thislist = ["apple", "banana", "cherry"]


print(thislist)

#output
['apple', 'banana', 'cherry']

creating and printing a list

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

#output
banana

accessing the second item of the list

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

#output
cherry

printing the last item of the list

negative indexing means beginning from the end -1 refers to the last item, -2 refers to the second
last item

list: ranges
— range of indexes specify range of indexes by specifying where to start and where to end the range

module 4 — collections 1
— when specifying a range, the return value will be a new list with the specified items

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print (thislist[2:5])

#this will return the items from position 2 to 5


#remember that the first item is position 0 and that the item in possition 5 is NOT included

#output
['cherry','orangee'.'kiwi']

the search will start at index 2 (included) and end at index 5 (not included)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print (thislist[:4])

#this will return the items from index 0 to index 4


#remember that index 0 is the first item, and index 4 is the fifth
#remember that the item in index 4 is NOT included

#output
['apple','banana'.'cherry','orange']

returning the items from the beginning to “orange”

list: range of negative index


— specify negative indexes if you want to start the search from the end of the list

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print (thislist[-4:-1])

#negative indexing means starting from the end of the list


#-4 (included) to index -1 (excluded
#output
['orangee'.'kiwi','melon']

list: change item value


— to change the value of a specific item, refer to the index number

thislist = ["apple","banana","cherry"]
thislist[1]=blackcurrant
print(thislist)

#output
['apple','blackcurrant','cherry']

change the second item

list: loop
— you can loop through the list items by using a for loop

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print (x)

module 4 — collections 2
#output
apple
banana
cherry

print all items in the list, one by one

list: checking existing item


— to determine if a specified item is present in a list use the in keyword

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes,'apple' is in the fruit list")

#output
Yes,'apple' is in the fruit list

check if “apple” is present in the list

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

#output
3

print the number of items in the list

list: add items

— to add an item to the end of the list, use

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

#output
["apple", "banana", "cherry", "orange"]

using the append() method to append an item

to add an item at the specified index, use the insert() method

thislist = ["apple", "banana", "cherry"]


thislist.insert(1,"orange")
print(thislist)

#output
["apple", "orange", "banana", "cherry"]

insert an item as the second position

list: remove item

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")

module 4 — collections 3
print(thislist)

#output
['apple','cherry']

remove() method removes the specified item

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)

#output
['apple','banana']

the pop() method removes the specified index, or the last item if not specified

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

#output
['banana','cherry']

the del keyword removes the specified index

thislist = ["apple", "banana", "cherry"]


del thislist
print(thislist)

del keyword can also delete the list completely

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)

#output
[]

the clear() method empties the list:

list: copy

— you cannot copy a list simply by typing list2=list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2

— there are ways to make a copy, one way is to use the built-in list method copy()
— another way to make a copy is use the built-in method list()

list: join

list1=["a","b","c"]
list2=[1.2.3]

module 4 — collections 4
list3 = list1 +list2
print(list3)

#output
['a','b','c',1,2,3]

list1=["a","b","c"]
list2=[1.2.3]

for x in list 2:
list1.append(x)
print(list1)

#output
['a','b','c',1,2,3]

list1=["a","b","c"]
list2=[1.2.3]

list1.extend(list2)
print(list1)

#output
['a','b','c',1,2,3]

list: constructor

— it is also possible to use the list() constructor to make a new list

thislist =list(("appel","banana","cherry"))
print(thislist)

#output
['apple','banana','cherry']

list: methods

append() adds an element at the end

clear() removes all elements

copy() returns a copy of list

count() number of elements with the specified value

extend() add the elements of list (or any iterable), to the end of current list

index() returns the index of 1st element with specified value

pop() removes the element at the specified position

remove() removes the item with specified value

reverse() reverses the order of list

sort() sorts the list

tuples

module 4 — collections 5
thistuple =("apple","banana","cherry")
print(thistuple)

#output
('apple','banana','cherry')

creating a tuple

thistuple =("apple","banana","cherry")
print(thistuple[1])

#output
banana

print the second item in the tuple

thistuple =("apple","banana","cherry")
print(thistuple[-1])

#output
cherry

print the last item of tuple using negative indexing

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[-4:-1)

#-4 (included) to -1 (excluded)

#output
('orange','kiwi','melon')

tuples: change to values

— once a tuple is crated, you cannot change its values

— tuples are unchangeable, or immutable as it is also called


— you can convert tuple to list, change the list, and convert the list back into a tuple

x=("apple","banana","cherry")
y=list(x)
y[1]="kiwi"
x=tuple(y)
print(x)

#output
("apple","kiwi","cherry")

convert the tuple into a list to be able to change it

tuples: loop and check item exist


— you can loop through the tuple items by using a for loop

module 4 — collections 6
thistuple("apple","banana","cherry")
for x in thistuple:
print(x)

#output
apple
banana
cherry

iterate through the items nd print the values

thistuple("apple","banana","cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

check if “apple” is present in the tuple

tuples: length

— to determine how many items a tuple has, use the len() method

thistuple("apple","banana","cherry")
print(len(thistuple))

#output
3

print the number of items in the tuple

tuples: add items


— once tuple is created, you CANNOT add items to it; tuples are UNCHANGEABLE

tuples: remove item

— tuples are unchangeable, so you CANNOT remove items from it, but you can delete the tuple
completely

thistuple("apple","banana","cherry")
del thistupple
print(thistuple) #error, because it is already deleted

tuples: join

— join two or more tuples you can use the + operator

tuple1 = ("a","b","c")
tuple2 = (1,2,3)
tuple3 = tuple1 + tuple2
print(tuple3)

#output
('a','b','c',1,2,3)

module 4 — collections 7
tuples() constructor

thistuple =tuple(("apple","banana","cherry"))
print(thistuple)

#output
('apple','banana','cherry')

tuples:methods

count() returns the number of times specified value occurs in tuple

index() searches the tuple for a specified value and returns the position where it was found

sets

thisset ={"apple","banana","cherry"}
print(thisset)

#will appear unodered, random order

#output
{'cherry','banana','apple'}

create a set

sets: access items

— you cannot access items in a set by referring to an index, since sets are unordered the items HAS NO
INDEX
— but you can loop through the set items using a FOR LOOP, or ask if a specified value is present in a
set, by using the IN keyword

thisset ={"apple","banana","cherry"}
for x in thisset:
print(x)

#output
apple
cherry
banana

loop through the set, and print the values

thisset ={"apple","banana","cherry"}
print("banana" in thisset)

#output
True

check if “banana” is present in the set

sets: add items


— once set is created, you cannot change its items, but you can add new items

module 4 — collections 8
— to add one item to a set use the add() method
— to add more than one item to a set use the update() method

thisset ={"apple","banana","cherry"}
thisset.add("orange")
print(thisset)

#output
{'apple','banana','orange','cherry'}

add an item to a set, using the add() method

thisset ={"apple","banana","cherry"}
thisset.update(["orange","mango","grapes"])
print(thisset)

#output
{'apple','cherry','orange','banana','grapes','mango'}

add multiple items to a set, using the update() method

sets: length

thisset ={"apple","banana","cherry"}
print(len(thisset))

#output
3

get the number of items in a set

sets: remove item

thisset ={"apple","banana","cherry"}
thiset.remove("banana")
print(thisset)

#output
{'apple','cherry'}

remove “banana” by using the remove() method

thisset ={"apple","banana","cherry"}
thiset.discard("banana")
print(thisset)

#output
{'apple','cherry'}

remove “banana: using the discard() method

— if the item to remove does not exist, remove() or discard() will raise an error

— you can also use the pop(), method to remove an item, but this method remove the last item

module 4 — collections 9
— remember that sets are unordered, so you will not know what item that gets removed
— the return value of the pop() method is the removes item

thisset ={"apple","banana","cherry"}
x = thisset.pop()
print(x) #removed item
print(thisset) #the set after removal

#output
cherry
{'banana','apple'}

remove the last item by using the pop method

— sets are unordered, so when using the pop() method, you will not know which item that gets removed

thisset ={"apple","banana","cherry"}
thisset.clear()
print(thisset)

#output
set()

clear() method empties the set

thisset ={"apple","banana","cherry"}
del thisset
print(thisset) #raise an error because it was deleted

the del keyword will delete the set completely

set: join
— there are several ways to join two or more sets in python
— you can use the union() method that returns a new set containing all items from both sets, or the
update() method that inserts all the items from one set into another

set1 ={"a","b","c"}
set2 ={1,2,3}

set3=set1.union(set2)
print(set3)

#output
{'a','b',1,2,'c',3}

the union() method returns a new set with all items from both sets

set1 ={"a","b","c"}
set2 ={1,2,3}

set1.update(set2)
print(set1)

module 4 — collections 10
#output
{2,3,1,'b','c','a'}

the update() method inserts the items in set2 into set1

set: constructor

thisset =set(("apple", "banana","cherry"))


print(thisset)

#output
{'apple','cherry','banana'}

using the set() constructor to make a set

set: methods

add() adds element

clear() removes all element

copy() returns a copy

difference() returns set containing the difference between 2 or more sets

difference update() removes the items in this set that are also included in another, specified set

discard() remove the specified item

intersection() returns a set, that is the intersection of two other sets

intersection update() removes the items in this set that are not present in other, specified set

isdisjoint() returns whether two sets have intersection or not

issubset() returns whether another set contains this set or not

issuperset() returns whether this set contains another set or not

pop() removes an element from the set

remove() removes specified element

symmetric difference() returns a set with symmetric differences of 2 sets

symmetric difference update() inserts the symmetric difference from this set and another

union() return a set containing the union of sets

update() update the set with the union of this set and others

dictionaries

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(thisdict)

#output{'brand':'ford','mode':'mustang','year':1964}

creating and printing a dictionary

dictionaries: accessing items

module 4 — collections 11
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=thisdict["model"]
print(x)

#output
mustang

get the value of the “model” key using square brackets

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=thisdict.get("model")
print(x)

#output
mustang

get the value of the “model” key using get method

dictionaries: change values


— you can change the value of a specific item by referring to its key name

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}

thisdict["year"]=2018
print(thisdict)

#output
{'brand':'ford','model':'mustang','year':2018}

change the “year” to 2018

dictionaries: loop
— you can loop through a dictionary by using a for loop; when looping through a dictionary, the return
value are the keys of the dictionary, but there are methods to return the values as well

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict:
print(x)

#output
brand

module 4 — collections 12
model
year

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict:
print(thisdict[x])

#output
ford
mustang
1964

print all values in the dictionary one by one

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict.values():
print(x)

#output
ford
mustang
1964

use the values() function to return values of a dictionary

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x, y in thisdict.items():
print(x,y)

#output
brand ford
model mustang
year 1964

loop through both keys and values, by using the items() function

dictionaries: checking

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in this thisdict dictionary")

#output
Yes, 'model' is one of the keys in this thisdict dictionary

module 4 — collections 13
checking if “model” is present in the dictionary

dictionaries: length
— to determine how many items (key-value pairs) a dictionary has, use the len() method

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(len(thisdict))

print the number of items in the dictionary

dictionaries: adding items


— 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)

#output
{'brand':'ford','model':'mustang','year':1964, 'color':'red'}

dictionaries: removing items

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict.pop("model")
print(thisdict)

#output
{'brand':'ford','year':1964}

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict.popitem()
print(thisdict)

#output
{'brand':'ford','model':'mustang'}

dictionaries: deleting an item

module 4 — collections 14
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
del thisdict
print (thisdict) #error because it was deleted already

the del keyword can also delete the dictionary completely

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict.clear()
print(thisdict)

#output
{}

the clear() keyword empties the dictionary

dictionaries: copy

— you cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to
dict1, and changes made in dict1 will automatically also be made in dict2. there are ways to make copy,
one way is to use built-in dictionary method copy()

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
mydict= thisdict.copy()
print(mydict)

#output
{'brand':'ford','model':'mustang','year':1964}

thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
mydict =dict(thisdict)
print(mydict)

#output
{'brand':'ford','model':'mustang','year':1964}

make a copy of a dictionary with the dict() method

dictionary: dict()
— it is also possible to use the dict() constructor to make a new dictionary

module 4 — collections 15
thisdict = dict(brand="ford", model="mustang", year= 1964
#keywords are not string literals
#use of equals rather than color for assignment
print(thisdict)

#output
{'brand':'ford','model':'mustang','year':1964}

dictionary: methods()

clear() removes all elements

copy() returns copy of the dictionary

fromkeys() returns a dictionary with the specified keys and values

get() returns the value of the specified key

items() returns list containing a tuple for each key value pair

keys() returns a list containing the dictionary’s keys

pop() removes the element with a specified key

popitem() removes the last inserted key value pair

returns the value of the specified key; if the key does not exist: insert the key, with the
setdefault()
specified value
update() updates the dictionaries with the specified key value pairs

values() returns a list of all the values in the dictionary

module 4 — collections 16
module 5 — functions
user defined and built-in functions

python functions

— a function is a block of code which only runs when it is called


— you can pass data, known as parameters, into a function
— can return data as a result
— defined using the def keyword

def my_function():
print("Hello from a function")

calling a function
— to call a function, use the function name followed by parenthes

def my_function():
print("Hello from a function")
my_function()

--output--
Hello from a function

functions: parameters
— information can be passed to functions as parameter
— parameters are specified after the function name, inside the parenthesis

— you can add as many parameters as you want, just separate them with a comma

def my_function(fname):
print(fname + "Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

--output--
Emil Refsnes
Tobias Refsnes
Linus Refsnes

module 5 — functions 1
functions: default parameters

— given example shows how to use a default parameter value; if we call the function without parameter, it
uses the default value
— fefault parameter values can be specified using the equals sign (=) followed by the default value.

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

--output--
I am from Sweden
I am from India
I am from Norway
I am from Brazil

function: list as parameter


— you can send any data types of parameter to a function (string, number, list, dictionary etc), and it will
be treated as the same data type inside the function

in the case of a list as a parameter, you can pass a list as an argument to a function. The function can
then modify the list as needed. The modifications will be visible outside the function as well, since lists are
mutable objects.

here is an example of using a list as a parameter in a function:

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

--output--
apple
banana
cherry

the function takes a list as a parameter and prints each item in the list. In this example, the list is ["apple",

"banana", "cherry"] , but you can pass in any list you like.

sending a list as a parameter, it will still be a list when it reaches the function

function: returning a value


— to let a function return a value, use the return statement

def my_function(x):
return 5*x
print(my_function(3))
print(my_function(5))
print(my_function(9))

--output--

module 5 — functions 2
15
25
45

function: keyword arguments


— you can also send arguments with the key= value syntax; this way the order of the arguments does not
matter

def my_function(child3, child2, child1):


print("The youngest chid is"+child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 ="Linus"

--output--
the youngest child is Linus

function: arbitrary arguments


— if you do not know how many arguments that will be passed into your function, add a * before the
parameter name in the function definition

— this way the function will receive a tuple of arguments and can access the items accordingly

def my_function(*kids):
print("The youngest child is" + kids[2])
my_function("Emil", "Tobias","Linus")

--output--
the youngest child is Linus

— arbitrary arguments are shortened to *args in python documentations

function: pass statements


— function definitions cannot be empty, but if you for some reason have a function definition with no
content, put in the pass statement to avoid getting an error

def myfunction:
pass

program structure and design

function: lambda
— small anonymous function
— take any number of arguments, but can only have one expression

lambda arguments : expression


the expression is executed and the result is returned:
example 1
— a lambda function that adds 10 to the number passed in as an argument, and print the result

module 5 — functions 3
x = lambda a : a + 10
print (x(5))

--output--
15

lambda functions can take any number of arguments

example 2

— a lambda function that multiplies argument a with argument b and print the result

x = lambda a, b : a*b
print (x(5,6))

--output--
30

example 3
— a lambda function that sums argument a, b, and c, and print the result

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

--output--
13

function: recursion
— python also accepts function recursion, which means a defined function can call itself

— recursion is a common mathematical and programming concept. it means that a function calls itself,
this has the benefit of meaning that you can loop through data to reach a result

— the developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. however, when
written correctly recursion can be very efficient and mathematically elegant approach to programming

in this example, tri_recursion() is a function that we have defined to call itself (”recurse”); we use the k
variable as the data, which decrements (-1) every time we recurse; the recursion ends when the condition
is not greater than 0 (i.e. when it is 0)

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results"_
tri_recursion(6)

--output--

Recursion Example Results


1

module 5 — functions 4
3
6
10
15
21

module 5 — functions 5
module 6 — OOP
classes and objects
— python is an object oriented programming language
— almost everything in python is an object, with its properties and methods

— a class is like an object constructor, or a “blueprint” for creating objects

defining a class
— a class in python can be defined using the class keyword; a class typically includes the following
members

constructor

instance attributes

class attributes

methods

access modifiers
— public members (generally methods declared in a class) are accessible from outside the class

the object of the same class is required to invoked a public method

this arrangement of private instance variables and public methods ensures the principle of data
encapsulation

— protected members of a class are accessible from within the class and are also available to its sub-
classes

no other environment is permitted to access to it

this enables specific resources of the parent class to be inherited by the child class

— python doesn’t have any mechanism that effectively restricts access to any instance variable or
method

python prescribes a convention of prefixing the name of the variable/method with single or double
underscore to emulate the behavior of protected and private access specifiers

— all members in python class are public by default

any member can be accessed from outside the class environment

public attributes

class employee:
def __init__(self,name,sal):
self.name=name
self.salary=sal

>>> e1=Employee("Kiran",10000)
>>> e1.salary

module 6 — OOP 1
10000
>>> e1.salary=20000
>>> e1.salary
20000

you can access employee class’s attributes and also modify their values

protected

— python’s convention to make an instance variable protected is to add a prefix (single underscore) to it
— this effectively prevents it to be accessed, unless it is from within a sub-class

class employee:
def __init__(self,name,sal):
self.name=name
self.salary=sal
e1 = employee ("Swati", 1000)
print(e1._name) #protected attribute
print(e1._salary) #protected attribute

e1.salary = 2000
#change the value of salary
print(e1.salary)

--output--
Swati
1000
2000

— in fact, this doesn’t prevent instance variables from accessing or modifying the instance; you can still
perform the given operations

— hence, the responsible programmer would refrain from accessing and modifying instance variables
prefixed with _ from outside its class
— python’s convention to make an instance variable protected is to add a prefix _ (single underscore) to
it
— this effectively prevents it to be accessed, unless it is from within a sub-class

private
— a double underscore __ prefixed to a variable makes it private

— it gives a strong suggestion not to touch it from outside the class


— any attempt to do so will result in an AttributeError:

class employee:
def __init__(self,name,sal):
self.__name=name #private attribute
self.__salary=sal #private attribute

>>> e1=employee("Bill",10000)
>>> el.__salary
AttributeError: 'employee' object has no attribute '__salary'

— python performs name mangling of private variables

module 6 — OOP 2
— every member with double underscore will be changed to _object._class__variable

— if so required, it can still be accessed from outside the class, but the practice should be refrained

>>> e1=employee("Bill",10000)
>>> e1._Employee__salary
10000
>>> e1._Employee__salary=20000
20000

class MyClass
x=5
print(MyClass)

--output--
<class '__main__.MyClass'>

create a class named MyClass, with a property named x:

class MyClass
x=5
p1 = MyClass()
print(p1.x)

--output--
5

using the class named myClass to create objects

the __init()__ function

— all classes have a function called __init__(), which is always executed when the class is being initiated
— used to assign values to object properties, or other operations that are necessary to do when the
object is being created

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
p1 = Person ("John", 36)

print(p1.name)
print(p1.age)

--output--
John
36

— create a class named person, use the __init__() function to assign values for name and age

object methods

— objects can also contain methods; methods in objects are functions that belong to the object

class Person:
def __init__(self,name,age):

module 6 — OOP 3
self.name=name
self.age=age
def myfunc(self:
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()

--output--
Hello my name is John

— insert a function that prints a greeting, and execute it on the p1 object

— note: the self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class

parameter self

— the self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class
— it does not have to be named self, you can call it whatever you like, but it has to be the first parameter
of any function in the class

class Person
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " +abc.name)
p1 = Person ("John", 36)
p1.myfunc()

--output--
Hello my name is John

— use the words mysillyobject and abc instead of self

properties (attributes)
— instance attributes are attributes or properties attached to an instance of a class; instance attributes
are defined in the constructor

class person:
def __init__(self) #constructor
self.name="Unknown" #instance attribute
self.age=0 #instance attribute

>>> p1= person()


>>> p1.name="Bill"
>>> p1.age= 25
>>> p1.name
Bill
>>> p1.age
25

you can set the value of attributes using the dot notation

module 6 — OOP 4
>>> p1.person()
>>> p1.name
unknown
>>> p1.age
0

an instance attribute can be accessed using dot notation: [instance name].[attribute name]

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print (p1.age)

--output--
40

modifying properties on objects: set the age of p1 to 40

properties

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1.age
print (p1.page)

--output--
attribute error

delete the age property from the p1 object: you delete properties on objects by using the del keyword

delete objects

class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1
print(p1)

--output--
name error

deleting objects by using the del keyword: delete the p1 object

module 6 — OOP 5
pass statement

— class definitions cannot be empty, but if you for some reason have a class definition with no content,
put in the pass statement to avoid getting an error

class Person:
pass
#having an empty class definition like this, would raise an error without the pass statement

persistent storage of object

inheritance

— comes into picture when a new class possesses the ‘IS A’ relationship with an existing class
— dog IS an animal; cat also IS an animal; hence, animal is the base class, while dog and cat are
inherited classes
— a quadrilateral has four sides; a rectangle IS a quadrilateral, and so IS a square; quadrilateral is a base
class (also called parent class), while rectangle and square are the inherited classes - also called child
classes

— the child class inherits data definitions and methods from the parent class; this facilitates the reuse of
features already available; the child class can add a few more definitions or redefine a base class method

syntax

class parent:
statements
class child (parent):
statements

the name of the parent class is put in the parentheses in front of it, indicating the relation between the two;
instance attributes and methods defined in the parent class will be inherited by the object of the child
class

class quadriLateral:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d

def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print("perimeter=",p)

a quadrilateral class having four sides as instance variables and a parameter() method is defined

— constructor (the init() method) receives four parameters and assigns them to four instance variables; to
test the above class, declare its object and invoke the perimeter() method

>>>q1=quadriLateral(7,5,6,4)
>>>q1.perimeter()

module 6 — OOP 6
perimeter=22

we now design a rectangle class based upon the quadrilateral class (rectangle IS a quadrilateral!). the
instance variables and the perimeter() method from the base class should be automatically available to it
without redefining it

since opposite sides of the rectangle are the same, we need only two adjacent sides to construct its
object. hence, the other two parameters of the init() method are set to none. the init() method forwards
the parameters to the constructor of its base (quadrilateral) class using the super() function. the object is
initialized with side3 and side4 set to none. opposite sides are made equal by the constructor of rectangle
class. remember that it has automatically inherited the perimeter() method, hence there is no need to
redefine it.

class rectangle(quadriLateral):
def __init__(self, a, b):
super().__init__(a, b, a, b)

>>> r1=rectangle(10, 20)


>>> r1.perimeter()
perimeter=60

declare the object of the rectangle class and call the perimeter() method

overriding
— methods of the parent class are available for use in the inherited class. however, if needed, you can
modify the functionality of any base class method.
— for that purpose, the inherited class contains a new definition of a method (with the same name and the
signature already present in the base class).
— naturally, the object of a new class will have access to both methods, but the one from its own class
will have precedence when invoked. this is called method overriding.

class rectangle(QuadriLateral):
def __init__(self, a,b):
super().__init__(a, b, a, b)

def area(self):
a = self.side1 * self.side2
print("area of rectangle=", a)

define a new method named area() in the rectangle class and use it as a base for the square class; the
area of rectangle is the product of its adjacent sides

class square(rectangle):
def __init__(self, a):
super().__init__(a, a)
def area(self):

module 6 — OOP 7
a=pow(self.side1, 2)
print('Area of Square: ', a)

define the square class which inherits the rectangle class. the area() method is overridden to implement
the formula for the area of the square as the square of its sides.

>>>s=Square(10)
>>>s.area()
Area of Square: 100

python try except


— the try block lets you test a block of code for errors
— the except block lets you handle the error

— the finally block lets you execute code, regardless of the result of the try- and except blocks

exception handling
— when an error occurs, or exception as we call it, python will normally stop and generate an error
message
— these exceptions can be handled using the try statement

try:
print(x)
except:
print("An exception occurred")

--output--
an exception occured

the try block will generate an exception, because x is not defined

many exceptions
— you can define as many exception blocks as you want, e.g. if you want to execute a special block of
code for a special kind of error

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

--output--
Variable x is not defined

print one message if the try block raises a NameError and another for other errors

else
— you can use the else keyword to define a block of code to be executed if no errors were raised

module 6 — OOP 8
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

--output--
Hello
Nothing went wrong

the try block does not generate any error

finally

— the finally block, if specified, will be executed regardless if the try block raises an error or not

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

--output--
the 'try except'' is finished

this can be useful to close objects and clean up resources

— try to open and write to a file that is not writable

try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")

the program can continue, without leaving the file object open

raise an exception
— choose to throw an exception if a condition occurs
— to throw (or raise) an exception, use the raise keyword

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

--output--
raise exception

module 6 — OOP 9
raise an error and stop the program if x is lower than 0
the raise keyword is used to raise an exception

you can define what kind of error to raise, and the text to print to the user

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

--output--
raise typeerror

module 6 — OOP 10
module 7 — graphics and image
processing
graphics

python turtle

popular way for introducing programming to kids

part of the original logo programming language developed by wally feurzeig, seymour papert and
cynthia solomon in 1967

the turtle module is an extended reimplementation of the same-named module form the python
standard distribution up to version python 2.5

turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways

it uses tkinter for the underlying graphics, it needs a version of python installed with tk support

“turtle” is a python feature like a drawing board, which lets you command a turtle to draw all over it

you can use functions like . . . which can move the turtle around

turtle.forward(...)
turtle.left(...)
import turtle

a window will pop up called python turtle graphics


containing tur the turtle

import turtle
wn = turtle.Screen()
tur = turtle.Turtle()
wn.mainloop()

forward takes pixels as its input - this will move tur


forward 100 units

import turtle
wn = turtle.Screen()
tur = turtle.Turtle()
tur.forward(100)
wn.mainloop()

module 7 — graphics and image processing 1


the left and right methods take degrees as their input
- this will turn tur left 45 degrees

>>> from turtle import Turtle


>>> tur = Turtle ()
>>> tur.forward (100)
>>> tur.left(45

>>> from turtle import Turtle


>>> myTur = Turtle()
>>> myTur.shape ('turtle')

#add
>>> myTur.color('green')

#add
>>> myTur.forward(100)

>>> from turtle import Turtle


>>> myTur = Turtle()
>>> myTur.shape('turtle')
>>> myTur.color('green')
>>> myTur.forward(100)
>>> yourTur = Turtle()
>>> yourTur.shape('circle')
>>> yourTur.color('red')
>>> yourTur.right(30)
>>> yourTur.backward(100)

#add

module 7 — graphics and image processing 2


>>> myTur.reset()

clear your canvas and move both turtles back to the middle

from turtle import Turtle, exitonclick


tur = Turtle()
tur.shape("turtle")
tur.forward(100)
exitonclick()

running in file

method parameter description

Turtle() none creates and returns a new turtle object

forward() amount moves the turtle forward by the specified amount

backward () amount moves the turtle backward by the specified amount

right() angle turns the turtle clockwise

left() angle turns the turtle counter clockwise

penup() none picks up the turtle’s pen

pendown() none puts down the turtle’s pen

up() none picks up the turtle’s pen

down() none puts down the turtle’s pen

color() color name changes the color of the turtle’s pen

fillcolor() color name changes the color of the turtle will use to fill a polygon

heading() none returns the current heading

position() none returns the current position

goto() x,y moves the turtle to position x,y

begin_fill() none remember the starting point for a filled polygon

end_fill() none closes the polygon and fills with the current fill color

dot() none leaves the dot at the current position

stamp() none leaves an impression of a turtle shape at the current location

shape() shapename should be ‘arrow’, ‘classic’, ‘turtle' or ‘circle’

images

one of the most popular and considered as default library of python for image processing is pillow

pillow is an updated version of the python image library or PIL and supports a range of simple and
advanced image manipulation functionality

it is also the basis for simple image support in other python libraries such as sciPy and Matplotlib

image is loaded directly using the open() function on image class

module 7 — graphics and image processing 3


this returns an image object that contains the pixel data for the image as well as details about the
image

the format property on the image will report the image format (e.g. png, jpeg), the mode will report the
pixel channel format (e.g. CMYK or RGB) and the size will report the dimensions of the image in
pixels (e.g. 400*260)

the show() function will display the image using operating systems default application

#load and show an image with pillow


from PIL import image

#load the image


img = image.open ('apple.png')

#get the basic details about the image


print(img.format)
print(img.mode)
print(img.size)

#show the image


img.show()

PNG
RGBA
(296, 314)

convert to grayscale

#import required library


from PIL import image

#read an image & convert it to gray-scale


image = image.open('apple.png').convert('L')

#display image
image.show()

#save image
image.save('apple_gs.png')

after running the program, a file “apple_gs.jpg” is created in the current working directory

convert to another image

current files additional orange.png was


a new image file is created and save in
added
the default directory

module 7 — graphics and image processing 4


resize image

new size (dimensions) of the image file is now 300X250px


the size (dimensions) of
the current image file is incase you want to crop the existing image, you can do it using
496*362px image.crop(box=none)

rotate

image.crop(box=none)
the image, rotates it 45 degrees and display it using an external viewer

thumbnail

module 7 — graphics and image processing 5


the program will create 128*128 thumbnails of all jpeg images in your current working directory from PIL
import image

attributes

instances of the image class have the following attributes

the file format of the source file, for images


format im.format string or none created by the library, this attribute is set to
non
specifying the pixel format used by the
mode im.mode string image, typical values are “1”, “L”, “RGB”, or
“CMYK”
image size, in pixels. the size is given as a
size im.size width, height
2-tuple (width, height)
color palette table, if any. if mode is “P”,
this should be an instance of the
palette im.palette palette or none
imagepalette class. otherwise it should be
set to none
a dictionary holding data associated with
info im.info dictionary
the image
convert im.convert (mode) image returns a converted copy of an image

copies the image. use this method if you


copy im.copy() image wish to paste things into an image, but still
retain the original
returns a rectangular region from the
current image. the box is a 4-tuple defining
the left, upper, right, and lower pixel
coordinate this is a lazy operation. changes
crop im.crop(box) image
to the source image may or may not be
reflected in the cropped image. to get a
separate copy, call the load method on the
cropped copy
returns a copy of an image by the given
filter im.filter(filter) image
filter
paste im.paste(image, box) paste another image into this image

returns a copy of the image where each


point im.point(table) im.point(function) image image pixel has been mapped through the given
table
transform im.transform (size, method, data) image image creates a new image with the given size,
im.transform (size, method, data, and the same mode as the original, and

module 7 — graphics and image processing 6


filter) copies data to the new image using the
given transform

module 7 — graphics and image processing 7


module 8 — graphical user interface
event-driven programming paradigm

UI in python-tkinter

modern computer applications are user-friendly

user interaction is not restricted to console-based I/O

they have a more ergonomic graphical user interface (GUI) thanks to high speed processors and
powerful graphics hardware

these applications can receive inputs through mouse clicks and can enable the user to choose from
alternatives with the help of radio buttons, dropdown lists, and other GUI elements (or widgets)

such applications are developed using one of various graphics libraries available

a graphic library is a software toolkit having a collection of classes that define a functionality of
various GUI elements

these graphics libraries are generally written in C/C++

many of them have been ported to python in the form of importable modules

GUI elements graphics libraries

tkinter is the python port for tcl-tk GUI toolkit developed by fredrik lundh

this module is bundled with standard distributions of python for all platforms

PyQtis the python interface to qt, is a very popular cross-platform GUI framework

PyGTK is the module that ports python to another popular GUI widget toolkit called GTK

WxPython python wrapper around WxWidgets, another cross-platform graphics library

tkinter.scrolledtext text widget with a vertical scroll bar built in

tkinter.colorchooser dialog to let the user choose a color

tkinter.commondialog base class for the dialogs defined in the other modules listed here

tkinter.filedialog common dialogs to allow the user to specify a file to open or save

tkinter.font utilities to help work with fonts

tkinter.messagebox access to standard tk dialog boxes

tkinter.simpledialog basic dialogs and convenience functions

tkinter.dnd drag-and-drop support for tkinter

tkinter.ttk provides access to the tk themed widget set

python’s tkinter module contains tk class

its object forms a top level window

other widgets such as label, button, entry etc. can be placed


on this top level window

module 8 — graphical user interface 1


import tkinter
top = tkinter.tk()
top.mainloop()

the top level window represented by this application object is having a frame with title bar, control box
with maximize, minimize, and close buttons, and inner client are to hold other widgets

the application object then enters an event listening loop by calling its mainloop() method

GUI elements and their functionality are defined in the tkinter module; the following code
demonstrates the steps in creating a UI

from tkinter import *


window = tk()

#add widgets here


window.title('Hello Python')
window.geometry("300x200+10+20")
window.mainloop()

all tkinter widget classes are inherited from the


widget class

first import the tkinter module then setup the application object by calling the tk() function

this will create a top-level window (root) having a frame with a title bar, control box with the
minimize and close buttons, and a client area to hold other widgets

the geometry() method defines the width, height and coordinates of the top left corner of the frame as
below (all values are in pixels)

: window.geometry(”widthxheight+XPOS+YPOS”) the application object then enters an event


listening loop by calling the mainloop() method

the application is now constantly waiting for any event generated on the elements in it

the event could be text entered in a text field, a selection made from the dropdown or radio
button, single/double click actions of mouse, etc

the application’s functionality involves executing appropriate callback functions in response to a


particular type of event

we shall discuss event handling later in this tutorial

module 8 — graphical user interface 2


the event loop will terminated as and when the close button on the title bar is clicked

the above code will create the following window

components: label

a label can be created in the UI python using the


label class

the label constructor requires the top-level


window object and options parameters

option parameters are similar to the button object

from tkinter import *


window = Tk()
lbl = Label (window, text="This is a Label widget", fg ='red', font=("Helvetica", 16))
lbl.place (x=60,y=50)
window.title('Hello Python')
window.geomertry("300x200+10+10")
window.mainloop()

components: entry

this widget renders a single-line text box for accepting the user input

for multi-line text input use the text widget. apart from the properties already mentioned, the entry
class constructor accepts the following

bd: border size of the text box; default is 2 pixels

show: to convert the text box into a password field, set show property to “*”

the given code adds the text field

txtfld =Entry(window ,text="This is Entry Widget",bg ='black',fg= 'white',bd =5)

from tkinter import *


window=Tk()
btn=Button(window, text="this is button widget", fg='blue')
btn.place(x=80, y=100)
lbl=label(window, text="this is label widget", fg='red', font=("Helvetica",16))
lbl.place(x=60, y=50)
txtfld=Entry(window, text="this is entry widget", bd=5)
txtfld.place(x=80, y=150)
window.title('hello python')
window.geometry("300x200+10+10")
window.mainloop()

components: selection widgets

this widget displays a toggle button having an on/off state. there may be
radiobutton
more than one button, but only one of them will be ON at a given time

module 8 — graphical user interface 3


checkbutton this is also a toggle button. a rectangular check box appears before its
caption. its ON state is displayed by the tick mark in the box which
disappears when it is clicked to OFF
this class is defined in the ttk module of tkinterpackage. it populates drop
combobox down data from a collection data type, such as a tuple or a list as values
parameter
unlike combobox, this widget displays the entire collection of string
listbox
items. the user can select one or multiple items

from tkinter import *


from tkinte.ttk import combobox
window =Tk()
var = StringVar()
var.set("one")
data=("one","two","three", "four")
cb=Combobox(window, values=data)
cb.place(x=60, y=150)

lb=Listbox(window, height=5, selectmode='multiple')


for num in data:
lb.insert(END,num)
lb.place(x=250, y=150)
v0=IntVar()
v0.set(1)
r1=Radiobutton(window, text="male", variable=v0, value=1)
r2=Radiobutton(window, text="female", variable=v0, value=2)
r1.place(x=100, y=50)
r2.place(x=180, y=50)

v1 =IntVar()
v2 =IntVar()
C1 = Checkbutton(window, text="Cricket", variable =v1)
C2 = Checkbutton(window, text="Tennis", variable =v2)
C1.place(x=100, y=100)
C2.place(x=180, y=100)

window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

gui event handling

an event is a notification received by the application object from various GUI widgets as a result of
user interaction

the application object is always anticipating events as it runs an event listening loop

module 8 — graphical user interface 4


user’s actions include mouse button click or double click, keyboard key pressed while control is
inside the text box, certain element grains or goes out of focus

events are expressed as strings in <modifier-type-qualifier> format

many events are represented just as qualifier

the type defines the class of the event

event modifier type qualifier action

button 1 button 1 left mouse button click

button 2 button 2 middle mouse button click

destroy destroy window is being destroyed

double button 1 double button 1 double-click first mouse button 1

enter enter cursor enters window

expose expose window fully or partially exposed

keypress a keypress a any key has been pressed

keyrelease keyrelease any key has been released

leave leave cursor leaves window

print print print key has been pressed

focusIN focusIN widget gains focus

focusOUT focusOUT widget loses focus

an event should be registered with one or more GUI widgets in the application

if it’s not, it will be ignored

in tkinter, there are two ways to register an event with a widget

first way is by using the bind() method and the second way is by using the command parameter in
the widget constructor

event: bind()

the bind() method associates an event to a callback function so that, when the even occurs, the
function is called

widget.bind(event, callback)

from tkinter import *


def MyButtonClicked(event):
print("Button Clicked")
window=Tk()
btn = Button(window, text='OK')
btn.place(x=80, y=100)
btn.bind('<Button-1>',MyButtonClicked)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

module 8 — graphical user interface 5


event: command parameter

each widget primarily responds to a particular type

for example, button is a source of the button event

so, it is by default bound to it

constructor methods of many widget classes have an optional parameter called command

this command parameters is set to callback the function which will be invoked whenever its bound
event occurs

this method is more convenient than the bind() method

btn = Button(window, text='OK', command=myEventHandlerFunction)

from tkinter import *


def MyButtonClicked();
print("Button Clicked")
window=Tk()
btn = Button(window, text='OK', command=MyButtonClicked)
btn.pack()
window.title('Hello Python')
window.mainloop()

from tkinter import *


class MyWindow:
def __init__(self,win):
self.lbl1=Label(win, text='First number')
self.lbl2=Label(win, text='Second number')
self.lbl3=Label(win, text='Result')
self.t1=Entry(bd=3)
self.t2=Entry()
self.t3=Entry()
self.btn1 = Button(win, text='Add')
self.btn2 = Button(win, text='Subtract')
self.lbl1.place(x=100,y=50)
self.t1.place(x=200,y=50)
self.lbl2.place(x=100,y=100)
self.t2.place(x=200,y=100)
self.btn1 = Button(win, text='Add', command=self.add)
self.btn2 = Button(win, text='Subtract')
self.b2.bind('<Button-1>',self.sub)
self.b1.place(x=100, y=150)
self.b2.place(x=200, y=150)
self.lbl3.place(x=100,y=200)

module 8 — graphical user interface 6


self.t3.place(x=200,y=200)
def add(self):
self.t3.delete(0,'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1+num2
self.t3.insert(END,str(result))
def sub(self):
self.t3.delete(0,'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1-num2
self.t3.insert(END,str(result))

window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()

from the example the application window has two text input fields and another one to display the
result

there are two button objects with the captions add and subtract

the user is expected to enter the number in the two entry widgets

their addition or subtraction is displayed in the third

the first button (add) is configured using the command parameter

its value is the add() method in the class

the second button uses the bind() method to register the left button click with the sub() method

both methods read the contents of the text fields by the get() method of the entry widget, parse to
numbers, perform the addition/subtraction and display the result in third text field using the insert()
method

module 8 — graphical user interface 7

You might also like