PP 11 Python1Studenti
PP 11 Python1Studenti
1
Privire generala
In Python exista urmatoarea structurare
Programele sunt compuse din module
Modulele sunt compuse din propozitii
Propozitiile contin expresii
Expresiile creaza si proceseaza obiecte
Exista cayeva cai de a executa programe scrise in
Python.
Unele modeule pot fi executate direct. Acestea se numesc
programe sau scripturi
Altele sunt scrise pentru a fi importate si utilizate de alte
programe. Acestea sunt bibliotecile
Cateodata se doreste crearea uni hibrid care sa poata fi folosit
foe ca un program de sine statator fie ca o biblioteca
sintaxa
Instrucţiuni multi-linie
Exemplu:
total = item1 + \
item2 + \
item3
Exemplu:
ZileLucrat = [‘Luni',‘Marti',‘Miercuri',
‘Joi',‘Vineri']
Punct și virgulă (;) permite declarații multiple pe o singură linie:
3
Cuvinte cheie
And exec not assert finally break or
For pass class from print continue
global raise def if return del
Import try elif in while else
Is with except lambda yield
variabile
Nu sunt declarate ci doar asignate direct
4
Executie conditionata
Cand se doreste ca un program sa porneasca o data ce
este incarcat de interpretor se va adauga la sfarsitul
codului linia main()
Deoarece la import se doreste ca modulul sa nu se
execute in cazul hibrid se va folosi un apel de main()
conditionat.
if <condition>:
main()
Deoarece la importul unui modul Python creaza o
variabila speciala __nume_modul__ pentru a-l referi se
poate face
if __name__ == '__main__':
main()
5
Control executiei
Decizie unica (simpla)
if <condition>:
<body>
Decizie binara/duala
if <condition>:
<statements>
else:
<statements>
6
Decizie multipla
In calculul rad ecuatie gr II
Check the value of discrim
when < 0: handle the case of no roots
when = 0: handle the case of a double root
when > 0: handle the case of two distinct
roots
if <condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
elif <condition3>:
<case3 statements>
…
else:
<default statements>
Similara cu switch-case-default
7
Instructiunea try:
Exceptii try:
<body>
except <ErrorType>:
<handler>
import math
def main():
print("This program finds the real solutions to a quadratic\n")
try:
a, b, c = eval(input("Please enter the coefficients (a, b, c): "))
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print("\nThe solutions are:", root1, root2 )
except ValueError as excObj:
if str(excObj) == "math domain error":
print("No Real Roots")
else:
print("You didn't give me the right number of coefficients.")
except NameError:
print("\nYou didn't enter three numbers.")
except TypeError:
print("\nYour inputs were not all numbers.")
except SyntaxError:
print("\nYour input was not in the correct form. Missing comma?")
except:
print("\nSomething went wrong, sorry!")
8
main()
Bucle definite - For
for <var> in <sequence>:
<body>
Bucla are var pe post de contor.
for i in range(11):
print(i)
Rezultate:
litera curenta : P
litera curenta : y
litera curenta : t
This is pass block
litera curenta : h
litera curenta : o
litera curenta : n
Good bye!
10
Operatori
Ordinea de precedenta este not, and, or deci consider ca
a or not b and c (a or ((not b) and c))
Totusi parantezele raman recomandate
(a >= 15 and a - b >= 2) or (b >= 15 and b - a >= 2)
(a >= 15 or b >= 15) and abs(a - b) >= 2
= atribuire simplă c = a + b
+= operandului din stânga i se adună operandul din dreapta c += a
c = c + a)
-= din operandul stâng se scade operandul drept c -= a
(c = c – a)
*= operandul din stânga se multiplică cu operandul din dreapta c *= a
(c = c * a)
/= împarte operandul din stânga cu cel din dreapta c /= a
(c = c / a)
%= operandului din dreapta i se atribuie restul împărțirii c %= a
(c = c % a)
**= operandului din stânga i se atribuie puterea c **= a
(c = c ** a)
//= împărțireă întreagă este atribuită operandului stâng c //= a
(c = c // a)
12
Operatori pe biți
Operatori pe biți lucrează pe biți şi anume bit -----------------
cu bit a&b = 0000 1100
Dacă a = 60 şi b = 13; reprezentările binare a a|b = 0011 1101
lui a şi b sunt: a^b = 0011 0001
a = 0011 1100 ~a = 1100 0011
b = 0000 1101
14
Tipuri de date:siruri de caractere
Python lucreaza cu Unicode (100,000+ caractere)
The ord intoarce codul numeric al unui caracter
The chr genereaza caracterul asociat codului.
>>> ord("A")65>>> ord("a") 97>>> chr(97) 'a'>>> chr(65) 'A‘
Un sir (de caractere) este definit intre (") sau (').
>>> str1="Hello">>> str2='spam'>>> print(str1, str2)Hello spam
>>> type(str1)<class 'str'>>>> type(str2)<class 'str'>
Citirea unui sir
>>> firstName = input("Please enter your name: ")
Forma generala de indexare <string>[<expr>] (ca in C)
H e l l o B o b
0 1 2 3 4 5 6 7 8
Suporta si indexarea negativa
>>> greet[-1] 'b' >>> greet[-3] 'B'
15
Tipuri de date:siruri de caractere
Extragere subsiruri (slicing)
H e l l o B o b
0 1 2 3 4 5 6 7 8
>>> greet[0:3]'Hel‘ >>> greet[5:9]' Bob'>>> greet[:5]'Hello'
>>> greet[5:]' Bob'>>> greet[:]'Hello Bob‘
Concatenare (+)
Repetitie (*)
Lungimea (nr caractere) len.
>>> "spam" + "eggs"'spameggs'>>> "Spam" + "And"+ "Eggs"'SpamAndEggs'
>>> 3 * "spam"'spamspamspam'>>> "spam" * 5'spamspamspamspamspam'
>>> (3 * "spam") + ("eggs" * 5) 'spamspamspameggseggseggseggseggs‘
>>> len("spam") 4
>>> for ch in "Spam!":
print (ch, end=" ")
16
Tipuri de date:conversii
Toate posibilitatile:
Functie Inteles
float(<expr>) expr valoare reala
17
Afisare obiecte
Ca si in limbaj C
Character Argument Expected
c Sir de lungime 1
s Sir de orice lungime
d Intregi in baza 10
u Intregi fara semn in baza 10
o Intregi in baza 8
x or X Intregi in baza 16 (uppercase for X)
e, E, f, g, G Reale in diverse stiluri
% Procent literal
18
Formatarea afisarii
print "Chapter " + str(x) + \
str(chapters[x]).rjust(15,'.')
print "\nHex String: " + hexStr.upper().ljust(8,'0')
print "Chapter %d %15s" % (x,str(chapters[x]))
#Right justify
print "Hex String: " + hexStr.upper().rjust(8,'0')
for x in chapters:
print "Chapter " + str(x) + \
str(chapters[x]).rjust(15,'.')
#Left justify
print "\nHex String: " + hexStr.upper().ljust(8,'0')
#String format
for x in chapters:
print "Chapter %d %15s" % (x,str(chapters[x]))
19
Executarea de cod din interiorul unui sir
cards = ['Ace', 'King', 'Queen', 'Jack']
codeStr = "for card in cards: \
print \"Card = \" + card"
areaStr = "pi*(radius*radius)"
#Execute string
exec(codeStr)
#Evaluate string
print "\nArea = " + str(eval(areaStr, \
{"pi":3.14}, {"radius":5}))
20
Interpolare variabile in interiorul sirurilor
import string
values = [5, 3, 'blue', 'red']
s = string.Template("Variable v = $v")
for x in values:
print s.substitute(v=x)
21
Unicode la siruri si invers
import string
locStr = "El "
uniStr = u"Ni\u00F1o"
print uniStr.encode('utf-8')
print uniStr.encode('utf-16')
print uniStr.encode('iso-8859-1')
22
Liste >>> x = [1,'hello', (3 + 2j)]
>>> x
[1, 'hello', (3+2j)]
>>> x[2]
(3+2j)
>>> x[0:2]
[1, 'hello']
>>> x = [1,2,3]
>>> y = x
>>> z = x.append(12)
>>> x = [1,2,3] >>> z == None
>>> y = x True
>>> x[1] = 15 >>> y
>>> x [1, 2, 3, 12]
[1, 15, 3] >>> x = x + [9,10]
>>> y >>> x
[1, 15, 3] [1, 2, 3, 12, 9, 10]
>>> x.append(12) >>> y
>>> y [1, 2, 3, 12]
[1, 15, 3, 12] >>>
Operatii pe lista
Operator Inteles
26
Tuple
hexStringChars = ('A', 'B','C', 'D', 'E', 'F')
hexStringNums = ('1', '2', '3', '4', '5', '6',\
'7', '8', '9','0')
hexStrings = ["1FC", "1FG", "222", "Ten"]
tupleList = list(hexStringChars)
listTuple = tuple(hexStrings)
27
Tuple
hexStringChars = ('A', 'B','C', 'D', 'E', 'F')
hexStringNums = ('1', '2', '3', '4', '5', '6',\
'7', '8', '9', '0')
hexStrings = ["1FC", "1FG", "222", "Ten"]
for hexString in hexStrings:
for x in hexString:
if ((not x in hexStringChars) and
(not x in hexStringNums)):
print hexString +\
" is not a hex string."
break
#Tupla catre lista
tupleList = list(hexStringChars)
print tupleList
#Lista catre tupla
listTuple = tuple(hexStrings)
print listTuple
28
Construirea unui dictionar
Se rezuma la asignarea unui grup de valori si
a cheilor lor la o variabila.
Deoarece orice este obiect in Python se pot
construi usor price fel de dictionare de la
cele simple (relatie unu-la-unu (cheie-
valoare)) pana la cele foarte complexe (unul
la mai multi sau mai multi la mai multi).
29
Construirea unui dictionar
numberDict = {1:'one', 2:'two', 3:'three', 4:'four'}
letterDict = {'vowel':['a','e','i','o','u'],\
'consonant':['b','c','d','f']}
numbers = (1,2,3,4,5,6,7,8,9,0)
letters = ('a','b','c','d','e','f')
punct = ('.', '!', '?')
charSetDict = {numbers:[], letters:[], punct:[]}
30
Adaugarea unei valori la Dictionar
numbers = ('1','2','3','4','5','6','7','8','9','0')
letters = ('a','b','c','d','e','f')
punct = ('.', '!', '?')
charSetDict = {numbers:[], letters:[], punct:[]}
cSet = raw_input("Insert characters: ")
for c in cSet:
for x in charSetDict.keys():
if c in x:
charSetDict[x].append(c)
break;
charSetDict["Special"] = ['%', '$', '#']
charSetDict["Special"] = '><'
31
Adaugarea unei valori la Dictionar
numbers = ('1','2','3','4','5','6','7','8','9','0') print x[1]
letters = ('a','b','c','d','e','f') cSet = raw_input("Insert characters: ")
punct = ('.', '!', '?') for c in cSet:
charSetDict = {numbers:[], letters:[], for x in charSetDict.keys():
punct:[]} if c in x:
def display_cset (cset): charSetDict[x].append(c)
print break;
for x in cset.items(): display_cset(charSetDict)
if x[0] == numbers: charSetDict["Special"] = ['%', '$', '#']
print "Numbers:" display_cset(charSetDict)
elif x[0] == letters: charSetDict["Special"] = '><'
print "Letters:" display_cset(charSetDict)
elif x[0] == punct:
print "Puctuation:"
else:
print "Unknown:"
32
Extragerea unei valori din dictionar
validkeys = (1,2,3)
keyGenDict={'keys':[1,2,3],1:'blue',2:'fast',
3:'test','key':2}
print keyGenDict.keys()
print keyGenDict.values()
print keyGenDict.items()
val = keyGenDict["key"]
keyGenDict["key"] = 1
val = keyGenDict["key"]
33
Extragerea unei valori din dictionar
validkeys = (1,2,3) print("Invalid key")
keyGenDict={'keys':[1,2,3],1:' print keyGenDict.keys()
blue', print keyGenDict.keys()
2:'fast', 3:'test','key':2} print keyGenDict.items()
def show_key (key): val = keyGenDict["key"]
if(key in validkeys): show_key(val)
keyVal = keyGenDict["key"] = 1
(keyGenDict["keys"])[key-1] val = keyGenDict["key"]
print "Key = " + show_key(val
keyGenDict[keyVal]
else:
34
Fisiere
Sunt gestionate ca in C
Se asociaza un obiect cu un fisier
open(path [,mode [,buffersize]])
<file>.read() –
<file>.readline() –
<file>.readlines() –
35
Fisiere
Atributele unui obiect fisier:
Dupa ce s-a deschis un fisier se obtine o referinta
(obiect fisier) care are mai multe atribute.
Atribut
file.closed
file.mode
file.name
file.softspace
36
Fisiere close()
Sintaxa:
fileObject.close();
Exemplu:
fo = open(“f1.txt”, “wb”)
print (“numele fisierului: “, fo.name
fo.close()
Rezultate:
numele fisiereului: f1.txt
37
Fisiere
Metoda write() :
Sintaxa:
fileObject.write(string);
string contine ceea ce se scrie;
Exemplu:
fo = open("f2.txt", "wb")
fo.write ("Python is a great language.\nYeah
its great!!\n")
fo.close()
38
Fisiere read()
Sintaxa str=fileObject.read([count]);
Exemplu:
fo = open("f2.txt", "r")
str = fo.read(10);
print (“Sirul este citit: ", str)
fo.close()
fo = open("f2.txt", "r")
str = fo.read();
print (“Sirul este citit:\n", str)
fo.close()
39
Fisiere
fo = open("f2.txt", "r+")
str = fo.read(5);
print (“Sirul citit este: ", str)
pos = fo.tell()
print (“Pozitia curenta:", pos)
pos = fo.seek(0, 0);
str = fo.read(11);
print (“din nou citire:”, str)
fo.close()
40
Fisiere
Metoda rename():
Syntaxa:
os.rename(current_file_name, new_file_name)
Exemplu:
import os
os.rename( "test1.txt", "test2.txt" )
Metoda delete()
Sintaxa:
os.delete(file_name)
Exemplu:
Stergem fisierul f2.txt
import os
os.delete(“f2.txt")
41
Fisiere Gestionarea Directoarelor in Python
Metoda mkdir()
Sintaxa:
os.mkdir("newdir")
Exemplu:
import os
# Create a directory "test"
os.mkdir("test")
Metoda chdir()
Syntax:
os.chdir("newdir")
Exemplu:
import os
os.chdir("/home/newdir")
42
Metoda getcwd()
Sintaxa:
os.getcwd()
Exemplu:
import os
os.getcwd()
Metoda rmdir()
Sintaxa
os.rmdir('dirname')
Exemplu:
import os
os.rmdir( "/tmp/test" )
43
Fisiere Metode asociate fisierelor
1.file.close() .
2.file.flush()
3.file.fileno()
4.file.isatty()
5.file.next()
6.file.read([size])
7.file.readline([size])
8.file.readlines([sizehint])
9.file.seek(offset[, whence])
10.file.tell()
11.file.truncate([size])
12.file.write(str)
13.file.writelines(sequence)
44
Fisiere
inPath = "input.txt"
outPath = "output.txt"
file = open(outPath, 'wb')
file = open(inPath, 'rU') if file:
if file: # scrie in fisier
# incepe citirea file.close()
file.close() else:
else: print "Error Opening
print "Error Opening File."
File."
45
Citire cu buffer
filePath = "input.txt" for line in inList:
buffer += line
print buffer
buffer = "Read buffer:\n"
buffer += open(filePath,
'rU').read() buffer = "Read buffer:\n"
print buffer file = open(filePath, 'rU')
while(1):
bytes = file.read(5)
buffer = "Readline buffer:\n" if bytes:
inList = open(filePath, buffer += bytes
'rU').readlines() else:
print inList break
print buffer
46
Citeste o linie
import linecache sau
filePath = "input.txt" infile = open(someFile, "r")
for i in range(5):
print linecache.getline(filePath, 1) line = infile.readline()
print linecache.getline(filePath, 3) print line[:-1]
linecache.clearcache()
Citeste un cuvant
filePath = "input.txt" for word in line.split():
wordList = [] wordList.append(word)
wordCount = 0 wordCount += 1
print wordList
print "Total words = %d" %
file = open(filePath, 'rU') wordCount
for line in file:
47
Scriere in fisier
wordList = ["Red", "Blue", "Green"]
filePath = "output.txt"
file.write("\n\nFormatted text:\n")
file.close()
48
OOP in Python
#include <stdio.h>
2 #include <time.h>
3 class now Si echivalentul in Python
4 {
5 public:
6 time_t t; 1
7
8
int year;
int month;
2 import time
9 int day; 3 class now:
10 4 def __init__(self):
11 int hour;
12 int minute; 5 self.t = time.time()
13 int second; 6 self.year, \
14 int dow; 7 self.month, \
15 int doy;
8 self.day, \
17
18
now()
{
9 self.hour, \
19 time(&t); 10 self.minute, \
20 struct tm * ttime; 11 self.second, \
21 ttime = localtime(&t);
22 year = 1900 + ttime->tm_year; 12 self.dow, \
23 month = ttime->tm_mon; 13 self.doy, \
24 day = ttime->tm_mday; 14 self.dst = time.localtime(self.t)
25 hour = ttime->tm_hour;
26 minute = ttime->tm_min; 15
27
28
second = ttime->tm_sec;
dow = ttime->tm_wday;
16 n = now()
29 doy = ttime->tm_yday; 17 print ''The year is", n.year
30 }
31 };
33 main ( int argc, char ** argv )
34 {
35 now n ;
36 fprintf ( stdout, ''The year is %d\n", n.year ) ;
37 } 49
OOP
In C++, avem terminator de instructiune “; “ nu si in Python.
In C++, marcajul de bloc este cu {} in Python, prin indentare.
In C++, clasa are un membru ascuns numit "this", care este
vizibil pentru orice metoda din clasa daca este nevoie. In
Python, echivalentul este "self", iar folosirea lui este
obligatorie .
In C++ (si in C), trebuie adaugat 1900 la anul intors de
localtime() ; In Python este rezolvata problema.
In C++, metoda apelata atunci cand se creaza o instanta a
clasei now poarta numele clasei: now(). Cand o clasa este
instantiata in Python, acesta cauta o metoda numita __init__()
si o apeleaza
Pentru copierea unui obiect se foloseste metoda clone()
50
OOP in Python - structurarea datelor
class Person:
def _ _init_ _(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
53
OOP in Python – adugare mostenire
>>> from person import Person
>>> from manager import Manager
>>> bob = Person(name='Bob Smith', age=42, pay=10000)
>>> sue = Person(name='Sue Jones', age=45, pay=20000)
>>> tom = Manager(name='Tom Doe', age=55, pay=30000)
>>> db = [bob, sue, tom]
>>> for obj in db:
obj.giveRaise(.10)
>>> for obj in db:
print obj.lastName( ), '=>', obj.pay
Smith => 11000.0
Jones => 22000.0
Doe => 36000.0
54
OOP in Python – adaugare persistenta
import shelve
from person import Person
from manager import Manager
db = shelve.open('class-shelve')
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
db.close( )
55
OOP in Python – adaugare persistenta
import shelve import shelve
db = shelve.open('class- db = shelve.open('class-
shelve') shelve')
for key in db: sue = db['sue']
print key, '=>\n ', sue.giveRaise(.25)
db[key].name, db[key].pay db['sue'] = sue
bob = db['bob'] tom = db['tom']
print bob.lastName( ) tom.giveRaise(.20)
print db['tom'].lastName( ) db['tom'] = tom
db.close( )
56
Exemplu 2
Fie un fisier cu datele studentilor care contine: nume,
orelele studiate si punctele obtinute la evaluare
Adams, Henry 127 228
Comptewell, Susan 100 400
DibbleBit, Denny 18 41.5
Jones, Jim 48.5 155
Smith, Frank 37 125.33
Trebuie scrisa o aplicatie care calculeaza GPA
Se va crea clasa Student
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
Deci pentru a crea o inregistrare student
aStudent = Student(“Adams, Henry”, 127, 228)
57
Exemplu clase
Crearea metodelor de acces variabile
def getName(self): def getQPoints(self):
return self.name return self.qpoints
def getHours(self): def gpa(self):
return self.hours return
self.qpoints/self.hours
Mai trebuie algoritm pentru gasirea celui mai bun student
# gpa.py def makeStudent(infoStr):
# cautare student cu media cea mai mare - GPA name, hours, qpoints = infoStr.split("\t")
return Student(name, hours, qpoints)
class Student:
def main():
def __init__(self, name, hours, qpoints):
filename = input("Enter name the grade file: ")
self.name = name
infile = open(filename, 'r')
self.hours = float(hours)
best = makeStudent(infile.readline())
self.qpoints = float(qpoints)
for line in infile:
def getName(self): s = makeStudent(line)
return self.name if s.gpa() > best.gpa():
best = s
def getHours(self): infile.close()
return self.hours print("The best student is:", best.getName())
def getQPoints(self): print ("hours:", best.getHours())
return self.qpoints print("GPA:", best.gpa())
59
Codul/modulul pt buton
# button.py return (self.active and
from graphics import * self.xmin <= p.getX() <= self.xmax
class Button: and
def __init__(self, win, center, width, height, label): self.ymin <= p.getY() <= self.ymax)
w,h = width/2.0, height/2.0 def getLabel(self):
x,y = center.getX(), center.getY() “intoarce eticheta buton."
self.xmax, self.xmin = x+w, x-w return self.label.getText()
self.ymax, self.ymin = y+h, y-h def activate(self):
p1 = Point(self.xmin, self.ymin) "Seteaza buton ca 'active'."
p2 = Point(self.xmax, self.ymax) self.label.setFill('black')
self.rect = Rectangle(p1,p2) self.rect.setWidth(2)
self.rect.setFill('lightgray') self.active = True
self.rect.draw(win)
def deactivate(self):
self.label = Text(center, label)
“seteaza buton ca 'inactive'."
self.label.draw(win)
self.label.setFill('darkgrey')
self.deactivate()
self.rect.setWidth(1)
def clicked(self, p):
self.active = False
60
Interfata
def __init__(self):
win = GraphWin("calculator")
win.setCoords(0,0,6,7)
win.setBackground("slategray")
self.win = win
self.buttons.append(Button(self.win,Point(cx,cy),.75,.75,label))
self.buttons.append(Button(self.win,Point(4.5,1),1.75,.75, "="))
for b in self.buttons:
b.activate()
61
Interfata
Bucla va initializa
cx,cy,label)=<urmatorul element din bSpecs> incepand cu
cx,cy,label = 2,1,”0”
Construirea zonei de afisare
bg = Rectangle(Point(.5,5.5), Point(5.5,6.5))
bg.setFill('white')
bg.draw(self.win)
text = Text(Point(3,6), "")
text.draw(self.win)
text.setFace("courier")
text.setStyle("bold")
text.setSize(16)
self.display = text
Tratarea evenimentelor de la taste pentru butoane
def run(self):
while True:
key = self.getButton()
self.processButton(key)
62
Interfata - Tratarea evenimentelor de la mouse
def getButton(self):
while True:
p = self.win.getMouse()
for b in self.buttons:
if b.clicked(p):
return b.getLabel() # sfarsit
metoda
Cum se apasa un buton - i se returneaza eticheta asociata si procesul se reia
Trebuie facut refresh la display
self.display.setText(text+key)
Tasta C de clear:
self.display.setText("")
Tasta backspace :
self.display.setText(text[:-1])
Tasta egal forteaza evaluarea expresiei introduse pana in momentul respectiv
try:
result = eval(text)
except:
result = 'ERROR'
self.display.setText(str(result))
Se observa tratarea erorii pentru evitarea opririi programului
63
Codul Calculator
from graphics import * self.buttons.append(Button(self.win,Point(c
from button import Button x,cy),.75,.75,label))
class Calculator: self.buttons.append(Button(self.win,
def __init__(self): Point(4.5,1), 1.75, .75, "="))
win = GraphWin("calculator") for b in self.buttons:
win.setCoords(0,0,6,7) b.activate()
win.setBackground("slategray") def __createDisplay(self):
self.win = win bg = Rectangle(Point(.5,5.5),
Point(5.5,6.5))
self.__createButtons()
bg.setFill('white')
self.__createDisplay()
bg.draw(self.win)
def __createButtons(self):
text = Text(Point(3,6), "")
bSpecs = [(2,1,'0'), (3,1,'.'),
text.draw(self.win)
(1,2,'1'), (2,2,'2'), (3,2,'3'), (4,2,'+'), (5,2,'-'),
text.setFace("courier")
(1,3,'4'), (2,3,'5'), (3,3,'6'), (4,3,'*'), (5,3,'/'),
text.setStyle("bold")
(1,4,'7'), (2,4,'8'), (3,4,'9'), (4,4,'<-'),(5,4,'C')]
text.setSize(16)
self.buttons = []
self.display = text
for (cx,cy,label) in bSpecs:
64
Codul Calculator
def getButton(self): try:
while True: result = eval(text)
p = self.win.getMouse() except:
for b in self.buttons: result = 'ERROR'
if b.clicked(p): self.display.setText(str(result))
return b.getLabel() else:
def processButton(self, key): self.display.setText(text+key)
text = self.display.getText()
def run(self):
if key == 'C':
while True:
self.display.setText("")
key = self.getButton()
elif key == '<-':
self.processButton(key)
# Backspace, stege ultimul
caracter if __name__ == '__main__':
self.display.setText(text[:-1]) theCalc = Calculator()
elif key == '=': theCalc.run()
65
Functii
Definitia:
def <name>(<formal-parameters>):
<body>
Parametrii formali ca si restul variabilelor din
corpul functiei exista doar in cadrul acesteia chiar
daca au acelasi nume cu o variabila externa
Apelul functiei
<name>(<actual-parameters>)
66
Functii care intorc valori
Cateodata o functie trebuie sa intoarca mai mult de o valoare.
def sumDiff(x, y):
sum = x + y
diff = x – y
return sum, diff
Python suporta return multiplu si initializare multipla
num1, num2 = eval(input("Enter two numbers(num1, num2)"))
s, d = sumDiff(num1, num2)
print("The sum is", s, "and the difference is", d)
67
Transfer parametri prin liste/tablouri
def addInterest(balances, rate):
for i in range(len(balances)):
balances[i] = balances[i] * (1+rate)
def test():
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, 0.05)
print(amounts)
test()
68
Cuvinte cheie ca argumente
Argumentele de apel sunt de forma "keyword = value".
De exemplu pentru functia
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
Putem avea un apel de forma
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
Dar nu putem avea un apel de forma
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
69
parrot(actor='John Cleese') # unknown keyword
Cuvinte cheie ca argumente
De exemplu daca definim o functie
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments:
print arg print '-'*40
for kw in keywords.keys(): print kw, ':',
keywords[kw]
Atunci ar putea fi apelata cam asa :
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
70
Grafica simpla
import graphics
win = graphics.GraphWin()
win.close()#distruge fereastra
from graphics import *
win = GraphWin()
71
Grafica simpla
>>> p = Point(50, 60)
>>> p.getX()
50
>>> p.getY()
60
>>> win = GraphWin()
>>> p.draw(win)
>>> p2 = Point(140, 100)
>>> p2.draw(win)
72
Grafica simpla
73
Preluarea pozitiei cursor mouse
from graphics import *
win = GraphWin("Click Me!")
p = win.getMouse()
print("You clicked", p.getX(), p.getY())
Si un program exemplu
from graphics import *
def main():
win = GraphWin("Draw a Triangle")
win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 0.5), "Click on three points")
message.draw(win)
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
74
Gestiunea textului
from graphics import *
def main():
win = GraphWin("Celsius Converter", 300, 200)
win.setCoords(0.0, 0.0, 3.0, 4.0)
Text(Point(1,3), " Celsius Temperature:").draw(win)
Text(Point(1,1), "Fahrenheit Temperature:").draw(win)
input = Entry(Point(2,3), 5)
input.setText("0.0")
input.draw(win)
output = Text(Point(2,1),"")
output.draw(win)
button = Text(Point(1.5,2.0),"Convert It")
button.draw(win)
Rectangle(Point(1,1.5),
Point(2,2.5)).draw(win)
win.getMouse()
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32
output.setText(fahrenheit)
button.setText("Quit")
win.getMouse()
win.close()
75
main()
Crearea threaduri
Se foloseste start_new_thread(function, args [, kwargs])
import thread
import time
def print_time(threadName, delay):
while 1:
time.sleep(delay)
print "%s: %s" % (threadName, \
time.ctime(time.time()))
thread.start_new_thread(print_time, ("Thread01",2,))
thread.start_new_thread(print_time, ("Thread02",4,))
while 1:
pass
class newThread (threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
.....
if doExit:
thread.exit()
76
Crearea si oprirea thread-urilor
import threading
import thread
import time
doExit = 0
class newThread (threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
77
Crearea si oprirea thread-urilor
def print_time(threadName, delay,
counter):
while counter: while thread2.isAlive():
if doExit: if not thread1.isAlive():
thread.exit() doExit = 1
time.sleep(delay)
print "%s: %s" % (threadName, \ pass
time.ctime(time.time()))
counter -= 1 print "Exiting Main Thread"
thread1.start()
thread2.run()
78
Sincronizarea thread-uri
threadLock = threading.Lock()
...
threadLock.acquire()
print_time(self.name, self.counter, 3)
threadLock.release()
S-a implementat un mechanism primar de blocare
obtinut prin apelul metodei Lock()
O data obtinut un nou lock thread-urile pot fi fortate
sa se execute sincron pron apelul metodei
acquire(blocking.
79
Sincronizarea thread-uri
import threading
import time
class newThread (threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
threadLock.acquire()
print_time(self.name, self.counter, 3)
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, \
time.ctime(time.time()))
counter -= 1
80
Sincronizarea thread-uri
threadLock = threading.Lock()
threads = []
thread1 = newThread(1, "Thread01", 1)
thread2 = newThread(2, "Thread02", 2)
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
print "Exiting Main Thread"
81
Implementarea unei cozi de prioritati multithread
import Queue
import threading
import time
import thread
doExit = 0
82
Implementarea unei cozi de prioritati multithread
def process_data(tName, q):
while not doExit:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (tName, data)
else:
queueLock.release()
time.sleep(1)
83
Implementarea unei cozi de prioritati multithread
for tName in threadList: doExit = 1
thread = newThread(tID, tName, for t in threads:
workQueue) t.join()
thread.start()
threads.append(thread) print "Exiting Main Thread"
tID += 1
queueLock.acquire()
for word in wordList:
workQueue.put(word)
queueLock.release()
while not workQueue.empty():
pass
84
Thread oprit de cuanta de timp
wakeCall = threading.Timer(waitTime, \
clean_queue, (qPath ,))
wakeCall.start()
Metoda Timer(interval, func [,args [, kwargs]]) ne
permite acest lucru
85
Thread oprit de cuanta de timp
import threading
import os
def clean_queue (qPath):
jobList = os.listdir(qPath)
for j in jobList:
delPath = "%s/%s" % (qPath, j)
os.remove(delPath)
print "Removing " + delPath
qPath = "/print/queue01"
waitTime = 600 #10 minutes
wakeCall = threading.Timer(waitTime, \
clean_queue, (qPath ,))
wakeCall.start()
86
Python: “If you don’t like me: I like you!”
87