Sunteți pe pagina 1din 53

PROGRAMAREACALCULATOA

RELOR ȘI LIMBAJE DE
PROGRAMARE II
Introducere in Python
http://www.eed.usv.ro/~ionelar/teaching.html

PCLP II :: Introducere în Python Limbajul Python


▪ Creat
în 1989 de programatorul Guido van
Rossum
▪ Limbajde programare dinamic multi-
paradigmă: orientat pe obiect, programare
imperativă, funcțională sau procedurală.
▪ Este un limbaj de nivel înalt, foarte folosit
în dezvoltarea platformelor web
(Google,Yahoo etc.), dar și în calcul științific
▪ Python este un limbaj interpretat, nu
compilat → ușor de portat pe diverse SO sau
arhitecturi hardware

http://www.eed.usv.ro/~ionelar/
2
teaching.html
John M. Zelle, Python Programming An Introduction to Computer Science(3rd ed)

Interpretor vs.
PCLP II :: Introducere în Python

Compilator (1)
▪ Limbaj de nivel înalt:
▪ c = a+b
▪ Acestă intrucțiune trebuie translatată în

limbaj mașină pentru a putea fi executată de

calculator.
▪ Compilatoarele convertesc programele

scrise în limbaje de nivel înalt în limbajul

mașină al sistemului.
http://www.eed.usv.ro/~ionelar/teaching.html

Interpretor vs.
PCLP II :: Introducere în Python

Compilator (2)
▪ Interpretoarele simulează înțelegera unui
limbaj de nivel înalt a calculatoarelor;
▪ Sursa programului nu este translatată în
limbaj mașină;
▪ Un interpretor analizează și execută codul
sursă intrucțiune cu instrucțiune.
John M. Zelle, Python Programming An Introduction to Computer Science(3rd ed)

4
http://www.eed.usv.ro/~ionelar/teaching.html

Interpretor vs.
PCLP II :: Introducere în Python

Compilator (3)
▪ O dată ce un program este compilat, el poate fi

executat ori de câte ori este nevoie fără a fi nevoie de

codul sursă sau compilator.


▪ Dacă programul este interpretat, codul sursă și

interpretorul sunt necesare de fiecare dată la rularea

programului.
▪ În general, programele compilate rulează mai rapid

față de cele interpretate deoarece translatarea codului

sursă are loc o singură dată.


▪ Programele interpretate sunt mai ușor portabile; de

ex. un program executabil furnizat de un compilator

pentru Intel nu va rula pe o platformă Mac fără o

recompilare, spre deosebire de codul interpretat a

cărui portabilitate o asigură interpretorul.


http://www.eed.usv.ro/~ionelar/
5
teaching.html

PCLP II :: Introducere în Python Python 3.7.3

▪ Release Date: March 25, 2019


▪ https://www.python.org/

▪ “>>>”- Python este pregătit pentru a primi


comenzi, comenzi denumite instrucțiuni
(statements)

http://www.eed.usv.ro/~ionelar/
6
teaching.html
Crearea unui
PCLP II :: Introducere în Python

fișier Python
▪ Crearea unui fișier cu extensia .py,
folosind un editor de texte sau din consola
Python

http://www.eed.usv.ro/~ionelar/
7
teaching.html

PCLP II :: Introducere în Python Comentarii


▪ încep cu # și țin până la sfârșitul liniei
▪ începcu ’’’ și țin mai multe rânduri, până
la un nou ’’’

http://www.eed.usv.ro/~ionelar/
8
teaching.html
http://www.eed.usv.ro/~ionelar/teaching.html
▪ Sintaxa:
print(object(s), separator=separator, end=end,
file=file, flush=flush)
object(s) Any object, and as many as you like. Will be converted to string before printed
sep='separator' Optional. Specify how to separate the objects, if there is more than one.
Default is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
file Optional. An object with a write method. Default is sys.stdout
flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False

Scrierea - print()
PCLP II :: Introducere în Python9

PCLP II :: Introducere în Python Citirea


▪ Sintaxa:
input([prompt]) -> string

prompt A String, representing a default message before the


input.
http://www.eed.usv.ro/~ionelar/
10
teaching.html
http://www.eed.usv.ro/~ionelar/teaching.html

