0% found this document useful (0 votes)
49 views

MyPython POO 2021V7

Uploaded by

abir saal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

MyPython POO 2021V7

Uploaded by

abir saal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Page 2

Object Oriented Programing

Abdelkader BELAHCENE
[email protected]

December 13, 2021

AnalyseNum A.Belahcene December 13, 2021


Contents

1 Introduction and Reminders 5


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Using asciinema . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Basic Python 11
2.1 History Command . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Basic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Some Methods on String . . . . . . . . . . . . . . . . . . . . . . 16
2.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5 Other Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.7 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.8 Regular Exception . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.9 Turtle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

3 OOP : the Concepts 43


3.1 Imperative Programming . . . . . . . . . . . . . . . . . . . . . 43
3.2 Response to Theses Problems . . . . . . . . . . . . . . . . . . . 43
3.3 Basic Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4 POO in Python 50
4.1 Everything is Object . . . . . . . . . . . . . . . . . . . . . . . . 50

3
Contents Page 4

4.2 Data Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . 56


4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.4 Packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.5 Special Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

5 GUI: Tkinter 66
5.1 Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.2 Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

AnalyseNum A.Belahcene December 13, 2021


Chapter 1

Introduction and Reminders


Here, I assume that the basics of the Python language are acquired.
The purpose of this document is to understand «Object Oriented Program-
ming» in Python, however, since, probably this language is new for you, I
give you a summary of the essential things in this chapter.
For further help, see my document myPython_Base_2021.pdf.

1.1 Introduction
You can get Documents and Programs example from the FTP local (if you are
in ENST) at the Server at address : 172.16.200.10. Use gftp program, and
login as anonymous (ftp protocole).
Maybe you ll see programs or documents, but you can’t download it, un-
til the permission is given. I do this to give the opportunity to write you
program.
Then, later, if you do not succeed in writing or want to verify your pro-
gram, you’ll find an example of solution, at your disposal, I’ll add read-
ing permission to the file at the appropriate time.

1.1.1 Working Environment

To check and execute your programs, it is recommended to have a Linux dis-


tribution installed. See the site: distrowatch.com to get for example MXLinux

5
1.1. Introduction Page 6

, LinuxMint , Ubuntu, .....


By the way there is a very useful program to create a bootable Flash ventoy.
Execute the program to enable the boot in the flash, then just copy the iso
image to the USB. In this way you can put several image in your usb.
Here is the content of my USB (I have 2 distributions)

ls /media/mx194/Ventoy/snapshot/ -lh

total 5.2G
-rwxrwxrwx 1 mx194 mx194 1.7G Oct 10 21:40 MX-19.4_386.iso
-rwxrwxrwx 1 mx194 mx194 3.6G Oct 4 11:14 mx21BCustom0410.iso
-rwxrwxrwx 1 mx194 mx194 54 Oct 4 11:14 mx21BCustom0410.iso.md5

1. Use a text editor, we preferably use geany (but gedit or another one
may be fine).

2. Use a Terminal, to launch commands and run programs.

3. Run commands on terminal is advised. Avoid graphical tools when-


ever possible. For example to list a directory content, use ls, instead of
calling a graphical file manager.

To convince oneself of the importance of the command line, here is just an


example.

Example 1. Suppose we want to convert a list of images (say 120 images !!!)
gif to png image. With a graphics tool converters, we have to open each
image, export in the new format.
Repeating this task 120 times is really painful, arduous and takes time. Now,
look at this command (just one loop command!!!), try it yourself
Solution 2. The variable “i” takes successively the name of the file, listed by
the command «ls *.gif», convert it to the new format. That’s it !!

for i in $(ls *.gif) ; do convert $i.gif $i.png done

Exercise 3. It is also important to feel comfortable in front of your machine,


so it is recommended, to do

• Customize the Text editor and the Terminal

AnalyseNum A.Belahcene December 13, 2021


1.1. Introduction Page 7

• Open the Terminal on half of the screen and on the other half the Editor
(eg geany).

• Open several terminals: practice yourself by doing exercises from the


next section.

1.1.2 Useful Commands

mkdir myDir Creates «myDir» directory, in the current directory. «mkdir -p


dir1/dir2» creates the directory rep2 in dir1 (if dir1 does not exist it is
also created). mkdir stands for make directory

pwd gives the current directory. pwd stands for ---> Path Working Directory

cd myDir go to «myDir» directory. cd means ---> Change Directory

ls -lrt /etc List files and directory of the «/etc» with option details (-l),
sort by time (-t) in reverse order (-r). To sort by size use (-S).

cat file.txt Displays the contents of the file «file.txt». With «zcat» you
can display a compressed text file. (On-the-fly decompression when
displaying).

cp f1.txt f2.txt Make a copy of f1.txt, called f2.txt

mv f1.txt f3.txt The file f1.txt is renamed f3.txt

rm f*.txt removes all files starting with «f» having extension txt. Be careful
with this command!!!

ls > f1.txt The list of the current directoy is stored in the file f.txt. If the
file f.txt exist , it’s content is erased. With the symbol “>>”, the list is
appended (added at the end) to the content..

history Gives the list of commands executed so far

Exercise 4. Open a terminal, type cd (without parameter, by default you go to


your home directory), create your own folder give it YourName, then inside
it 2 folders: Progs and Docs.

AnalyseNum A.Belahcene December 13, 2021


1.2. Using asciinema Page 8

Open geany editor, write in some sentences, save the content as file.txt in
your Docs folder. Comeback to the terminal, go to Docs. List the content
with details (use ls -l ), you should find your file.txt.

1.1.3 Tree Structure of the System

The whole system (hard disks, CDROM, flash Disk or remote media on other
machines !!) is attached to the root denoted by the symbol “/”.
The main folders, attached to the root are :

/bin,/usr/bin contains basic (binary) commands, for example ls, cat, mkdir,
..

/etc contains the service and system configurations, like webServer,

/home contains user directories. Each user has a folder in this directory.

Exercise 5. Navigate in your system, by using :

• File manager (graphical program)

• The «ls» command with different options (-l, -lt, -lS, -lrt)

Remark 6. (Classroom work) Keep all your work and programs in your Progs
Folder. Puts the documents you use in the Docs folder. At the end of the
session you should take your programs in flask disk.

1.2 Using asciinema

In Debian-like linux distribution like (Debian, MX, mint, Ubuntu,...), just use
apt-get install asciinema to install it, or download it and install it with
dpkg -i. You must be administrator.
Asciinema is a small, but very useful program to record and play a terminal
session.
To record a terminal session, just type in terminal : asciinema rec nameOfFile,
and all what you do in the terminal is store the file.

AnalyseNum A.Belahcene December 13, 2021


1.2. Using asciinema Page 9

For this reason, if you open a file to read from or to write in, use a text-text
editor like nano. Nano opens the file in a terminal, and all what you do in
nano editor is stored. But if you open graphical editor like geany, gedit, ... ,
which opens a window outside the terminal, ALL you do out the terminal is
not saved.
To finish recording, type CTRL-D.
So, to see the recorded session just type in terminal : asciinema play nameOfFile.
In practice, maybe, you want to see rapidly the session to have just an idea,
before following the different steps of the session, that ’s easy, give the speed
option.
For example : asciinema play -s 4 nameOfFile plays the session 4 times
faster. And you can also play more than one session, each one on a terminal.
Remark 7. Since there is no sound attached to the file, you can write expla-
nations in the terminal, however you must start with a «#» symbol, to tell to
shell, it is a comment and not a command .

Example 8. Run the following session firstly with speed 10, to get a idea
about the subject, then with normal speed. Of course you can run it again
and again. Get from the server the file Demo.cast and check it. The python
program used is given here. Execute the command, for example with speed
10, asciinema play -s 10 mkdir.cast Then without -s option to follow
and execute the commands.
If you want to pause the playing, just hit the space key. Hit it again to
continue.
This demo tests the following commands :

cd
mkdir Docs Progs
cd Progs/
nano p1.py
this file contains : v=input("Please your Name : ")
print(" Hello : ", v)
ls -l
python3 p1.py
cd
cd Docs
pwd

AnalyseNum A.Belahcene December 13, 2021


1.2. Using asciinema Page 10

cd ..
pwd

Exercise 9. Use the previous demo. Create in your home Folder : Docs and
Progs directories. Go to Progs folder, create the file p1.py using nano, test the
program. Create another file p2.py with same commands but, now, use the
geany editor. Don’t forget to save p2.py in the Progs Folder.

AnalyseNum A.Belahcene December 13, 2021


Chapter 2

Basic Python
In this Chapter, we give a summary, through examples, of the essential ele-
ments of the Basic Python. For more details consult for example our docu-
ment “myPython_Base_2021”.

2.1 History Command

2.2 Basic Statements

2.2.1 Operators

Arithmetic *, /, +, ** (Power), // (integer division), % (remainder of integer


division)

Relational <, <=,>,> =, == (equality test)! = (Different)

Logical and (logical AND), or (inclusive OR), not (NOT)

Binary logic & (binary AND), | (Binary OR), ~ (NOT: 1’s complement), ^
(binary exclusive OR), >> (right shift), << (left shift)

Example 10. Using operators

tt, ff = True, False


a1, a2, a3 = tt and ff, tt or ff, not ff
a1, a2, a3 contain respectively: (False, True, True)

11
2.2. Basic Statements Page 12

a, b = 23, 115
c, e = a | b, a & b
c, e contain (119, -24)
e, f = ~ a, ~ b
e, f contain (-24, -116)

We can display the contents of the variables in binary like this :

bin (a), bin (b), bin (c)


gives ----> (’0b10111’, ’0b1110011’, ’0b1110111’)

Example 11. Run the following program, try to understand the result. Get
the files operators.py and operators.cast from the our local server

Listing 2.1: logical and Binary Operators


1 tt, ff = True, False
2 a1, a2, a3 = tt and ff, tt or ff, not ff
3
4 print( "Value of a1, a2, a3 :", a1,a2,a3)
5 print(" Binary Operators : & , | and ~")
6 print("resp. and , or and not ")
7 print("Integer Value and Binary representation")
8
9 a, b = 23, 115
10 c, d = a | b, a & b
11 e= ~ a
12 f= a >> 3 # shift toword the right
13 # same as dividing by 8 (integer division)
14 g= a << 2 ## same as multipling by 4
15
16 print (" a = ",a," binary format :", bin(a) )
17 print (" b = ",b," binary format :", bin(b) )
18
19 print (" c = ",c," binary format :", bin(c) )
20 print (" d = ",d," binary format :", bin(d) )
21
22 print (" e = ",e," binary format :", bin(e) )
23 print (" f = ",f," binary format :", bin(f) )
24 print (" g = ",g," binary format :", bin(g) )

2.2.2 String Operations


For strings the operator "+" makes a concatenation, The symbol is used "*"
to repeat the string, like this for example:

AnalyseNum A.Belahcene December 13, 2021


2.2. Basic Statements Page 13

A = ’salam’
B = A + ’alaykum’
01011 + 01110
C = A * 2 + B
A, B gives ----> (’salam’, ’salam alaykoum’)
C gives ----> (’salam salam salam alaykoum’)

2.2.3 Standard Inputs/Outputs


To display on the screen, one ca use the «print» function like this:

print (A, ’salam alaykoum’, myText)

