Professional Documents
Culture Documents
Integ Reviewer
Integ Reviewer
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
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
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
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
python interpreter
— 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
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
2. change directory to where you saved the file, for example, cd/tmp/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
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
numeric
>>> 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
>>> 2+3j
(2+3j)
>>> type (2+3j)
<class 'complex'>
— 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
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'>
mutable vs immutable
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
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
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
module 2 — fundamentals 4
assignment operators — assign values to variables
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
— 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
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
if
conditional expressions
module 2 — fundamentals 8
— used to check a condition
— if the condition is true, we run a block of statements (if-block)
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
while loop
i = 1
while i < 6:
print(i)
i += 1
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
a = "Hello"
print (a)
string as array
a = "Hello, World!"
print(a[1])
#output
e
string: slicing
#output
llo
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
a ="Hello, World!"
print(len(a))
#output
13
string: strip()
#output
Hello, World!
string: lower()
#output
hello, world!
string: upper()
#output
HELLO WORLD!
string: replace
#output
Jello, World
string: split()
#output
['Hello', 'World']
string methods
method description
find() searches the string for a specified value and returns the position of where it was found
index() searches the string for a specified value and returns the position of where it was found
isupper() returns true if all characters in the string are upper case
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
split() splits the string at the specified separator, and returns a list
startswith() returns true if the string starts with the specified value
swapcase() swaps cases, lower case becomes upper case and vice versa
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
#output
True
#output
False
string concatenation
a = "Hello"
b = "World"
c = a + b
print (c)
#output
HelloWorld
a = "Hello"
b = "World"
c = a + " " + b
print (c)
#output
Hello World
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
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
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
#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
— a physical file must be mapped to a built-in file object with the help of built-in function open()
— 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
r reading only
w writing only
a appending
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
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
— 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()
— 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()
— to read or write at a specific position, use the seek() function to set the current read/write position
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"
— 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
f= open("binfile.bin","wb")
num = [5, 10, 15, 20, 25]
arr = bytearray(num)
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
next(file) returns next line from the file each time it is called
file.readlines() reads until EOF and returns list containing the lines
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
#output
['apple', 'banana', 'cherry']
#output
banana
#output
cherry
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
#output
['cherry','orangee'.'kiwi']
the search will start at index 2 (included) and end at index 5 (not included)
#output
['apple','banana'.'cherry','orange']
thislist = ["apple","banana","cherry"]
thislist[1]=blackcurrant
print(thislist)
#output
['apple','blackcurrant','cherry']
list: loop
— you can loop through the list items by using a for loop
module 4 — collections 2
#output
apple
banana
cherry
#output
Yes,'apple' is in the fruit list
#output
3
#output
["apple", "banana", "cherry", "orange"]
#output
["apple", "orange", "banana", "cherry"]
module 4 — collections 3
print(thislist)
#output
['apple','cherry']
#output
['apple','banana']
the pop() method removes the specified index, or the last item if not specified
#output
['banana','cherry']
#output
[]
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
thislist =list(("appel","banana","cherry"))
print(thislist)
#output
['apple','banana','cherry']
list: methods
extend() add the elements of list (or any iterable), to the end of current 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
thistuple =("apple","banana","cherry")
print(thistuple[-1])
#output
cherry
#output
('orange','kiwi','melon')
x=("apple","banana","cherry")
y=list(x)
y[1]="kiwi"
x=tuple(y)
print(x)
#output
("apple","kiwi","cherry")
module 4 — collections 6
thistuple("apple","banana","cherry")
for x in thistuple:
print(x)
#output
apple
banana
cherry
thistuple("apple","banana","cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
tuples: length
— to determine how many items a tuple has, use the len() method
thistuple("apple","banana","cherry")
print(len(thistuple))
#output
3
— 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
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
index() searches the tuple for a specified value and returns the position where it was found
sets
thisset ={"apple","banana","cherry"}
print(thisset)
#output
{'cherry','banana','apple'}
create a set
— 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
thisset ={"apple","banana","cherry"}
print("banana" in thisset)
#output
True
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'}
thisset ={"apple","banana","cherry"}
thisset.update(["orange","mango","grapes"])
print(thisset)
#output
{'apple','cherry','orange','banana','grapes','mango'}
sets: length
thisset ={"apple","banana","cherry"}
print(len(thisset))
#output
3
thisset ={"apple","banana","cherry"}
thiset.remove("banana")
print(thisset)
#output
{'apple','cherry'}
thisset ={"apple","banana","cherry"}
thiset.discard("banana")
print(thisset)
#output
{'apple','cherry'}
— 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'}
— 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()
thisset ={"apple","banana","cherry"}
del thisset
print(thisset) #raise an error because it was deleted
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'}
set: constructor
#output
{'apple','cherry','banana'}
set: methods
difference update() removes the items in this set that are also included in another, specified set
intersection update() removes the items in this set that are not present in other, specified set
symmetric difference update() inserts the symmetric difference from this set and another
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}
module 4 — collections 11
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=thisdict["model"]
print(x)
#output
mustang
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
x=thisdict.get("model")
print(x)
#output
mustang
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict["year"]=2018
print(thisdict)
#output
{'brand':'ford','model':'mustang','year':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
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict.values():
print(x)
#output
ford
mustang
1964
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))
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict["color"] ="red"
print(thisdict)
#output
{'brand':'ford','model':'mustang','year':1964, 'color':'red'}
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'}
module 4 — collections 14
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
del thisdict
print (thisdict) #error because it was deleted already
thisdict ={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict.clear()
print(thisdict)
#output
{}
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}
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()
items() returns list containing a tuple for each 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
module 4 — collections 16
module 5 — functions
user defined and built-in functions
python functions
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.
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
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.
def my_function(food):
for x in food:
print(x)
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
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
--output--
the youngest child is Linus
— 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
def myfunction:
pass
function: lambda
— small anonymous function
— take any number of arguments, but can only have one expression
module 5 — functions 3
x = lambda a : a + 10
print (x(5))
--output--
15
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--
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
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
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
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
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
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'
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'>
class MyClass
x=5
p1 = MyClass()
print(p1.x)
--output--
5
— 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
— 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
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
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
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
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
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)
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
— 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
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
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
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"
--output--
raise typeerror
module 6 — OOP 10
module 7 — graphics and image
processing
graphics
python turtle
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
import turtle
wn = turtle.Screen()
tur = turtle.Turtle()
wn.mainloop()
import turtle
wn = turtle.Screen()
tur = turtle.Turtle()
tur.forward(100)
wn.mainloop()
#add
>>> myTur.color('green')
#add
>>> myTur.forward(100)
#add
clear your canvas and move both turtles back to the middle
running in file
fillcolor() color name changes the color of the turtle will use to fill a polygon
end_fill() none closes the polygon and fills with the current fill color
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
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
PNG
RGBA
(296, 314)
convert to grayscale
#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
rotate
image.crop(box=none)
the image, rotates it 45 degrees and display it using an external viewer
thumbnail
attributes
UI in python-tkinter
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
many of them have been ported to python in the form of importable modules
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
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
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
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)
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
components: label
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
show: to convert the text box into a password field, set show property to “*”
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
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()
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
an event should be registered with one or more GUI widgets in the application
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)
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
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
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