Variabile. Tipuri de date


▪ Nu se declară
▪ Tipul variabilelor este stabilit în timpul
execuției
PCLP II :: Introducere în Python11

PCLP II :: Introducere în Python Variabile. Tipuri


de date
▪ Numerice – numerele sunt imutabile –

odată create valoarea nu se mai poate

schimba (operațiile crează noi obiecte) ✓int


(numere întregi) - numerele întregi (pozitive și

negative), dimensiune limitat doar de memoria

disponibilă. Operații: +, -, *, /, //, **, % comparare:==,!


=,<, > operații pe biți: |, ^, &, <<, >>, ~ ✓bool (boolean)
- Valorile True (1) și False (0); Operații: and, or, not
✓float (numere reale): numerele reale (dublă

precizie); Operatii: +, -, *, / comparare:==,!=,<, >

▪ Numere complexe

http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

12
Variabile.
Tipuri de
date
PCLP II :: Introducere în Python13
Tipuri de
http://www.eed.usv.ro/~ionelar/
teaching.html

Variabile. date
PCLP II :: Introducere în Python14

PCLP II :: Introducere în Python Conversii de tip


- cast
▪ Conversia se realizează cu ajutorul
funcțiilor constructor:
▪ int()

▪ float()

▪ str()
http://www.eed.usv.ro/~ionelar/
15
teaching.html

PCLP II :: Introducere în Python Operatori

▪ Aritmetici

Operator Name Example

+ Addition x + y

- Subtraction x - y

* Multiplication x * y

/ Division x / y

% Modulus x % y

** Exponentiation x ** y

// Floor division x // y

http://www.eed.usv.ro/~ionelar/
16
teaching.html

PCLP II :: Introducere în Python Operatori


▪ Atribuire
Operator Example Same As
=x=5x=5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
http://www.eed.usv.ro/~ionelar/teaching.html
<<= x <<= 3 x = x << 3
17
http://www.eed.usv.ro/~ionelar/teaching.html

Operatori

▪ Atribuirea multiplă
PCLP II :: Introducere în Python18

http://www.eed.usv.ro/~ionelar/teaching.html
Operatori

▪ Comparare

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x > y

< Less than x < y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


PCLP II :: Introducere în Python19

PCLP II :: Introducere în Python Operatori


▪ Logici
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is
not(x < 5 and x < 10) true
http://www.eed.usv.ro/~ionelar/teaching.html

20

PCLP II :: Introducere în Python Operatori


▪ Identitate
Operator Description Example
is Returns true if both variables are the same object x is y
is not Returns true if both variables are not the same object x
is not y
▪ Apartenență
Operator Description Example
in Returns True if a sequence with the specified value is
x in y present in the object
not in Returns True if a sequence with the specified value is
x not in y not present in the object
http://www.eed.usv.ro/~ionelar/teaching.html

21

PCLP II :: Introducere în Python Operatori


▪ pe biți
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left
Shift left by pushing zeros in from the right and let the shift
leftmost bits fall off
>> Signed right
Shift right by pushing copies of the leftmost bit in from shift
the left, and let the rightmost bits fall off
http://www.eed.usv.ro/~ionelar/teaching.html

22

PCLP II :: Introducere în Python Blocuri

▪ Partea unui program care este executată


ca o unitate
▪ Secvență de instrucțiuni
▪ Se realizează prin identarea liniilor:
toate instrucțiunile identate la același nivel
aparțin aceluiași bloc
▪if ... else
http://www.eed.usv.ro/~ionelar/
teaching.html

23
▪for

▪while
PCLP II :: Introducere în Python24

http://www.eed.usv.ro/~ionelar/
teaching.html

Structuri de
control http://www.eed.usv.ro/~ionelar/
teaching.html
IF...ELSE
http://www.eed.usv.ro/~ionelar/
teaching.html

PCLP II :: Introducere în Python25 FOR


PCLP II :: Introducere în Python26

PCLP II :: Introducere în Python FOR


▪ Funcțiarange(stop) sau range(start,
stop [,step])
▪ Creează o listă
▪ [0, 1, ... , stop-1]