The words «A» and «myText» are variables, on the other hand «salam alayk-
oum» is a string and so it is surrounded by character «’», (we can also use the
double quote «"»)
To read from the keyboard we use the «input» instruction, we can display a
help message, before reading like:

msg = input (’Enter your Name’)

The variable «msg» receives the string entered by the keyboard, the message
between "(,)" is displayed as an indication (this message can be ignored).
When we want to receives a value (integer or real number), we ca use «eval»
function (or float or int) to convert the string to value.
By the way the function eval () can evaluate a mathematical expression.
Check the code:

import math as m
eval( "m.sin(3.1)**2+ m.cos(1.67)")
gives the value ----> -0.09731208511033676
x, y =eval( input("2 real Numbers : "))
2 real Numbers : 12.345, -1.55
print(" Sum : ", x+y) gives ----> Sum : 10.795

Formatted outputs

We can precise how to print the data, specially the numbers, by using the
keyword format, here are some examples

AnalyseNum A.Belahcene December 13, 2021


2.2. Basic Statements Page 14

Example 12. Using the format keyword after the string to format

a,b,c = 12, 234.546, ’Salam alaykoum’


print("a={0:6d},b={2:10.1f} c={1:25s} a={0}".format(a,c,b))
a= 12,b=234.5 c=Salam alaykoumou a=12

Between « {}» we put the number of the variable and the format, that {0:6d}
means the variable 0, here is «a»,is displayed in 6 decimal positions, {2:25s},
displays the third variable as a string in 25 positions. Note that numbers are
right justified while string are left justified. We print again «a», we give it the
its index. If nothing is given between «{}», it is displayed in the order of the
variables, in the default format.

2.2.4 Tests and Loops

The presence of ":" is mandatory for any block (while, for, if, or functions).
The instructions in a block, must be preceded by a tabulation or a character.
Avoid mixing tabulation and character (make an indentation).
The newline (without indentation) ends the block. We can obviously have
nested blocks.

for i in 12,15,55,38:
if i> 20: ## Tab or space
print (i, "> 20") ## two tabs or spaces
output ---> 55 > 20
output ---> 38> 20

General Format of «if»

Example 13. The following instructions show: 12 small and even, 17 is odd,
22 is large and even.

for a in range (12,25,5):

if a% 2: print (a, " is odd")


elif a <20: print (a, "is small and pair")
else: print (a, "large and pair")

Notice that no condition follows «else»

AnalyseNum A.Belahcene December 13, 2021


2.2. Basic Statements Page 15

General Format of For and While

Consider the same procedure written in a different ways:

i=10
for i in range(10,28,3): while i < 28:

print (i,end=" ") print (i,end=" ")


i += 3
10 13 16 19 22 25
10 13 16 19 22 25

The function «range» generates a list of numbers. it has 3 different writings :

range(N) : gives the list 1, 2, ...., N-1

range(M,N) : gives the list M, M+1, ..., N-1

range(M,N,S) : gives the list M, M+S, ..., L : L is Last number < N


Example 14. Write the following code to a file and run the program.

Listing 2.2: basic statements


1 a = eval (input (’Give 1,2 or 3 (or 0 to finish)’))
2 while a != 0:
3 if a == 1:
4 print ("You have chosen: 1")
5 elif a == 2:
6 print ("You prefered : 2")
7 elif a == 3:
8 print ("You choosed the largest ")
9 else:
10 print ("Please give 1, 2 or 3!!")
11 print (’Choose a number again (or zero to end) ’, end = ’’)
12 a = eval (input (’Give 1,2 or 3 (or 0 to finish)’ ))
13 print("Thank you, Good bye")

Exercise 15. Write a program that displays: (Use the «for» then «while»
command)

• Integer numbers <10

• Integer numbers <10 in decreasing order

• Integer numbers <40 by steps of 3 (i.e: 0,3,6, ...)

AnalyseNum A.Belahcene December 13, 2021


2.3. Some Methods on String Page 16

• The whole numbers from A to B in steps of P. The numbers A, B and P


are read from keyboard.

• The whole numbers from A to B multiple of 5. The numbers A and B


are read from keyboard.

• Make a menu for the choice of the program to be executed.

2.3 Some Methods on String


Let x be a string, just type x.<Tab> (<tab> is the tab key), on the interactive
python console, to get the list of the different methods. This procedure (use
the <tab> ) can be used for any object.

x = "salam alaykum"
x.strip (’um’)

gives ----> ’salam alayk’ , remove um at the end

x.find (’am’)

gives ----> 3 (index of the substring am )

x.upper () gives ----> ’SALAM ALAYK’

the count method, count the number of occurrence for the argument. We
can also use the string without a name like ’salam’.upper() gives —->
’SALAM’

x.count (’a’)

gives ----> 4 ( number of occurrence of ’a’)

The split method breaks the string into list of elements, using a separator, by
default the separator is «space».

x = "salam;alay; kum;Hello; world"


x.split()

gives --> [’salam;alay;’, ’kum;Hello;’, ’world’]

x.split(’;’)

gives --> [’salam’, ’alay’, ’ kum’, ’Hello’, ’ world’]

The replace method, replace a string by another, like

AnalyseNum A.Belahcene December 13, 2021


2.4. Lists Page 17

x.replace(’a’,’AA’)

gives --> ’sAAlAAm;AAlAAy; kum;Hello; world’

Exercise 16. Check all theses operations and examples from yourself. Firstly
run the recorded file string.cast ( get it from our local server)

2.4 Lists
A list is a set of objects grouped together under the same name. The objects
are not necessary of the same type, like

myL = [1, 3.5, "a string", [’hello’, ’still’], [12.5, 156]]

To get an element we use the index, like

myL[1] --> 3.5


myL[2] --> ’a string’
myL[3] --> [’hello’, ’still’]
myL[4][0] --> 12.5

By the way my_list is an object of the class list, which has methods, for
example to add an element at the end of my_list, we use the append
method:

myL.append(’salam’)
myL [1][ 3]

You can also build a list with the list constructor, «list» like this: aList = list
(); aList is now an empty list object.
The access to items is done by using index (use square brackets []), we start
at 0, we can start at the end by using negative index.

myL=[’start’, 11,2,’salam’,23.5, ’alaykoum’, 3.14, ’hello’]


myL[0] gives ---> ’start’
myL[4] gives ---> 23.5
myL[-1] gives ---> ’hello’
myL[-2] gives ---> 3.14

AnalyseNum A.Belahcene December 13, 2021


2.4. Lists Page 18

Essential List Methods

Most of these methods directly modify the list (except copy). That is the list
is modified after using the method, and doesn’t return anything.

my_list [3], the string "Hello".

append add an element at the end of the list.

insert inserts an element at the indicated position (append is a special case


of insert)

remove Remove the argument from list


sort sort the list, this is a method, it modifies the content. The type must be
the same. If no argument is given, the sort is increasing order,
alphabetical or numeric according to the type. The code of «digit» is
less that «letter» according to ASCII code, that is ’34’ is less that ’A0’.
See the Unicode UTF8 for more details. The argument reverse=True,
changes the sorting order.
One can use the function sorted (not a method), to sort a list (and
also a tuple). In this case this original list is not modified. Like
d=[3,5,1,10,9]
s=sorted(d)
s gives ----> [1, 3, 5, 9, 10]
d gives ----> [3, 5, 1, 10, 9], it remains, d is not modified

reverse reverses the order of the elements

copy creates a new list from the first one.

clear clears the list;

pop retrieves from the list the element whose index is given as an argument
(by default the last one, which is equivalent to pop (-1) and removes it
from the list.

del removes an element from the list by giving its index. this is a function
and not a method, i.e we write: del ll [2] and not ll.del (2).

split splits a string into a list according to the criteria given in argument.

AnalyseNum A.Belahcene December 13, 2021


2.4. Lists Page 19

join is the reverse operation of split. It creates a string from the list. The
leading characters are used as the joining element.

Consider the list : LL = [["fs", "666", "aa"], ["33", "rt"]]

append, insert
LL[1] .append ("Hello")

LL ---> gives [[’6666’, ’aa’, ’fs’], [’33’, ’rt’, ’Hello’]]

LL[0].insert (2, ’hello’)

LL ---> gives [[’666’, ’aa’, ’hello’, ’fs’], [’33’, ’rt’, ’Hello’]]

LL [1] .remove (’333’)

LL ---> gives [[’666’, ’aa’, ’hello’, ’fs’], [’rt’, ’Hello’]]

del LL [1]

LL ---> gives [[’6666’, ’aa’, ’hello’, ’fsre’]]

pp = LL [0] .pop (2)

pp ---> gives ’hello

copy method
LL2 = LL.copy ()
LL2 gives ---> [[’fs’, ’666’, ’aa’], [’33’, ’rt’]]
LL2.reverse ()
LL2 gives ---> [[’33’, ’rt’], [’fs’, ’666’, ’aa’]]
LL2[1] gives ---> [’33’, ’rt’]

sort method
LL2[1] .sort ()
LL2 gives ---> [[’33’, ’rt’], [’666’, ’aa’, ’fs’]]
LL2.sort(reverse=True)
LL2 gives ---> [[’666’, ’aa’, ’fs’], [’33’, ’rt’]]

Customized sort, let consider a dictionary, and sort according the key ( see
lambda function in section : 2.6.6 on page 29 )

d= [{’name’: ’ali’, ’age’: 25}, {’name’: ’omar’, ’age’: 23}, {’name’: ’said’, ’age’: 35}]
d.sort(key=lambda x : x[’age’], reverse=True)
d gives --->
[{’name’: ’said’, ’age’: 35}, {’name’: ’ali’, ’age’: 25}, {’name’: ’omar’, ’age’: 23}]

AnalyseNum A.Belahcene December 13, 2021


2.5. Other Lists Page 20

split, join
ch = "dar-el-chabab-boumerdes"
type(ch)
lst2 = ch.split (’-’)
type(lst2)
lst2 ---> gives [’dar’,’el’,’chabab’,’boumerdes’]
ch2 = "***".join (lst2)
ch2 ---> gives ’dar *** el *** chabab *** boumerdes’

The elements of lst2 are joined with «***»

Exercise 17. Check all theses operations and examples from yourself. Firstly
run the recorded file list.cast ( get it from our local server)

2.5 Other Lists

2.5.1 Tuples

Python defines another type of list called "tuples", constructed using "(,)" and
not "[,]". But tuples are not editable, modifiable.
Tuples are preferable to lists, when passing them to a function, for example,
which should not modify them. tuples are "readOnly" lists.
Example 18. Example 1. We define t1 and t2 as tuples. List operations are
the same

t1, t2 = ("a", "b"), ("c", "d", "e")


t3 = t1 * 2 + t2
t3 receives: another tuple : (’a’, ’b’, ’a’, ’b’, ’c’, ’d’, ’e’)

The zip function creates tuples objects from each element of the arguments:
Example 19. Here we create tuples, every element of the tuple takes one
from each entry, like

E = [’Red’, ’Blue’, ’Green’, ’Yellow’]


F = [’Rouge’, ’Bleu’, ’Vert’, ’Jaune’]
A = [’Ahmar’, ’Azraq’, ’Akhdar’, ’Asfar’]
for i in zip (E, F, A): print (i)

gives ---> (’Blue’, ’Bleu’, ’Azraq’)


(’Green’, ’Vert’, ’Akhdar’)
(’Yellow’, ’Jaune’, ’Asfar’)

AnalyseNum A.Belahcene December 13, 2021


2.5. Other Lists Page 21

2.5.2 Dictionary

Yet another type of list are the dictionaries, which are modifiable but not
ordered, and access is by key, and not by index.
A dictionary is created using braces "{,}". To find an element we put the key
between brackets. Note here that the addition of element is done by a simple
assignment, in particular the key, for the lists one uses rather the function
append.
Example 20. Creating and using a dictionary:

d = {} creation of an empty dictionary


d [’keyb’] = ’keyboard’
## add an element, keyb is the key and keyboard the value
d [’mouse’] = ’souris’
d [’screen’] = ’elshasha’
d
gives --> {’keyb’: ’keyboard’, ’mouse’: ’souris’, ’screen’: ’elshasha’}
c = {’prem’: 1, ’sec’: 2, ’tris’: 3, ’quatro’: 4}
c [’tris’] gives ---> 3
del c[’prem’] ---> remove item
c
{’sec’: 2, ’tris’: 3, ’quatro’: 4}
del c ---> destroys the variable
c ---> gives error
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ’c’ is n

Note that the order in which the values are saved is not necessarily the one
given at the creation.
The keys method returns the keys of the dictionary and values returns the
values

d.keys()

gives ---> dict_keys([’keyb’, ’mouse’, ’screen’])

d.values()

gives ---> dict_values([’keyboard’, ’souris’, ’elshasha’])

The list if values or keys may be obtained with the «list()» function

dd=list(d.values()) ; dd

gives ---> [’keyboard’, ’souris’, ’elshasha’]

cc=list(d.keys()) ; cc

AnalyseNum A.Belahcene December 13, 2021


2.5. Other Lists Page 22

gives ---> [’keyb’, ’mouse’, ’screen’]

Exercise 21. First test the following code :

d1={’amar’:22, ’salima’:21, ’wahab’:32,’malika’:16}


d2={’amar’:22, ’samira’:21, ’wahab’:31}
for k in list(d2.keys()): print(k, ’ is in d1 dict ’)

2.5.3 Shortcuts on Lists

An even more elegant way to create lists.


The list consists of an expression between "[,]" for a list, or between "(,)" for
a tuple, followed by the "for" clause, which may be followed by "if" or "for"
clauses.
Example 22. Some examples to illustrate the use.

v1 = [2, 4, 6, 8 ]
v2 = [3 * x for x in v1]

v2 gives ---> [6, 12, 18, 24]

v3= [3 * x for x in v1 if x > 4]

v3 contains ---> [ 18, 24]

v4=[[x, x ** 2] for x in v1]

v4 contains --->[[2, 4], [4, 16], [6, 36], [8, 64]]

Check the folloging program in Listing 2.32.3

Listing 2.3: Use lists Simply


1 L1 = [2,4,6, 8, 10]
2 a=[3*x for x in L1]
3 b=[[x,x**2] for x in L1]
4 c=[3*x for x in L1 if x>5 and x < 13 ]
5 d=[3*x for x in L1 if x**2<50 or x > 10]
6
7 L2 = range(3,5)
8 e=[x*y for x in L1 for y in L2]
9 print(" L1 List : " , L1)

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 23

10 print(" L2 List : " ,end=’\t ’)


11 for i in L2: print(i , end=’\t ’)
12 print("\n A List : " , a)
13 print(" B List : " , b)
14 print(" C List : " , c)
15 print(" D List : " , d)
16 print(" E List : " , e)
17
18 """
19 Output :
20 L1 List : [2, 4, 6, 8, 10]
21 L2 List : 3 4
22 A List : [6, 12, 18, 24, 30]
23 B List : [[2, 4], [4, 16], [6, 36], [8, 64], [10, 100]]
24 C List : [18, 24, 30]
25 D List : [6, 12, 18]
26 E List : [6, 8, 12, 16, 18, 24, 24, 32, 30, 40]
27
28
29 """

Exercise 23. We want to create a dictionary for students, we mean the name
followed by the grade, like : {’Berkane’: 14, ’zaichi’: 12.5}, we have the list of
the name et the corresponding grades. Test with the following lists:

students=[’Berkane’,’Zaichi’,’Chabi’, ’Morsli’,’Bensid’]
grades=[14, 12.5, 15, 11.5, 9]

Then print the dictionary obtained. Hint: see example 19 on page 20

2.6 Functions

2.6.1 Definition
The creation of user functions is done by the keyword: "def". A function can
admit several parameters as input and may return a value.

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 24

Listing 2.4: using Simple Functions


1 #Using Functions
2
3 def fact(n):
4 ’’’This function returns the factorial
5 of the integer given as argument ’’’
6 val,i=1,1
7 # initialise both variables val and i
8 while i <= n:
9 val *= i
10 i = i+1
11 return val
12 ## don’t forget the indentations
13 ## Tabulations or Spaces
14
15 a = eval( input(’Give an Integer :\t’) )
16 ## eval convert string to number
17 nbre=fact(a)
18 print("Factorial of ",a ," is : " ,nbre)
19 ’’’
20 Outputs:
21 python3 example2.py
22 Give an Integer : 5
23 Factorial of 5 is : 120
24 Prog$ python3 example2.py
25 Give an Integer : 14
26 Factorial of 14 is : 87178291200
27 ’’’

Exercise 24. Add to the example 2.4 the recursive form for the factorial func-
tion

LAB1
Get the programs from my Server

1. Complete the program matrixStud.py. You’ll find explanations and


what to do inside the program.

2. Complete the program argStud.py. You’ll find explanations and what


to do inside the program.

3. write a function to calculate the integral of a function using the trape-


zoidal method. Complete the program trapIntegrStud.py. You’ll find
explanations and what to do inside the program.

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 25

2.6.2 Implicit arguments


We can define a default argument, i.e. this value will be taken if the
argument is not supplied

def f1 (ll = 25):

return 2 * ll

f1 (15) gives ----> 30


f1 () no argument, assumed 25,

gives ----> 50

If several arguments are used, the arguments provided are taken in the order
given, the missing ones are the last in the list
Example 25. In the first case no argument is given, "a, b and c", keep the
default values. In the second case, the 2 arguments provided are assigned to
“a” and “b”, c receives the default value. Note that the type of the variable
is defined by its content

def ff (a = 12, b = 34.5, c = ’salam’):

aa = 3 * a; bb = 4 * b; cc = 2 * c;
return aa, bb, cc

a1, b1, c1 = ff ()
print ("a1: {} b1: {} c1: {}".format (a1, b1, c1))

gives ----> a1: 36 b1: 138.0 c1: salam salam

a1, b1, c1 = ff (’OK’, 33)


print ("a1: {} b1: {} c1: {}". format (a1, b1, c1))

gives ----> a1: OKOKOK b1: 132 c1: salam salam

a1, b1, c1 = ff (25, c = ’GOOD’)


print ("a1: {} b1: {} c1: {}".format (a1, b1, c1))

gives ----> a1: 75 b1: 138.0 c1: GOODGOOD

In the last case, the argument "a" receives 25, "c" receives "GOOD", and "b"
keeps the default value. i.e : 34.5.

a1,b1,c1=ff(c=’OK’, 13)

gives ---->error File "<stdin>", line 1

The statement a1, b1, c1 = ff (c = ’GOOD’, 25) gives an error, the provided
values (here: 25) must be the first, in the list of arguments. All the formal
argument must be given first!!

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 26

2.6.3 Reference as Argument

List type arguments are passed by reference, that is, any modification of the
argument in the function is done on the calling object.
Example 26. In this case, the content of "mylist" is modified in the function

def change (LL):

LL.append (547);

myList = [1,2,3]
change (myList]
print (myList)
displays ----> [1, 2, 3, 547],

we see here the list «myList» is modified


Of course this is not the case for simple variable , see the following

def modif(c): c=12


d=1234
modif(d)
d ---> gives ----> 1234

Be carefully with the assignment, the object is not duplicated, it just creates
a reference, i.e a new name for the same memory space. We can check it by
using the id (Object Identifier).
Example 27. Consider the following program. Notice the id of object v1 and
v2 are the same, which means, v1 and v2 reference to the same memory
location.

Listing 2.5: Objects with same reference


1 def Copy(V):
2 R=[]
3 for i in range(len(V)):
4 R.append(V[i])
5 return R
6
7 v1=[1,2,3.4,11]
8 v2=v1
9 print("Vector 1 it’s Id :\t", id(v1))
10 print(v1)
11 print("Vector 2 it’s Id :\t", id(v2))
12 print(v2)

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 27

13 v3=Copy(v1)
14 print("Vector 3 it’s Id :\t", id(v3))
15 print(v3)
16 ## ---------------------------------------
17 v1[0]=999
18 print("v1 is Modified \nv1[0] :\t\t",v1[0])
19 print("v2[0] :\t\t", v2[0])
20 print("v3[0] :\t\t", v3[0])
21 ’’’
22 Prog$ python3 reference.py
23 Vector 1 it’s Id : 140431382574400
24 [1, 2, 3.4, 11]
25 Vector 2 it’s Id : 140431382574400
26 [1, 2, 3.4, 11]
27 Vector 3 it’s Id : 140431381165952
28 [1, 2, 3.4, 11]
29 v1 is Modified
30 v1[0] : 999
31 v2[0] : 999
32 v3[0] : 1
33 ’’’

In the following code, while the «w» variable is just an other name (same id)
for the «v» variable, «vv» is a new space ( with different id) where values of
v are copied.

v=[1,2,3,4]
w=v
vv=[x for x in v]
id(v) ---> 139824555062464
id(w) ---> 139824555062464
id(vv) ---> 139824554079104)

2.6.4 Arguments Variables

A function accepts any list of arguments, the number arguments not being
known while writing the function.
The formal arguments (always provided) must be given at the beginning, the
others are preceded by a "*".
A function can also receive a dictionary as an argument. We use "**" in front
of the variable. The most complete declaration is : f1 (a, b, *c, **d).
Here «a» and «b» are formal, «c» is a list and «d » is a dictionary.

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 28

Example 28. Here is a complete example, how to use list and dictionary as
argument of function

Listing 2.6: Multipltes Arguments


1 def Fonc( a1, *a2, **a3):
2 # a1 always provided
3 print("\nFormal argument ", a1)
4 print("Argument as a list ", a2)
5 print("Argument as a Dictionary ", a3)
6
7 n,l,d = 12.25, (17,44), {"v1":23, "v2":121}
8 # just a formal argument
9 Fonc(n)
10 ## a list is added
11 Fonc(n,*l)
12 ## a dictionary is given too
13 Fonc (n,*l,**d)
14 """ Resultat
15 argument Formel 12.25
16 argument liste ()
17 argument dictionnaire {}
18
19 argument Formel 12.25
20 argument liste (17, 44)
21 argument dictionnaire {}
22
23 argument Formel 12.25
24 argument liste (17, 44)
25 argument dictionnaire {’v1’: 23, ’v2’: 121}
26 """

Exercise 29. TODO

2.6.5 Argument of a Program

When we run a program, we often give arguments to this program by com-


mand line.
For example, in system mode, to copy a file to another, in a terminal we write:
cp f1.txt f2.txt. Here f1.txt is the first argument and f2.txt is the second
argument of the cp program.

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 29

Python provides through the sys module, the procedure for retrieving these
arguments. The argument as read as a string, so in case we need numbers
we have to convert them.
Example 30. As shown in the example (see the recorded demo :
functions.cast), we use eval to convert the string of digits to numbers.
Check the value of the system variable «$?», after running the program, if
there is no error, you ’ll, 0 otherwise, if you haven’t supplied required
argument, you ’ll get «43», see the exit function in the program. To print this
value, in terminal type : echo $?

Listing 2.7: Arguments for the main Program


1 import sys
2 message=’’’
3 This Program needs three Arguments :
4 A string, follows by integer than a reel number
5 ’’’
6 if len(sys.argv) < 4:
7 print(message) ; exit(43)
8
9 # argv[0] contains the program name
10 print(" Program Name : ", sys.argv[0])
11 print(" First argument : ", sys.argv[1])
12 print("Type of arg1 : {}".format(type(sys.argv[2]) ) )
13 print("Type of arg2 : {}".format(type(sys.argv[3]) ) )
14
15 numb1=eval(sys.argv[2])
16 numb2=eval(sys.argv[3])
17 print("The product of argument 2 and 3 : ", numb1*numb2)

2.6.6 Anonymous function

Sometimes we use a small function, it is called «anonymous function», and


not defined with the keyword «def », but by using the keyword «lambda», it
does not have a proper name, its name is the name of the calling variable. It
is declared inline (in one line code) and can be used in an expression.
Its general format:

myVar=lambda [arg1 [, arg2, ..... argn]] Expression

The function returns Expression to the variable myVar and admits as argu-
ment the elements arg1, ...., argn

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 30

Example 31. Here is a sum function, with 2 arguments. The variable sum
receives the sum of the 2 arguments. Please, note here the «+» operator is
overloaded. Note also, sum is a function and not a simple variable.

sum = lambda a1, a2: a1 + a2;

sum (25, 13)


gives -----> 38
sum ("salam ", " alaykoum")
gives -----> ’salam alaykoum’
type(sum)
gives -----> <class ’function’>

For each couple of values it returns their sum. it is equivalent to :

def sum(a,b):

return a+ b

2.6.7 Variable scope

A variable can be local to a function or global visible throughout the pro-


gram. Test the following example. See example of listing 2.8

Example 32. We create inside the function «myFunc», another function called
«Local». The variable "a" declared non-local in the Local function is there-
fore the same as the variable "a" of parent function myFunc. The variable «b»
is declared Global, so in the same as the the «b» declared in the program (
outside the function myFunc).
However, in otherFunc, the variables are just used and not declared so they
keep last value known in the program.

Listing 2.8: Global, nonLocal and local variable


1 ’’’ Local variable, nonlocal
2 and global variable
3 ’’’
4 def otherFunc():
5 print("in OtherFunc b = ", b)
6 print("in OtherFunc a = ", a)
7
8 def myFunc(a):
9 global b

AnalyseNum A.Belahcene December 13, 2021


2.6. Functions Page 31

10 print(’Here in myFunc a = ’,a, " b = ", b)


11 a = 50 ; b= 33
12 print(’After Modif in myFunc a= ’,a, " b = ", b)
13 # define a function inside another
14 def Local():
15 nonlocal a
16 a=254
17 print(’In Local Function a = ’,a)
18 Local()
19 print(’Out of Local, but in myFunc a = ’,a)
20
21 b, a =25 , 100
22 myFunc(40)
23 print(’After calling myFunc : a= ’,a, " b = ", b)
24 otherFunc()
25
26 ’’’
27 Output of the program:
28 Prog$ python3 localGlobal.py
29 Here in myFunc a = 40 b = 25
30 After Modif in myFunc a= 50 b = 33
31 In Local function a = 254
32 Out of Local, but in myFunc a = 254
33 After calling myFunc : a= 100 b = 33
34 After calling myFunc : a= 100 b = 33
35 in OtherFunc b = 33
36 in OtherFunc a = 100
37 ’’’

2.6.8 Files

To store data permanently we need files, or to restore data we read it from


file. We have specific functions that handle and process them.

Text Files

A text file is a series of characters, each character is coded by itself, in ASCII


or Unicode code.
The file must be opened, before reading from it. The operation in fact is to
find the file in the disk, and read all it properties, using the i-node. An
i-node (index ) is attached to each file, it contains, among other fields . (see
the stat structure) :

AnalyseNum A.Belahcene December 13, 2021


2.7. Exception Handling Page 32

i-node number # use option -il in ls command like :


ls -li /etc/passwd, to get the the i-node number of the file passwd
st_mode access permissions
st_size the size of the file
st_atime, st_mtime; last access and modified time

After that (opening procedure), if there is no problem, one can read from or
write in the file.
Example 33. The file must firstly be opened, the following code copy a text
file to another file.

def copyFile(inp, out):

”’copy a file to another file”’


fs = open(inp, ’r’) ## Open files
fd = open(out, ’w’)
while 1:
txt = fs.read(11)
if txt =="": break
print("Text read : ", txt)
fd.write(txt)
fs.close() ; fd.close() ## Close files
return

copyFile(’e.txt’, ’f.txt’)

2.7 Exception Handling

2.7.1 Types of errors

When an illegal operation is performed if nothing is planned then the pro-


gram stops and gives the error message.
An illegal system operation can be, for example:

• A division by 0

• A division by a string other than a number

• an undefined variable

• a non-existent file, etc .....

AnalyseNum A.Belahcene December 13, 2021


2.7. Exception Handling Page 33

• An illegal user operation, like out of range of legal values, or illegal


dates.
Example 34. Some types of exceptions

a = 12, b = 0
a / b -----> ZeroDivisionError: division by zero
b = ’8’; a / b -----> TypeError: unsupported operand type (s)
a / c -----> NameError: name ’c’ is not defined
open (’file.txt’) -----> FileNotFoundError: No such file or directory
open (’ff.txt’) -----> PermissionError: Permission denied:

2.7.2 Raising the exception

Raising the exception means, predict what to do in the one of these errors
occurs, or what to do in general case. And thus let the program continue,
when an exception is detected.
To achieve this goal and purpose objective, one must plan to throw an excep-
tion for each type, and what to do in each case.
We can also provide a raiser for any exception, as will be seen in detail.
We then try the instruction block:

try :

This block is executed if no error detected

except:

Here what to do if error

Example 35. In this program , we have handled the errors of type "TypeEr-
ror", the program has to continue, but not the exception "ZeroDivisionError",
the program did not display the last message.

Listing 2.9: raising Exception example 1


1 num=12 ; den=’cc’
2 try:
3 print (f ’result: {num/ den} ’)
4 except TypeError:
5 print ( ’The types are not valid’)
6

AnalyseNum A.Belahcene December 13, 2021


2.7. Exception Handling Page 34

7 print ( ’Program Continues . . . . . . ’)


8 den = 0
9 try:
10 print (f ’report: {num/ den} ’)
11 except TypeError:
12 print ( ’The types are not valid’)
13 print ("End of the Program, Good Bye")
14
15 ’’’
16 Output of the program :
17 The types are not valid
18 Program continues . . . . . .
19
20 Traceback (most recent call last):
21 File "/home/mx21/2021−22/OOP/Prog/exception1.py", line 10, in <module>
22 print (f ’report: {num / den} ’)
23
24 ZeroDivisionError: division by zero

Exercise 36. Replace, in the program 2.9 on the previous page the second
“TypeError” with “ZeroDivisionError” and verify that the program ends cor-
rectly.

We can put several exception in one «except» clause. If we omit the Error
from the clause, then any exception is accepted, unfortunately, the help is not
clear enough fro the use. For example , if you just say the entered «is not cor-
rect», it is not enough, is there a TypeError, ZeroDivisionError, NameError,
....?
Example 37. This is more complete example, for getting a real number
corresponding to rational number. The program still ask for values (
integers ), until the values entered are correct.

Listing 2.10: Exception example 2


1 while 1:
2 try :
3 n=int(input(’numerator ?:\t ’))

AnalyseNum A.Belahcene December 13, 2021


2.7. Exception Handling Page 35

4 except ValueError :
5 print (" Not an integer value entered ")
6 else :
7 break
8
9 print(" Program continues ")
10 while 1:
11 try :
12 d=int(input(’denominator ?:\t ’))
13 r= n / d
14 except (ValueError,ZeroDivisionError) :
15 print (" Value entered (not int or 0) is not valid ")
16 else :
17 print(f’Result : {r:12.4}’ )
18 break
19 print(" End of Program")

Remark 38. The number of exceptions can be large, but it is not necessary to
know them all, when throwing an exception the interpreter gives its name.

2.7.3 assert, raise, else and finally

Example 39. Consider the program in listing 2.11, the keyword "raise" indi-
cates the raising of exception, ie in our example "age <15" is considered as
exception, which will be raised and following line "except" the capture.
The "else" is executed when there is no exception, the "finally" is always
executed. The keyword "assert" is used to say that the condition "age> 20
and age <70" must be verified, otherwise the exception "AssertionError"
must be caught.

Listing 2.11: Using assert


1 age=eval(input("Enter your age : "))
2 try :
3 if age < 15: raise
4 except:
5 print(" Still teenager ")
6 else :
7 print(" Life goes for you ")
8 finally:
9 print(" Continue the program ")
10
11 try :
12 assert age > 10 and age < 70

AnalyseNum A.Belahcene December 13, 2021


2.8. Regular Exception Page 36

13 except AssertionError:
14 print (" Too Old or too young ")
15 finally:
16 print(" End of Program ")

2.8 Regular Exception

A regular expression is represented by a search pattern. This search pattern


will be able to be compared to one or more strings to determine the matches.
A search pattern can be composed of “normal” characters, that is to say char-
acters that represent only themselves and of “special” characters, that is to
say characters that have a special meaning, we call them “meta-characters”.

\ Escape character that will have several uses: gives a special meaning to a
character, or in inverse neutralize the special meaning of meta-character.

- Placed between two characters, allows you to indicate an interval of char-


acters (corresponds to writing the two characters and all the characters
between these two).

^ If placed at the very beginning of a class, allows to negate the class, that is,
to find any character that does not belong that object.

$ precise the end of a string or a line

. Any character

| An alternative (like the or operator) match the character to the right or to


the left

\w stands for word

\d stands for digit

\D any character but digit

\s a space (tabulation or new line)

\S inverse of \s

AnalyseNum A.Belahcene December 13, 2021


2.8. Regular Exception Page 37

\A the beginning of the string

\t horizontal tabulation

\f vertical space

\n newline
* 0, 1 or more occurrences, the last left character
ma*n matches mn, man, maan, ... but not main

+ 1 or more occurrence the last left character


? 0 or 1 occurrence
ma?n matches mn, man,woman, but not maaan

{n,m} This means at least n, and at most m repetitions of the pattern left to
it.
a{2,4} matches daaat, aabc but not badac

[. . . ] A character class: all the characters listed in the class, with the possibil-
ity of ranges whose limits are separated by "-". The «^» inside brackets,
invert the meaning of the expression.

• [a-e] is the same as [abcde].


• [1-4] is the same as [1234].
• [0-395] is the same as [012395].
• [^abc] everything but a, b and c
• [0-9]{2,4} matches 12, 3425, 45

(. . . ) A capture group: used to limit the range of a mask or an alternative.

• (a|b|c)xy matches abxz, cabxy not ab xz

2.8.1 re module

The module re implement the using of Regular Expression. We’ll this thru
examples.

AnalyseNum A.Belahcene December 13, 2021


2.8. Regular Exception Page 38

1.6.3 Match and Search

The general match search format:

re.match ( r’pattern’, String, flag = 0)


re.search ( r’pattern’, String, flag = 0);

Example 40. Here, the pattern corresponds to string starting with a,


finishing with s, and between them , exactly 3 characters

import re
pattern = ’^a...s$’
test_string = ’abrys’
result = re.match(pattern, test_string)
if result: print("Search successful.")
else: print("Search unsuccessful.")

After importing re, the pattern is an re, we put r in front of the pattern to
avoid any ambiguity, and trait pattern as a Regular Expression.
The String is the character string in which we are looking for the pattern.

The flag

The flag allows us to precise type of correspondence we are looking for (also
valid for search and replacement). Here are the meaning of some flags

re.I Ignore the case, both uppercase and lowercase are allowed

re.M According to beginning or end of the word or Line

re.S The «.» match any character comprising «\n»

re.U Use the uni-code characters.

Match

returns the matching string, if it finds it in the string. Just once.

AnalyseNum A.Belahcene December 13, 2021


2.8. Regular Exception Page 39

Search

The "search" function works like "match" except that match searches for the
match at the start of the string while search searches for it anywhere in the
string.

findall

Returns the list of all matches found.

Replace

Replace one character string with another, use the re.sub command.

split

break the string in parts according to the pattern: p=split(pattern, String,


maxSplit). maxSplit indicate the max elements obtained after splitting.
Example 41. A set of regular expression methods

Listing 2.12: regular Expressions


1 import re
2 string = ’hello 12 hi 89. Howdy 34 Others 8 ’
3 pattern = ’\d+’ # digit repeated, at least one
4
5 result = re.findall(pattern, string)
6 print(result)
7
8 line = "Python , Python 2 or python 3 is more useful than Perl or perl "
9
10 Obj_f = re.findall( r’python’, line, re.I)
11 if Obj_f:
12 print ( "findall --> the list: \n\t", Obj_f )
13 else:
14 print ( "findall ---> None!!")
15
16
17 string = ’Twelve:12 Eighty nine:89 Nine:9.’
18 pattern = ’\d+’

AnalyseNum A.Belahcene December 13, 2021


2.9. Turtle Page 40

19
20 # if the flag is N, split only at Nth occurrence
21 result = re.split(pattern, string, 2) #, flag)
22 print(f’ Splitting Result {result}’)
23
24 ## Substitute
25 phone = " 0775 - 353 - 321 # my friend mobile "
26 num = re.sub(r’#.*’, "AA", phone)
27 print ("Phone number without comment : \n", num)
28 num = re.sub(r’\D’, "", phone)
29 print ("Phone number : ", num)
30
31 ## multiline string
32 string = ’abc 12\
33 de 23 \n f45 6’
34
35 # matches all whitespace characters
36 pattern = ’\s+’ ## space, \t, \n
37 new_string = re.sub(pattern, "", string)
38 print("remove spaces :",new_string)

2.9 Turtle

The graphical part of python is not part of this course, but you should know
that there is a very rich and very easy to use library: matplotlib.
You can also use the tkinter graphics library, integrated into the Python stan-
dard, to create menus, windows and buttons. Here let’s just give a little
schematic plotting program. See chapter 5 on page 66
This is a small module allows you to draw simple figures, with the essential
commands:

reset() We erase everything and start over

goto(x,y) Go to location of coordinates x, y

pos() returns the current position of the pen.

forward(size) Go forward a given size

AnalyseNum A.Belahcene December 13, 2021


2.9. Turtle Page 41

backward(size) Backward

up() Lift the pencil (to be able to move forward without drawing)

down() Lower the pencil (to start drawing again)

color color can be a predefined string (’red’, ’blue’, etc.)

left(angle) Turn left by a given angle (expressed in degrees)

right(angle) Turn right

width Choose the thickness of the path

fill(1) Fill a closed contour using the selected color

write(text) text must be a string


Example 42. A small recreation example, the turtle module allows you to
play small games. see the following code:

Listing 2.13: Turtle Game


1 import time
2 import turtle as tt
3
4 bb= tt.Turtle()
5 bb.width(3)
6 bb.up()
7 bb.goto(70, -100 )
8 time.sleep(3)
9 bb.color(’blue’)
10 bb.write(’Star’, font=(14,) )
11 bb.goto(0, 0 )
12 bb.down()
13 a = 0
14 col= [ "red", "black", "purple", "pink", "green", "olive",
15 "blue", "brown","cyan", "yellow", "orange", "grey" ]
16 while a <12:
17 bb.color(col[a])
18 a = a +1
19 bb.write(a, font=(14,))
20 bb.forward(150)
21 time.sleep(0.5)
22 bb.left(150)
23 bb.reset()
24 input("just enter to end the program: ")

AnalyseNum A.Belahcene December 13, 2021


2.9. Turtle Page 42

Figure 2.9.1: Polygon Example with turtle

AnalyseNum A.Belahcene December 13, 2021


Chapter 3

OOP : the Concepts

3.1 Imperative Programming

Classic imperative programming separates data and processing on this data.


Given a type of data, we only say what will be the associated values.
The different operations that can be performed with this type will be defined
separately, in the form of functions.
Several problems appear, among others:

• The values are not encapsulated, that means: we can read or modify
these values everywhere. Values may not be properly initialized.

• So the variable may have inconsistent values.

• Programming logic and data are scattered, and can be found anywhere.

3.2 Response to Theses Problems

3.2.1 Structural Division of the Application

A structural breakdown of the application in the form of objects with clearly


identified roles.

43
3.2. Response to Theses Problems Page 44

• objects can be linked by simple associations, objects can communicate


with each other

• By aggregation relations (an object is made up of other objects),

• by inheritance relations (an object is a specialization of another object).

3.2.2 Breakdown of Treatments

A breakdown of the treatments in the form of methods operating on the at-


tributes of the object concerned.
When two objects are needed for processing, they communicate with each
other by sending messages to each other.
Basically, an object requests a service from another object by calling the ap-
propriate method of this object, and if necessary sending parameters.
The message sent to the other object is therefore the name of the method and
the call arguments required for its execution.

3.2.3 Designing Software

To write quality software, it is necessary to take into account quality mea-


surement criteria, we can quote and require :

Accuracy ability of software to provide desired results under normal condi-


tions of use.

Robustness Ability to react and respond well when deviating from normal
conditions of use.

Extensibility ease with which a program can be adapted to meet changing


demand.

Re-usability Ability to use parts of the software to solve other problems.

Portability is the ease with which one can operate the same software in dif-
ferent implementations.

Efficiency Optimization of execution time, memory size etc..

AnalyseNum A.Belahcene December 13, 2021


3.3. Basic Principles Page 45

3.3 Basic Principles

3.3.1 Practical Examples

Class Car

A car manufacturer, creates new model car (that is : type of engine, body-
work, power, options, etc.) with the tools and system for starting, braking,
protection, air conditioning, etc.)
After validation of the model, he sets up and configures the machines that
make these cars.
In the object-oriented sense, the model is the class with the attributes (power,
type of engine, fuel, ...) and the methods (accelerating, braking, .... ). So we
have cars of this type manufactured, in our field we call it : the objects of this
class.
When the customer buys a car of a given model, he buys an object of a given
class.

In summary

• Data (Attributes): Engine, Color, Year of manufacture, ...

• Functions (Methods) : Start, Accelerate, Brake, Sound, .....

Student Class

A person (Student) can have Name, Parents, Address, Weight, Height, and
so on, and can also do actions on himself, like Eating, Running, Jumping,
Sleeping, ....
Example 43. Ali Benameur is a 24-year-old student, lives in «martyrs road ,
Algiers» , weighs 73 kg, and is 1m78 tall. He enjoys running and swimming,
but also studying very hard.

• Data (Attributes): Name, Age, Address, Weight and Height

• Functions (Methods) : Running, Swimming, Studying

AnalyseNum A.Belahcene December 13, 2021


3.3. Basic Principles Page 46

3.3.2 Object and Class

An object is an instance of a class, or we can say an element of class, which


has the proprieties o f the class.
So if we declare the Student class with the following proprieties

• Data (Attributes): Name, Age, Address, Weight and Height

• Functions (Methods) : Running, Swimming, Studying

The treatments or functions are called methods or operations on the object


Data is called variables, data members, attributes or properties.
The Benameur declared in example 43 on the preceding page is an element
of Student or an instance of Student class.
An object combines data and processing, leaving only the object interface
visible, ie the processing that can be done on it.

• The overall behavior of an application is based on the communication


between the objects that compose it

• There is a strong and rich communication between objects

So we can say a class describes the domain

• It is a model that defines the data and processes common to a collection


of similar objects

• Each object belongs to that class

• The generalities are contained in the class and the particularities in the
objects.

Oriented Object is based on

More details will be given later.

AnalyseNum A.Belahcene December 13, 2021


3.3. Basic Principles Page 47

Abstraction ignore the details to keep only a general notion. we do not act
directly on the data of an object.

Encapsulation: binds together the data and functions that manipulate the
data.

Inheritance: allows you to define a new class from an existing class to which
new data and methods are added. (Specialization and reuse.)

Polymorphism: give several shapes to the same class of objects depending


on the data.

3.3.3 Abstraction

In order to protect the data against mishandling and misuse, some part of
the data of object is declared private and cannot be directly accessible, and is
hidden from the outside to the object.
So to use theses data we need access methods.
We call this concept : abstraction. This means we need an interface to our
class, which contains all required methods.

Example 44. Take the case of driving a car. To increase speed you need an
accelerator pedal, which adjusts the flow of fuel to the carburetor. The driver
does not have to know the quantity, nor to know how the gasoline arrives
and burns etc .... Imagine that the driver manually regulates the quantity
which goes into the carburetor !!!! We can imagine the rest ... !!

In our field, in computer science

Example 45. When you type in the " ls " command in the terminal, you get
the list of files, you don’t need to know neither on which sectors, track and
cylinder of the disk your files are stored, nor the number of pieces constitut-
ing your files !! ! all this is transparent to you (hidden). This means there is
an «Abstraction» or Access interface to manipulate your files. Imagine that
you have to give physical location of the files.

AnalyseNum A.Belahcene December 13, 2021


3.3. Basic Principles Page 48

3.3.4 Encapsulation

Put in the object, all what we need : Data and Methods, which them form
a whole. Let’s look at a simple example in which we compare the use of
procedural (through functions) and object oriented programming.
Example 46. Suppose we have a rectangle with a width, a height and a
color. We want a function to display its data. Using the procedural concept,
we write (in python for example) :

display(int w, int h, string s):

print( w, h, s)

display (12, 13, ’blue’)

We must send 3 parameters, which makes the call heavy, the time of use of a
function depends a lot on the number of parameters. Whereas with OOP,
we just use the method directly on the object ( if myRect is the object):

myRect.display()

The width, height and color values are the properties of the myRect object.

3.3.5 Inheritance

Another important advantage of object oriented programming is to complete


a class with properties and create a new class without creating all the ele-
ments. We call it the Inheritance.
Just as in real life, the child inherits from his mother, or from his grandfather,
the color of his eyes, for example

Example 47. Consider a class «Rectangle» containing the data : width and
height, and Display method which prints the data. Now we need a colored
Rectangle, we declare it as a child of Rectangle, and so we inherit width and
height. We just add the color to the colored Rectangle class, and can also use
Display the width and height.

AnalyseNum A.Belahcene December 13, 2021


3.3. Basic Principles Page 49

3.3.6 Polymorphism

The word polymorphism means several forms. When we have commonly


named methods across classes or subclasses.
This permits functions to use entities of different types at different times. So,
it provides flexibility and the code can be extended and easily maintained
over time.
In fact this notion of polymorphism, already exists in the classical arithmeti-
cal operators.

Example 48. This concept already exists in classical arithmetic operators,


such as plus when we write 12 + 14 , 12.0 + 14.0, and ’12’ + ’14’. Actually
we do not use the same operator. The operations are not implemented this
way, the first uses the fixed representation for the numbers, but the second
use the the floating point (mantissa and exponent), and in the third case, we
just concatenate (put the strings together).
So we the same symbol (or in the same way, the same name for function) to
do different operations.

AnalyseNum A.Belahcene December 13, 2021


Chapter 4

POO in Python

4.1 Everything is Object


In python everything is an object, thus: c= atoi(v)

a, b, c = 12, 4.55, ’C Language’


L=[’a’, ’b’, 123, 23.25]
type (a)

<class ’int’>

type (b)

<class ’float’>

type (c)

<class ’str’>

type(L)

<class ’list’>

These objects have methods predefined in the language, we can only use
these.
We have seen before, some methods for the String class and List class. Here
are some examples.
The method string method count give the number of occurrence of the
string given in argument. The list method append adds an element to the
list, that is :

c = ’ language C , C++ and Python ’


c.count (’an’)

50
4.1. Everything is Object Page 51

gives ----> 2

L=[ [ 1,2,3] ]
L.append([11,22,33])

In the same way, we can work around integer or float. We can write for
example:

a, b, c = 1245, 13.25, "salam"


a.bit_length ()

gives -------> 11 (number of bits of the integer)

b.as_integer_ratio ()

gives -------> (53, 4), transforms to rational number

c.upper ()

gives -------> ’SALAM’ (in upper case)

4.1.1 A Simple Class


Creating the class with the declaration

class ClassName:

put here attributes and methods

One of the simplest examples:

class myClass:

x = 10

p1 = myClass
print (p1.x)

displays --------> 10

We create the class "myClass" with a single attribute "x". We create an object
“p1” of type “myClass”, we display the attribute x of the object p1.
Remark 49. . The data is directly accessible. Here we are not yet talking about
a private, protected or public attribute. We will see later how Python deals
with these notions.

A complete class can contain:

• An object constructor

AnalyseNum A.Belahcene December 13, 2021


4.1. Everything is Object Page 52

• A set of object attributes

• A set of class attributes

• attribute processing methods

We see these notions through the following example.


Example 50. A class with object attributes

class Student:

__Number = 0 ## to store number of objects


def __init __ (self, name, age):
self.name = name
self.age = age
Student.Number += 1

Explanations

• The Number variable is an attribute of a class and not of an object, ie,


is not linked to a given object.

• The __init__ function, (you have to write it like this) is called each time
an object is created (it is the equivalent of a constructor in other lan-
guages such as C ++, for example.

• The first argument “self” (by convention, but we can give it any other
name) is used to differentiate argument variables from attributes. Here
age is the argument self.age is the attribute. The "self" argument indi-
cates the current object which is being processed.

• Attributes are public and accessible from outside the classroom.

class member

The attribute Student.Number relates to the class attribute. But can also be
used by an object. Indeed the attribute Number, does not concern any object
but the whole class.

AnalyseNum A.Belahcene December 13, 2021


4.1. Everything is Object Page 53

Thus Number contains the number of object of the class, which must be up-
dated each time an object is created or deleted.
Using the class «Student» :

E1 = Student ("Bouras malik", 23)


print ("Student {} is {} years old". format (E1.name, E1.age))

We add to our class a «display» method which prints the information about
a student object, the complete program is

def display (self):

print ("Student {} is {} years old" .format (self.name, self.age))

We, then use it, as follows: E1.display ()

As all the attributes and methods of the Student class are public, you can
modify any attribute or delete it.
Conversely to «__init__» method, which creates a new object, the method
«__del__» delete an object. Thus «__init__» is called when a new object is
declared, « __del__» is called hen an object is removed. We can then write:

del E1 ----> delete the object E1


print (E1.age) gives ---> an error

Example 51. The more complete Student class is

Listing 4.1: Student Class


1 class Student:
2 ’’’ The Student class has 2 attributes name and age,
3 a class attribute Number.
4 The __init__ method which initialise an object
5 and contains a display method the print the content
6 and finally a __del__ method wich remove an object
7 ’’’
8 Number = 0
9 def __init__ (self, nn, age):
10 self.name = nn
11 self.age = age
12 Student.Number += 1
13
14 def display (self):
15 print ("Student {} is {} years old".format(self.name, self.age))
16 print("in DISPALY Number : ", self.Number, " again ", Student.Number)
17

AnalyseNum A.Belahcene December 13, 2021


4.1. Everything is Object Page 54

18 def __del__(self):
19 Student.Number -= 1
20
21 s1=Student(’ali’,25)
22 s2=Student(’omar ’,22)
23 s3=Student(’moussa’,35)
24 s1.display()
25 s2.display()
26 s3.display()
27
28 print("Size of Student Class : ", Student.Number)
29 ###del s2
30 ##print("Size of Student Class : ", Student.Number)
31 ##s2.display() ## gives error and stops program
32 ’’’
33 try :
34 s2.display()
35 except:
36 print(" the object doesn’t exist ")
37 ’’’
38
39 msg=’’’\n\n Using the exception clause, the program ends normally,
40 otherwise, the program is stopped with error. Check in the terminal
41 the value of environment variable $?.
42 Run the program with and without the try bloc, and in each case
43 run the system command ; echo "value returned : $? "
44 if the program ends normally, it returns 0
45 otherwise other value, and this message is not printed \n
46 ’’’
47 print(msg)

The block «try/except» prevents the program from terminating abnormally


and allows the program to go to the end. Without it, the last statement is not
executed, and the program returns an error. As it is indicate in the program,
check it. For more details about «try/except» bloc, see the section 2.7 on
page 32

LAB2

Create a class, named Rectangle with 3 attributes and 4 methods :

AnalyseNum A.Belahcene December 13, 2021


4.1. Everything is Object Page 55

width, height the number of characters used to draw the rectangle. The rect-
angle consists of height rows, each row by width columns. By default
theses values are 1.

pattern this pattern is used to draw the rectangle. By default the value is ’*’.

perimeter gives the perimeter of the rectangle.

area gives the area of the rectangle

display prints the attributes of the rectangle. That’s width, height, perimeter
, area and pattern

draw draw the rectangle as height lines of the pattern. An offset is given to
right shift the drawing.

Here is an example of the program test :

r1 = Rectangle(25, 3, ’+’)
r2 = Rectangle(8, 4)
r1.width
r1.display() ; r1.draw()
r2.display() ; r2.draw(15)
r3=Rectangle()
r3.display() ; r3.draw()

Here is the output :

The rectangle is 25 width , 3 height, His perimeter is 56 and area 75


+++++++++++++++++++++++++
+++++++++++++++++++++++++
+++++++++++++++++++++++++
The rectangle is 8 width , 4 height, His perimeter is 24 and area 32
********
********
********
********
The rectangle is 0 width , 0 height, His perimeter is 0 and area 0

In the first phase :

• Put the data inside of the program (number of rows, columns, offset
and pattern)

AnalyseNum A.Belahcene December 13, 2021


4.2. Data Protection Page 56

• Create directly the objet as in the example

In the second phase :

• Read data from keyboard

• Use the try/except bloc for checking the data, that is :

– width is integer and ∈ [10, 50]


– height is integer ∈ [1, 15] .

• the body of a rectangle is empty. Print just the border.

4.2 Data Protection

Python does not have a special word for private or protected like C ++ or
Java, but instead uses a notation on the variable.
If all the attributes are public, an essential principle of object orientation ("Ab-
straction") is not respected.

private a variable preceded by "__" is considered private: the attribute or


method is only accessible from inside the class.

protected a variable preceded by "_" is considered protected: the attribute


or method is only accessible from inside the class or child classes.

Apart from these special cases, the data is accessible and public.
Let’s go back to the “Student” class and replace the Number variable with
__Number. In this case the instructions:

print ("Number of students:", Student .__ Number)


print ("Student {0} is {1} years old" .format (E1.name, E1 .__ age))

Give errors. We must then add to the class a public method which displays
this number and a method which retrieves the age.

AnalyseNum A.Belahcene December 13, 2021


4.3. Inheritance Page 57

Example 52. The class becomes as follows. Note the absence of self for the
class method.

def age(self):

return self.__age;

To retrieve the age, we use the "age ()" method


Indeed, Python has a mechanism called “name mangling” which makes that
any class member starting with two underscores, that is to say of the form
__name will be prefixed by the name of the class that is : className__name.

4.3 Inheritance

Consider In the following example, the listing file (presented like this for ease
of reading) must be split into several files as shown: person.py student.py
employeee.py testPerson.py.
Consider the inheritance scheme as follows:

Person class is the parent class


Employee and Student inherit from Person class

Example 53. The program testPerson.py, uses theses classes. Since each
class is defined alone in a file, we import all theses files . So the first
statements are the import. Here is the code of the programs.

Listing 4.2: testing the person Class


1 from pers import Person
2 from stud import Student
3 from employ import Employee
4
5 a1=("Azzi Malek",’25/01/1997’, ’Said’,’Amizour’)
6 a2=("Argoub Amar",’13/06/1989’, ’Mohamed’,’SidiBelabes’)
7 et1=Student(’1’,’automatic’,10.8, *a1)
8 print("\n\tInfo about Student :\n ")
9 et1.Display()
10 b3=(’Office manager’, "Geophysic", 65_000.0)
11 emp1=Employee (*b3,*a2)
12 print("\n\tInfo about Employee :\n ")
13 emp1.Display()
14 emp1.Marry()
15

AnalyseNum A.Belahcene December 13, 2021


4.3. Inheritance Page 58

16 print("\n Before ending \n")


17 p1=Person(*a2)
18 p1.Display()
19 #print("\nObject Employee One Information: \n ")
20 #print (emp1.__dict__)

Listing 4.3: Person Class


1 class Person:
2 country=’Algeria’
3 def __init__(sf, name , born, father, adr ):
4 sf.Name=name ; sf.Born=born
5 sf.Father=father ; sf.Address=adr
6 def Display(sf):
7 who="Hello, I am {}, my Father is {} born on {}"
8 where="\tI live in {} Town , in {} "
9 print(who.format(sf.Name.upper(),sf.Father,sf.Born))
10 print(where.format(sf.Address, sf.country))
11 if __name__==’__main__’:
12 Iam=Person(’AAAAAIbrahim Bousbaa’, ’1977’, ’Abdelkader’, ’Ouargla’)
13 son=Person(’AAAAAYanis Bousbaa’, ’2001’, ’Ibrahim’, ’Ouargla’)
14 Iam.Display() ; son.Display()

Listing 4.4: Employee Class


1 from pers import Person
2 Empl=’’’my monthly Salary is about {} DA, in my company I hold
3 the position {} in department {} ’’’
4 class Employee(Person):
5 marriageBonus = 50_000
6 def __init__(sf, fonc, dept, sal , *Id):
7 super().__init__(*Id)
8 sf.Job = fonc ; sf.Dpt = dept
9 sf.Salary = sal
10 def Display(sf):
11 super().Display()
12 print(Empl.format(sf.Salary,sf.Job, sf.Dpt))
13 def Marry(sf):
14 mar="{} got married and got the marriage bonus of {}"
15 print(mar.format(sf.Name, Employee.marriageBonus) )
16
17 if __name__==’__main__’:
18 print(" salam Houna employee")

Listing 4.5: Student Class


1 from pers import Person
2
3 Info = ’’’I am in year {}, my speciality is {}, my best grade is {}’’’
4 class Student (Person):

AnalyseNum A.Belahcene December 13, 2021


4.4. Packaging Page 59

5 def __init__(sf, year, spec, grade, *Id):


6 super().__init__(*Id)
7 sf.Year = year ; sf.Spec = spec
8 sf.Average = grade
9
10 def Display (sf):
11 super().Display()
12 print(Info.format(sf.Year, sf.Spec,sf.Average))
13 if __name__==’__main__’:
14 ident=[’Yanis Bousbaa’, ’2001’, ’Ibrahim’, ’Ouargla’]
15 stud1= Student(’1’, ’Automatic’, 14.25, *ident)
16 stud1.Display()
17 print("\n\n SALAM \n\n")

To execute the programs, we use : python3 testPers.py, which in turn uses


the different classes. The keyword super(), is a reference to the parent class,
that is super().__init__(*Id) calls the __init__ method of Person Class.
This means, when we create an Employee objet (or a Student), we create the
identifier Person ( information about the Person: the name, address, ...).

In the same way, when we call the Display method for the Employee (or Stu-
dent), we call the Display method of the Person. So the printing information
( name, address, ...) concerning the Employee or Student are not duplicated
in theses classes, it is written just once in the Person Class.
The statement if __name__==’__main__’: used in pers.py (we can use it in
other files), is to prevent the execution of the following statements if the file
is used as a module.
in other words, if we run the program like : python3 pers.py, the __name__
variable will contain __main__, then the commands Iam=Person(.....), son=Person(.....)
are executed, otherwise, they will be skipped.

Exercise 54. Modify the programs, using other data, run each file alone

4.4 Packaging

Think a package just as a python program in a file or several programs in


folders and sub-folders. Let’s start with :

AnalyseNum A.Belahcene December 13, 2021


4.4. Packaging Page 60

4.4.1 A simple example

Listing 4.6: use module


1 # importing module calc.py
2 import calc as cc
3 #import math as mm
4 from math import *
5
6 ##from calc import *
7 x = cc.add(12,25)
8 y = cc.prod(11,3)
9
10 print(f’Sum is {x} and Product is {y}’)
11
12 print(’Sum is {} and Product is {}’.format(x,y))
13 a=sin(1.2)
14
15 print(f’sin of {a}’)
16 ’’’
17 include <stdio.h>
18
19 float tata(float, float); declaration
20 double sin(double);
21
22 #include <math.h>
23
24 float tata(float a, float b){
25
26 return a*b+2*a;
27 }
28 ’’’

Listing 4.7: create module


1 # A simple module, calc.py
2
3 def add(x, y):
4 return (x+y)
5
6 def prod(x, y):
7 return (x*y)
8
9 # use module
10
11 x=add(2,5)
12 y=prod(23,3)
13 print(f’ sum {x} prod ; {y}’)

AnalyseNum A.Belahcene December 13, 2021


4.4. Packaging Page 61

4.4.2 A more complete Package

When importing the package, Python searches thru the stp3andard directo-
ries and subdirectories declared on the path : sys.path.
The __init__.py file is required to make Python treat directories containing
the files as packages. This prevents directories with a common name, such as
string, unintentionally hiding valid modules that occur later on the module
search path.
In the simplest case, __init__.py can just be an empty file, but it can also exe-
cute initialization code for the package or set the __all__ variable, described
later.

Importing * From a Package

Now what happens when the user writes from sound.effects import *? Ide-
ally, one would hope that this somehow goes out to the filesystem, finds
which submodules are present in the package, and imports them all. This
could take a long time and importing sub-modules might have unwanted
side-effects that should only happen when the sub-module is explicitly im-
ported.
The only solution is for the package author to provide an explicit index of
the package. The import statement uses the following convention: if a pack-
age’s __init__.py code defines a list named __all__, it is taken to be the list
of module names that should be imported when from package import * is
encountered. It is up to the package author to keep this list up-to-date when
a new version of the package is released. Package authors may also decide
not to support it, if they don’t see a use for importing * from their package.

Example 55. Let’s see all this in an example. Consider the files of classes :
Person, Employee, and Student

LAB3
AnalyseNum A.Belahcene December 13, 2021
4.4. Packaging Page 62

Create a class, named «polygon» which is a base class for Square. A square
is a regular polygon with 4 edges.
The polygon has number of edges, and length of edge. The Polygon displays
the position of its nodes.
Consider a polygon with N nodes, where length of side is L. We calculate the
internal angle of the polygon with int_Angle= 180 (N-2)/ N.
We want to draw the polygon centered at position (0,0), so we shift left the
starting point by on x-axis with L/2 and down shift by L/(2 tan(π/N ))
Create a file for polygon class, a file for Square class and a file main to check
the classes.
The entered values must be checked for validity, with following conditions :
3 ≤ N ≤ 10 and 50 ≤ L ≤ 250. Consider the try/except block to check the
entered values.
The polygon has a drawing method using the turtle package, see the section
2.9 on page 40. The polygon has method to calculate the perimeter.
Square has its proper methods to calculate the area and perimeter. The rect-
angle has another method to draw the rectangle in terminal a matrix of a
given character.
We consider a character on terminal as 16x16 pixels image, so divide the
length L by 16 to get the number of rows to print on terminal.
Here is a demonstration;

python3 Lab3.py

Draw a regular Polygon


Number of nodes and step 8, 120
Perimeter : 960
List of Nodes [(-60, -144), (60, -144), (144, -59), (144, 60),
(60, 145), (-59, 145), (-144, 60), (-144, -59)]

Another Test (for a special polygon: Square):

python3 Lab3.py

Draw a regular Polygon


Number of nodes and step 4, 120
Perimeter : 480
List of Nodes

AnalyseNum A.Belahcene December 13, 2021


4.5. Special Methods Page 63

[(-60, -60), (60, -60), (60, 60), (-59, 60)]


Display the square :
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
just enter to end the program:

Figure 4.4.1: Polygon ( octogon ) Example with turtle

4.5 Special Methods

4.5.1 isinstance

The isinstance () function allows you to test the type of an instance, that is
to say the type of an object, that is to say, allows you to know whether an
object belongs to a certain class or not.

AnalyseNum A.Belahcene December 13, 2021


4.5. Special Methods Page 64

4.5.2 issubclass

The issubclass () function is used to test the inheritance of a class, that is to


say, to know if a class inherits from another class or not.
We have seen the «__init__» method, there are still other methods that can
be used, declared implicitly in the language.

4.5.3 __doc__

Displays the information inserted in the class.


If we document the class as follows ,
Example 56. Consider our Student class, since it is documented like this:

class Student:

”’The Student class has 2 attributes ........ ”’

s1.__ doc__

----> prints exactly the comment inserted in the class, that is: The Student
class has 2 attributes .......

4.5.4 __dict__
This method gives information about an object or a class. In our case (
Student class ),

s1 .__ dict__ --->gives:

{’name’: ’Bouras malik’, ’age’: 23}

Student .__ dict__: ---> gives

{ ’__module__’: ’__main__’, ’Number’: 2, ’__init__’: <function


Student .__ init__ at 0x7f3672939e50>, ’__dict__’: <attribute
’__dict__’ of ’Student’ objects>, ’__weakref__’: <attribute
’__weakref__’ of ’Student’ objects>, ’__doc__’: None
}

AnalyseNum A.Belahcene December 13, 2021


4.5. Special Methods Page 65

4.5.5 __add__, __mul__, __str__ ...

Using __add__, like __mul__ and other built-in method.


The __add__ method overloads the “+” operator, will be called when the +
is used on an object. in the same way The method __mul__ overloads the
operator "*", will be called when one uses the * on an object.
The __str__ method specifies the use of a character string by the print of the
object.
Example 48. Using __mul__ in Rational

4.5.6 __help__

help (Rational) gives information about the Rational class


Help on class Rational in module __main__:

class Rational (builtins.object) # inherits from builtins.objet


Rational (n, d)
Methods defined here:

__init __ (self, n, d)

Initialize self. See help (type (self)) for accurate signature.

__mul __ (self, a)

poster (self)

AnalyseNum A.Belahcene December 13, 2021


Chapter 5

GUI: Tkinter

5.1 Presentation

Figure 5.1.1: Tkinter commands

An example of using OOP is the Tkinter GUI. Let’s analyze this simple little
example. We will come back with more details on the different objects, here
we give an idea on the tkinter module.
Example 57. Creating a basic window with text

import tkinter as tk
myFen = tk.Tk ()
message = tk.Label (myFen, text = "Salam Alaykoum!")
message.pack ()
myFen.mainloop ()

66
5.2. Widgets Page 67

Explanation

• import the tkinter package, we can also import ttk (set for tk themes) which
is newer and allows more themes.
• Creation of the Base Window object myWin = tk.Tk ()
• Add a Label object (containing text) to the base window myWin
• Place the Label object by default in the window, the options allow you to
choose the position, top, bottom, ... with the pack placement method.
• Two other placement methods exist: place and grid. In the following we
will use grid which seems simpler and more precise to use.
• Keep the Displayed Window with the mainloop loop.

5.2 Widgets

Any "widget" must be attached to the base "window" which will contain ev-
erything else.
The graphical interface is the application par excellence that uses the OOP.
We are going to write our interface using the object oriented principle.
For all our programs we import tkinter like this: import tkinter as tk

5.2.1 window
A window is a rectangle to be drawn on screen with an N-E position and a
dimension.

myWin = tk.Tk ()

"myWin" is a standard window type object created by the Tk constructor.


We customize it by changing the parameters, by calling the corresponding
methods:

title Window title

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 68

geometry dimensions LxH + X + Y, where L is width, H is height, and X and


Y are horizontal and vertical positions

resizable False or True accepts or not the resizing according to x or y

minsize,maxsize give the minimum and maximum sizes allowed

topmost indicates that the window will be above other windows on the
screen. you can also specify with lift and lower to move it forward
and back in the list of windows.

iconbitmap indicates window icon image


Example 58. User cannot change window height, width can be changed
within limits imposed by minsize and maxsize. The initial size is 600 x 400,
positioned at 400,200 pixels from the top left corner of the screen. The
window is in the foreground (above all the other windows on the screen).
Finally, the mainloop () method is used to display and keep the window on
screen.

Listing 5.1: Basic Window (parent for all)


1 import tkinter as tk
2
3 myWin = tk.Tk()
4 myWin.title(’Tkinter Demonstration Program’)
5 myWin.geometry(’600x400+600+200’)
6 myWin.resizable(True, False)
7 myWin.minsize(300,300)
8 myWin.maxsize(800,600)
9 myWin.attributes(’-topmost’, 1)
10 myWin.mainloop()

Remark 59. Until then, the program guides the user, now we are going to do
programming by event, that is to say the program remains listening to the
events of the user, and responds to the keyboard key or. of the mouse.

We can also use a recent addition to tkinter which supports ttk themes
In our case, the mainloop function listens to the keyboard and the mouse,
and responds to these events.
For example, clicking on a button triggers the execution of a code.

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 69

5.2.2 Label

A label is a text added in its container, ie the window which contains it. We
specify the container, the parent class, (which contains this Label), here fen.
This is valid for all widgets: button, menu, etc ...
The format for creating a widget is to specify the options as a dictionary in
addition to the parent class:
etiq = tk.Label (fen, background = ’yellow’, font = ("Helvetica", 16))
The options are given as a dictionary, for example background = ’yellow’,
font = ("Helvetica", 16).
The most common options

anchor When the text is smaller than the box, it is placed in the center, on
the left (W: West) or on the right (E: East) with tk.W, tk.E or tk.CENTER

text specifies the text to display

textvariable the text can be modified with the variable of type StringVar

width specifies the size (in characters) of the string to display

background Background color for either a name or a code. in short bg

forekground Pencil color of either a name or a code. in short fg

borderwidth Add border

font Choose the type and size of the font

wraplength sets the length (in pixels) of the text before carriage returns.

padding add space around text

image allows you to insert an image

tk.PhotoImage creates an image to insert

Appearances can be changed by using the config command, for example

etiq.config (background = ’blue’)

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 70

changes the background color of the label object to blue. Which means the
presentation can be changed dynamically. For example retrieve the name of
the color from an entry.
Example 60. We complete our window by adding a Label, we obtain the
listing 5.2. Here we did not specify the size of the window, it will be
determined by the size of the objects it contains.

Listing 5.2: Label Example


1 import tkinter as tk
2 from tkinter import ttk
3 myWin = tk.Tk()
4 myWin.title(’Using Label Demonstration’)
5 photo = tk.PhotoImage(file=’bugs2.gif’)
6 Lab1= ttk.Label(myWin, text=’Font: Helvetica 14’, anchor=tk.E,
7 width=30, wraplength=150, font=("Helvetica", 14),
8 background=’blue’, foreground=’#FFAA00’)
9 Lab2= ttk.Label(myWin, image=photo)
10
11 Lab3= tk.Button(myWin, text=’Exit’, font=("Helvetica", 16),
12 background=’red’, command=myWin.quit)
13 Lab1.grid(row=1, column=1, padx=10, pady=10, columnspan=2)
14 Lab2.grid(row=2, column=1)
15 Lab3.grid(row=2, column=2)
16
17 myWin.mainloop()

The pack method allows you to specify the location of the message object in
the fen object. Here we add internal and external spaces in x and y (ipadx,
...,) to the text.
We obtain the Figure 5.2.1 on the following page

Question 61. What is the size of the program window 5.2.1 on the next page

5.2.3 Button
The appearance properties (background, font, padx, ....) of Button are
practically the same as for Label, the essential thing to consider is the
command to execute when clicking on the button object. As the following
instruction indicates:

btn = tk.Button (myWin, text = ’In Blue’, background = ’blue’, command = colorB)

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 71

Figure 5.2.1: Labeling with image

// The btn object is placed in the “myWin” window type object with a blue
background. When you click on the btn object, the colorB function is
executed. See the example of listing 5.3.

Listing 5.3: Button Example


1 import tkinter as tk
2
3 def modColor( col ):
4 myWin.config(background=col)
5
6 myWin = tk.Tk()
7 myWin.title(’Using Buttons’)
8 myWin.geometry(’300x120’)
9
10 btn1 = tk.Button(myWin, text=’Choose Blue’, background=’cyan’,
11 font=("Helvetica", 14), command=lambda: modColor(’blue’) )
12 btn2 = tk.Button(myWin, text=’Choose Green’, background=’green’,
13 font=("Helvetica", 14),command=lambda : modColor(’green’)
)
14 btn3 = tk.Button(myWin, text=’Exit\nQuit’, font=("Helvetica", 16),
15 background=’red’, command=myWin.quit)
16
17 btn1.grid(row=1, column=1)
18 btn2.grid(row=2, column=1)
19 btn3.grid(row=1, column=2, rowspan=2,sticky=’NS’)
20
21 myWin.mainloop()

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 72

5.2.4 Grid
The grid is simply a grid or matrix, in which the positions are indicated by
the row number and column number, for example:

hlp.grid (row = 2, column = 3, sticky = tk.E)


resSum.grid (row = 3, column = 2, sticky = tk.E + tk.W)
hlpBtn.grid (row = 4, column = 1, columnspan = 2)

The help object is placed in row 2, column 3 frame on the right (sticky = tk.E).
The resSum object is placed in row 3 and column 2 by taking the entire width
of the box with sticky (tk.E + tk.W, East-West) , i.e from left to right.
The hlpBtn object is placed from column 1, on 2 columns (columnspan = 2)
We can also do a placement on several rows with rowspan

5.2.5 Frame
A frame is a frame or container that can group other widgets. It is thus
possible to create groups of objects in the same window and each group in a
frame. For a complete example see Listing 5.4.

Listing 5.4: Frame Example


1 import tkinter as tk
2 from math import *
3 theText=’’’The Entry must be a valid
4 mathematical expression,
5 for example :
6 sin(2.5)+ cos(pi)**2+ cosh(2.5).
7 ’’’
8
9
10 class myFrame():
11 ’’’ We create 2 Frames : one for Input/Output
12 widgets and
13 The second for the Buttons
14 ’’’
15 def __init__(self,master):
16 self.frameInput = tk.Frame(master, background=’cyan’)
17 self.frameInput.grid(row=1, column=1)
18 self.frameBtn = tk.Frame(master ,background=’yellow’)
19 self.frameBtn.grid(row=1, column=2)
20

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 73

21
22 self.exp1 = tk.Entry(self.frameInput)
23 self.etiq1 = tk.Label(self.frameInput, text="Exp1 :")
24 self.exp2 = tk.Entry(self.frameInput)
25 self.etiq2 = tk.Label(self.frameInput, text="Expression 2 :")
26 self.res = tk.Label(self.frameInput, text=’Here the Result’)
27
28 self.etiq1.grid(row =1,column=1)
29 self.exp1.grid (row =1,column=2)
30 self.etiq2.grid(row =2,column=1)
31 self.exp2.grid (row =2,column=2)
32 self.res.grid(row =3, column =1)
33
34 self.som = tk.Button(self.frameBtn,text=’Sum’,
35 command=self.Sum)
36 self.prod = tk.Button(self.frameBtn,text=’Product’,
37 command=self.Product)
38 self.quit = tk.Button(self.frameBtn, text=’Exit’,
39 command=myWin.quit)
40 self.som.grid(row =1, column =1)
41 self.prod.grid(row =2, column =1)
42 self.quit.grid(row =3, column =1)
43
44 def Sum(self):
45 try:
46 rr=eval(self.exp1.get()) + eval(self.exp2.get())
47 except:
48 self.res.config(text=theText, foreground=’red’)
49 else:
50 ss="Result: "+rr.__format__(’.3f’)
51 self.res.config(text = ss , foreground=’blue’)
52 def Product(self):
53 try:
54 rr=eval(self.exp1.get()) * eval(self.exp2.get())
55 except:
56 self.res.config(text=theText, foreground=’red’)
57 else:
58 ss="resultat: "+ rr.__format__(’.3f’)
59 self.res.config(text = ss , foreground=’blue’)
60
61 if __name__==’__main__’:
62 myWin=tk.Tk()
63 myWin.title(’Frame and Entry Example’)
64 app=myFrame(myWin)
65 myWin.mainloop()

myWin= tk.Tk ()
frame = tk.Frame (myWin, background = ’blue’)
frame.grid (row = 1, column = 1)

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 74

exp1 = tk.Entry (frame)


exp1.grid (row = 1, column = 1)

The Frame "frame1" is inside myWin Window, and contains the entry "ent1"
placed as indicated, with grid widget.

5.2.6 Entry

The Entry widget allows the user to enter data, somewhat the opposite of
Label which allows text to be displayed. In this example from listing 5.4 on
page 72 we discuss the grid placement method.

5.2.7 Menu
Listing 5.5: barMenu Example

1 importtkinter as tk
2 classmyMenu():
3 def__init__(self, master):
4 self.master=master
5 menubar=tk.Menu(master)
6 master.config(menu=menubar)
7 file_menu=tk.Menu(menubar)
8 edit_menu=tk.Menu(menubar)
9
10 #menubar.grid(row=1,column=1)
11 #addamenuitemto themenu
12 file_menu.add_command(label=’Ouvrir’,command=self.ouvrir )
13 file_menu.add_command(label=’Exit’,command=master.destroy )
14 file_menu.add_command(label=’Quitter’,command=self.quitter )
15

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 75

16 edit_menu.add_command(label=’Copier’,command=self.copier)
17
18 #addthe Filemenuto themenubar
19 menubar.add_cascade(label="Fichier",menu=file_menu)
20 menubar.add_cascade(label="Edition",menu=edit_menu)
21 defcopier(self):
22 print(" Copier le Texte ")
23 defouvrir(self):
24 print(" Ouverturedefichier ")
25 def quitter(self):
26 print(" Destructionde la Fenetre ")
27 self.master.destroy()
28
29 if __name__==’__main__’:
30 fen=tk.Tk()
31 fen.title(’ExempledeFrameet Entry’)
32 fen.geometry("400x300")
33 app=myMenu(fen)
34 fen.mainloop()

5.2.8 Canvas

Listing 5.6: Drawing in canvas


1 import tkinter as tk
2
3
4 points = []
5
6 def f(x,y,p,t):
7 for i in (1,-1):
8 points.extend((x, y + i*p))

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 76

9 points.extend((x + i*t, y + i*t))


10 points.extend((x + i*p, y))
11 points.extend((x + i*t, y - i * t))
12
13 p,t=70,25
14 x,y=100,100
15 f(x,y,p,t)
16 print(" Points: ", points)
17
18 coul1 = "#476042" ## vert
19 coul2=’yellow’
20
21 fen = tk.Tk()
22
23
24
25 w = tk.Canvas(fen, width=300, height=300)
26 w.grid(row=1, column=1)
27
28 w.create_rectangle(50, 20, 150, 80, fill="#476042")
29 w.create_rectangle(65, 35, 135, 65, fill="blue")
30 #w.create_line(0, 0, 50, 20, fill="#476042", width=3)
31 """
32 w.create_line(0, 100, 50, 80, fill="#476042", width=3)
33 w.create_line(150,20, 200, 0, fill="#476042", width=3)
34 w.create_line(150, 80, 200, 100, fill="#476042", width=3)
35 """
36 #points = [50,90, 110, 110, 170,150, 120, 165, 100, 250,60,120]
37 #points= [100, 170, 125, 125, 170, 100, 125, 75, 100, 30, 75, 75, 30, 100, 75, 125]
38 w.create_polygon(points, outline=’red’, fill=’gold’, width=3)
39
40
41 fen.mainloop()
42
43 """
44
45 canvas_width = 400
46 canvas_height =400
47 print(points)
48
49 canvas.create_polygon(points, outline=outline,
50 fill=fill, width=width)
51
52 master = Tk()
53
54 w = Canvas(master,
55 width=canvas_width,
56 height=canvas_height)

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 77

57 w.pack()
58
59 p = 50
60 t = 15
61
62 nsteps = 10
63 step_x = int(canvas_width / nsteps)
64 step_y = int(canvas_height / nsteps)
65
66 for i in range(1, nsteps):
67 polygon_star(w,i*step_x,canvas_height - i*step_y,p,t,outline=’red’,fill=’gold’, widt
68
69 mainloop()
70 """

LAB4

The goal of this Lab is to manipulate tkinter widgets : buttons and Canvas.
As is described in the figure 5.2.2. see also the program canva.py

Figure 5.2.2: Using Canvas

The window is constituted by 2 Parts :

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 78

1. Canvas window : Receives the graphs of filled Circles and filled Poly-
gon. Create a class, named «polygon» which is a base Menu window
contains:

2. Buttons and Entries

• Color and list of nodes for the Polygon


• Color and size for the circle (or Ellipse)
• Button to clear the canvas
• Button to exit the program
• Finally the data must be valid (use try/except). The graphs must
be kept inside the canvas.

5.2.9 Other Widgets

Text displays a multi-line text entry field.

Scrollbar Link a scroll bar to a scrolling widget, for example a Text widget.

ScrolledText shows how to create a scrolling text widget consisting of Text


widgets and vertical scroll bar.

Separator use a separator widget to separate fields.

Checkbox shows how to create a checkbox widget.

radioButton uses radio buttons to allow users to select one of many mutu-
ally exclusive choices.

Combobox guides you through the steps of creating a combobox widget.

Listbox shows how to display a list of single-line text items in a Listbox.

PanedWindow shows how to use the PanedWindow to divide the space of


a frame or window.

Slider Learn how to create a slider using the Tkinter Scale widget.

AnalyseNum A.Belahcene December 13, 2021


5.2. Widgets Page 79

Spinbox shows how to use a Spinbox.

Sizegrip guides on how to use the Sizegrip widget to allow users to resize
the entire application window.

LabelFrame shows you how to group related widgets into a group using the
LabelFrame widget.

progressbar shows you how to use the progress bar widget to give user
feedback on the progress of a long-running task.

notebook explains how to use the Notepad widget to create tabs.

Treeview guides you through the steps of creating treeview widgets that
display tabular and hierarchical data.

Frame use the Frame widget to group other widgets.

AnalyseNum A.Belahcene December 13, 2021

You might also like