▪ [start, start+1, ... , stop-1]

▪ [start, start+step, ... , start+(n-1)*step]


http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

27
WHILE
PCLP II :: Introducere în Python29

http://www.eed.usv.ro/~ionelar/
teaching.html

FOR http://www.eed.usv.ro/~ionelar/
teaching.html
PCLP II :: Introducere în Python28
WHILE
▪ Buclă infinită http://www.eed.usv.ro/~ionelar/
teaching.html

Șiruri de
caractere
▪ While ... else
PCLP II :: Introducere în Python30
▪ Extragerea unui
caracter

▪ Extragerea unui
subșir
PCLP II :: Introducere în Python31

PCLP II :: Introducere în Python Șiruri de


caractere
▪ Eliminarea spațiior dintr-un șir (de la început
sau de la sfârșit)

▪ Lungimea unui șir

http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

32
Șiruri de
caractere
▪ Transformarea în
minuscule
▪ Transformarea
majuscule
în
caractere
PCLP II :: Introducere în Python33

▪ Împărțirea în
subșiruri

▪ Transformarea în
majuscule
PCLP II :: Introducere în Python34

http://www.eed.usv.ro/~ionelar/
teaching.html

Șiruri de
http://www.eed.usv.ro/~ionelar/
teaching.html
▪ Formatarea
șirurilor
Șiruri de PCLP II :: Introducere în Python35

caractere
PCLP II :: Introducere în Python Colecții
(Vectori)

▪ Liste - colecție ordonată și mutabilă


▪ Tuple - colecție ordonată și imutabilă
▪ Mulțimi- colecție neordonată și
neindexată
▪ Dicționare - colecție neordonată, indexată
și mutabilă
http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

36
Liste

▪ Accesarea unui
element

▪ Modificarea unui
element
PCLP II :: Introducere în Python38

http://www.eed.usv.ro/~ionelar/
teaching.html

Liste
PCLP II :: Introducere în Python37
http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html
▪ Dimensiunea
liste
unei
Liste
Liste ▪ Adăugarea unui
element în listă
▪ Manipularea listei
folosind bucle ▪ APPEND

▪ Căutarea unui
element ▪ INSERT
PCLP II :: Introducere în Python40
PCLP II :: Introducere în Python39

PCLP II :: Introducere în Python Liste

▪ Ștergerea unui element în listă


▪ REMOVE

▪ POP (șterge ultimul din listă sau cel


indicat de index)

http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

41
Liste

▪ Ștergerea întregii
liste
PCLP II :: Introducere în Python42
http://www.eed.usv.ro/~ionelar/
teaching.html
▪ LIST
▪ COPY Liste

▪ Copierea unei liste


PCLP II :: Introducere în Python43

Liste – metode
PCLP II :: Introducere în Python

predefinite
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
http://www.eed.usv.ro/~ionelar/teaching.html
sort() Sorts the list

44
http://www.eed.usv.ro/~ionelar/teaching.html

Liste
liste.py
PCLP II :: Introducere în Python45

[out]:

PCLP II :: Introducere în Python Liste (tablouri)


▪ Definire vector, initializare si afisare
N = 10 (1)tab = [0] * N (2)tab = [0 for i in
range(N)]
print(tab) [out]:
for i in tab:
print(tab[i],end=' ')
[out]:
http://www.eed.usv.ro/~ionelar/teaching.html

46

Lista comprehensivă
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Citirea vectorului de la tastatura

[out]:
PCLP II :: Introducere în Python47

[out]:
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
PCLP II :: Introducere în Python48

[out]:

http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
PCLP II :: Introducere în Python49
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Definire matrice

[out]:
PCLP II :: Introducere în Python50
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Definire matrice

[out]:
PCLP II :: Introducere în Python51
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Definire matrice

[out]:
PCLP II :: Introducere în Python52
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Definire matrice

[out]:
PCLP II :: Introducere în Python53

[out]:
http://www.eed.usv.ro/~ionelar/teaching.html

Liste (tablouri)
▪ Citire matrice de la tastatura
PCLP II :: Introducere în Python54

Tuple PCLP II :: Introducere în Python


/
Enumerari
▪ Colectie de elemente imutabila (elementele nu

pot fi modificate, vs. mutabila - liste)


▪ Dimensiune fixa ( nu pot fi adaugate elemente

cu append, dar suporta concatenarea cu alte

tuple)
▪ Elementele sunt liste)http://www.eed.usv.ro/~ion
elar/teaching.html
incadrate intre () (vs. 55
[] –
PCLP II :: Introducere în Python Tuple
No. Function with Description

1 cmp(tuple1, tuple2)Compares elements of both tuples.

2 len(tuple)Gives the total length of the tuple.

3 max(tuple)Returns item from the tuple with max value.

4 min(tuple)Returns item from the tuple with min value.

5 tuple(seq)Converts a list into tuple.

http://www.eed.usv.ro/~ionelar/ [out]:
teaching.html

56
Tuple
http://www.eed.usv.ro/~ionelar/
teaching.html

PCLP II :: Introducere în Python57

PCLP II :: Introducere în Python Dicționare


▪ Colecție neordonată, indexată și mutabilă
▪ Conține indecși de cuvinte și pentru
fiecare index conține o definiție.
▪ Indexul = KEY
▪ Definiția = VALUE
▪ Exemplu:

bdStud = {123:’Popescu Ion’, 124:’Grigorescu


Maria’, \ 125:’Andronic Cezar’}

http://www.eed.usv.ro/~ionelar/
58
teaching.html
No. Methods with Description
1 dict.clear()Removes all elements of dictionary dict
2 dict.copy()Returns a shallow copy of dictionary dict
3 dict.fromkeys()Create a new dictionary with keys from seq and
values set to value.
4 dict.get(key, default=None)For key key, returns value or default
if key not in dictionary
5 dict.has_key(key)Returns true if key in dictionary dict, false
otherwise
6 dict.items()Returns a list of dict's (key, value) tuple pairs
7 dict.keys()Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)Similar to get(), but will set
dict[key]=default if key is not
already in dict
9 dict.update(dict2)Adds dictionary dict2's key-values pairs to dict
10 dict.values()Returns list of dictionary dict's values
http://www.eed.usv.ro/~ionelar/teaching.html

Dicționare
PCLP II :: Introducere în Python59

[out]:
http://www.eed.usv.ro/~ionelar/teaching.html

Dicționare
PCLP II :: Introducere în Python60

http://www.eed.usv.ro/~ionelar/teaching.html

Dicționare
PCLP II :: Introducere în Python61
[out]:

http://www.eed.usv.ro/~ionelar/teaching.html

Dicționare
PCLP II :: Introducere în Python62

PCLP II :: Introducere în Python Funcții


▪ Definirea
funcțiilor cu ajutorul sintaxei:
▪ def <nume_functie> ( [ <lista
parametri> ] ): bloc de instructiuni [return
valori]
▪ Nu se specifică tipul argumentelor, acesta
fiind transmis la apelul functiei. Ex.
def fractie(x,y):
if (y==0):
return else:
return float(x)/float(y)
http://www.eed.usv.ro/~ionelar/teaching.html

63

PCLP II :: Introducere în Python Funcții


▪ Funcțiilepot returna una sau mai multe
valori cu ajutorul instrucțiunii return.
Execuția instrucțiunii return fără argumente
face ca funcția să returneze valoarea None.
▪ Pentru a putea folosi o variabilă globală în
cadrul unei funcții, este necesar specificare
în cadrul funcției sintaxa:
global <nume_variabila>
x=5 teaching.html

64
http://www.eed.usv.ro/~ionelar/
x=?
PCLP II :: Introducere în Python Funcții
▪ Încadrul listei de argumente pot fi
transmise argumente cu valoare implicită

http://www.eed.usv.ro/~ionelar/ http://www.eed.usv.ro/~ionelar/
teaching.html teaching.html

65
Funcții
http://www.eed.usv.ro/~ionelar/
PCLP II :: Introducere în Python66
teaching.html

Funcții
[out]:
▪ Afișarea
comentariilor din
funcție:

http://www.eed.usv.ro/~ionelar/ [out]:
teaching.html
PCLP II :: Introducere în Python68

Funcții
PCLP II :: Introducere în Python67

PCLP II :: Introducere în Python Funcții cu un


număr variabil de argumente
(împachetarea
argumentelor )

teaching.html
69
http://www.eed.usv.ro/~ionelar/
[out]:

PCLP II :: Introducere în Python Funcții cu un


număr variabil de argumente
(despachetarea
argumentelor)

[out]:

http://www.eed.usv.ro/~ionelar/
70
teaching.html
http://www.eed.usv.ro/~ionelar/teaching.html
Module (import)
▪ Utilizarea unei functii din alt modul
[out]:
PCLP II :: Introducere în Python71

http://www.eed.usv.ro/~ionelar/teaching.html

Module (import ... as ...)


PCLP II :: Introducere în Python72

[out]:

http://www.eed.usv.ro/~ionelar/teaching.html

Module (import ... as ...)


PCLP II :: Introducere în Python73

PCLP II :: Introducere în Python Module Aplicație:


Evaluarea expresiilor aritmetice post-
fixate
▪ Exemple de expresii aritmetice post fixate 10 2
3 + / → (2+3)/10 = 0.5 a b – a b + * → (a-b)*(a+b) 10
→ 10 X → X
▪ Sintaxa în forma normală Backus: <expr_pfix>
::= <operand> | <expr_pfix> <expr_pfix> <operator>
<operand> ::= <nr_fără_semn> | <id_variabilă>
<nr_fără_semn> ::= <cifră> | <nr_fără_semn> <cifră>
<cifră> ::= 0 | 1 | 2 | . . . | 9 <id_variabilă> ::= <literă> |
<id_variabilă> <literă> <literă> ::= a | b | c | . . . |z | A | B
| C | . . . | Z | _ <operator> ::= + | - | * | /
http://www.eed.usv.ro/~ionelar/
74
teaching.html

PCLP II :: Introducere în Python Module Aplicație:


Evaluarea expresiilor aritmetice post-
fixate
▪ Fieexpresia 10 2 3 + * . Analiza sintactica
este următoarea:
75
1 http://www.eed.usv.ro/~ionelar/teaching.html
singur simbol neterminal de start → Expresie corectă
dpdv. sintactic

PCLP II :: Introducere în Python Module Aplicație:


Evaluarea expresiilor aritmetice post-
fixate

1023+*
push(3)

pop(3)

3 push(50)
push(50)
pop(2)
push(5) push(10)
push(5) 102 + 3 = 5
1010 * 5 = 50
pop(5) 1010 * 5 = 50
pop(5) 50
pop(5) 50
50
push(2) pop(50)
25 pop(50)
pop(10)
pop(50) http://www.eed.usv.ro/~ionelar/
teaching.html
PCLP II :: Introducere în Python77

Stiva vidă → expr. este


corectă

76
http://www.eed.usv.ro/~ionelar/
teaching.html

PCLP II :: Introducere în Python Module


▪ Temă: implementați funcțiile specifice
stivei în fișierul stiva.py pentru a putea fi
folosite în aplicația pentru evaluarea
parantezelor
http://www.eed.usv.ro/~ionelar/
78
teaching.html
<file_object> = open (<file_name>,[<mod>])
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or
truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the
operation fails.
Open for appending at the end of the file without truncating it.
'a'
Creates a new file if it does

not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
http://www.eed.usv.ro/~ionelar/teaching.html

Operații cu fișiere text


▪ Deschiderea unui fișier
PCLP II :: Introducere în Python79

Metode Descriere .read(size=-1) Citeste size octeti din fisier.


Dacă nu este specificat parametrul size
sau este specificată valoarea -1 pentru acest parametru, se
va citi întreg fișierul.
.readline(size=-1) Citeste size octeti de pe o linie din fisier.
Dacă nu este specificat nici
un argument sau este transmisă valoarea -1, atunci va fi citită
întreaga linie (sau restul de octeti rămași de pe linie).
.readlines() Se citesc liniile din fișier și se memorează într-o
listă.
http://www.eed.usv.ro/~ionelar/teaching.html

Operații cu fișiere text


▪ Citirea informațiilor din fișier
PCLP II :: Introducere în Python80

S-ar putea să vă placă și