Introducere în limbajul Python
Cosmin Poieana
<cmin@ropython.org>
→ interpretorul Python
→ tipuri și structuri de date
→ instrucțiuni de control și bucle
→ funcții
→ clase
→ biblioteci
→ fluxuri intrare/ieșire
→ resurse
Ce este Python?
● Limbaj de nivel înalt orientat pe obiecte
● Uz general (POO, procedural, funcțional)
● Interpretoare (CPython, Jython, IronPython)
● Syntaxa (inexistența acoladelor, indentare)
● Încorporare (Cython)
● Avantaje/dezavantaje
Interpretorul Python
● http://python.org
● Windows/Linux
● 2.x/3.x
● >>> help()
● dir(__builtins__)
● Calculator de buzunar
● python -c “print 'Salut Lume'”
Tipuri și structuri de date
● Orice este un obiect
● bool, int, float, str
● tuple, list, set, dict
● eterogenitate
● referinte (slabe)
● etichete
bool, int, float, str
>>> a = 1
>>> b = 2
>>> c = (a + b) ** 2 % 5
>>> c
4
>>> c * 0.5 == 2 is True
False
bool, int, float, str
>>> c * 0.5 == 2
True
>>> (c * 0.5 == 2) is True
True
>>> int(str(c) + "1")
41
>>> "Ana are %d mere {}".format("rosii") % 3
'Ana are 3 mere rosii'
>>>
tuple
>>> a, b = (1, 2, 3), (1,)
>>> a
(1, 2, 3)
>>> b
(1,)
>>> a + b
(1, 2, 3, 1)
>>> a[0]
1
tuple
>>> a[-1]
3
>>> a[1:2]
(2,)
>>> a[0:10:2]
(1, 3)
>>> a[::-1]
(3, 2, 1)
list
>>> a = ["text", 1, 0xFF, sum]
>>> a[0] * 3
'texttexttext'
>>> a[3]([a[1], a[1], a[1]])
3
>>> a[2]
255
>>> a.append(True)
list
>>> a.insert(0, False)
>>> a
[False, 'text', 1, 255, <built-in
function sum>, True]
>>> dir(a)
[...,
'append', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse',
'sort']
>>>
set
>>> a = set([1, 1, 2, 3])
>>> a
set([1, 2, 3])
>>> b = {2, 4, -1, 0}
>>> b
set([0, 2, 4, -1])
>>> help(set.union)
Help on method_descriptor:
union(...)
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
(END)
set
>>> a.union(b)
set([0, 1, 2, 3, 4, -1])
>>> a.intersection(b)
set([2])
>>> b.difference(a)
set([0, 4, -1])
>>>
dict
>>> a = dict()
>>> b = {1: "a", 2: "b"}
>>> b.keys()
[1, 2]
>>> a[_[0]] = b[2]
>>> a
{1: 'b'}
>>> a.update({True: False, False: True})
dict
>>> a
{False: True, 1: False}
>>> hash(1), hash(True)
(1, 1)
>>> a.pop(True)
False
>>> a
{False: True}
>>>
Referinte
>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> del b
>>> a
[1, 2, 3, 4]
>>> del a
>>>
Instrucțiuni condiționale
>>> a = 3
>>> if a == 3:
... print 1
... elif a in (4, 5):
... print 2
... else:
... print 3
...
1
>>> b = "impar" if a % 2 else "par"
Instrucțiuni condiționale
>>> print b
impar
>>> if True and (any([False, 0, None, 1]) or 0):
... print all([1, 2, 3, False])
...
False
>>>
* Nu exista switch
Instrucțiuni repetitive
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> pare = list()
>>> for i in a:
... if not i % 2:
... pare.append(i)
...
>>> pare
[0, 2, 4, 6, 8]
Instrucțiuni repetitive
>>> total = 0
>>> while pare:
... total += pare.pop()
...
>>> total
20
>>> sum([i for i in a if i % 2 == 0])
20
* Nu exista do-while
Funcții
>>> def func(nr):
... return func(nr - 1) * nr if nr > 1 else
1
...
>>> func(4)
24
>>> def func2(nr):
... return func(nr) / (func(func2.k) *
func(nr - func2.k))
...
>>> func2.k = 2
Funcții
>>> func2(3)
3
>>> func2(4)
6
>>> func3 = lambda arg: arg ** (2 if arg % 2 else 3)
>>> func3(2)
8
>>> func3(3)
9
>>>
Funcții (2)
>>> def func4(a, b, c=2):
... if a or b:
... return c * (a + b)
...
>>> func4(1, 1)
4
>>> func4(1, 0, c=3)
3
>>> func4(c=10, a=0, b=0)
>>> func4(c=10, a=0, b=1)
10
Funcții (2)
>>> def func5(*args, **kwargs):
... print args
... print kwargs
...
>>> func5(1, 2, c=4, d=5)
(1, 2)
{'c': 4, 'd': 5}
>>>
Clase
>>> class A(object):
... def __init__(self, x=1):
... self.x = x
... def pow(self, e=2):
... return self.x ** e
...
>>> a = A()
>>> a.pow()
1
>>> A(3).pow(3)
27
Biblioteci
>>> import math
>>> math.sin(math.pi / 2)
1.0
>>> math.sin(math.pi / 4)
0.7071067811865475
>>> math.pow((_ * 2), 2)
1.9999999999999996
>>> math.log(2)
0.6931471805599453
>>> math.sqrt(1024)
32.0
Biblioteci
● Python 2.x
import urllib2
>>>
urllib2.urlopen("http://ipv4.icanhazip.com/").read()
'89.137.142.53n'
● Python 3.x
>>> import urllib.request
>>>
urllib.request.urlopen("http://ipv4.icanhazip.com/")
.read()
b'89.137.142.53n'
Biblioteci
>>> import re
>>> text = """
... Abcdef 22 33 45 http://www.site.com/
... }{*| ----
... 11
... """
>>> re.findall("d{2}", text)
['22', '33', '45', '11']
>>> re.findall("(http://.+)", text)
['http://www.site.com/']
>>> re.findall("[a-zA-Z]+", text)
['Abcdef', 'http', 'www', 'site', 'com']
>>> re.findall("[^swd]+", text)
['://', '.', '.', '/', '}{*|', '----']
Biblioteci
● StringIO
● time
● copy
● decimal
● os
● sys
● shutil
● hashlib
● threading
● json
● socket
● smtplib
● ftplib
● Tkinter
I/O
● Python 3.x
>>> print(1, 2, 3, sep=" - ")
1 - 2 - 3
● Python 2.x
>>> print 1, 2, 3
1 2 3
>>> print "int: %d, float: %f, str: %s" % (1, 2.0, "text")
int: 1, float: 2.000000, str: text
>>> print "int: %d, float: %.2f, str: %s" % (1, 2.0, "text")
int: 1, float: 2.00, str: text
>>> print "{0} {1} {key}".format(1, "a", key=True)
1 a True
I/O (2)
>>> a = raw_input("Input: ")
Input: test
>>> a
'test'
>>> f = open("out.txt", "w")
>>> f.write(a + "n")
>>> f.close()
:~$ cat out.txt
test
I/O (3)
>>> from socket import
*
>>> sock =
socket(AF_INET,
SOCK_STREAM)
>>>
sock.bind(("0.0.0.0",
51234))
>>> sock.listen(5)
>>> cl = sock.accept()
>>> from socket import
*
>>> sock =
socket(AF_INET,
SOCK_STREAM)
>>>
sock.connect(("127.0.0
.1", 51234))
I/O (3)
>>> cl
(<socket._socketobjec
t object at
0x7f09118627c0>,
('127.0.0.1', 58003))
>>>
cl[0].send("Salut!")
6
>>> cl[0].recv(1024)
'Salut!Salut!'
>>> a =
sock.recv(1024)
>>> sock.send(a * 2)
12
Resurse
● https://www.python.org/
● http://learnpythonthehardway.org/
● http://corepython.com/
● http://www.codecademy.com/tracks/python
● http://www.checkio.org/

Intro

  • 1.
    Introducere în limbajulPython Cosmin Poieana <cmin@ropython.org> → interpretorul Python → tipuri și structuri de date → instrucțiuni de control și bucle → funcții → clase → biblioteci → fluxuri intrare/ieșire → resurse
  • 2.
    Ce este Python? ●Limbaj de nivel înalt orientat pe obiecte ● Uz general (POO, procedural, funcțional) ● Interpretoare (CPython, Jython, IronPython) ● Syntaxa (inexistența acoladelor, indentare) ● Încorporare (Cython) ● Avantaje/dezavantaje
  • 3.
    Interpretorul Python ● http://python.org ●Windows/Linux ● 2.x/3.x ● >>> help() ● dir(__builtins__) ● Calculator de buzunar ● python -c “print 'Salut Lume'”
  • 4.
    Tipuri și structuride date ● Orice este un obiect ● bool, int, float, str ● tuple, list, set, dict ● eterogenitate ● referinte (slabe) ● etichete
  • 5.
    bool, int, float,str >>> a = 1 >>> b = 2 >>> c = (a + b) ** 2 % 5 >>> c 4 >>> c * 0.5 == 2 is True False
  • 6.
    bool, int, float,str >>> c * 0.5 == 2 True >>> (c * 0.5 == 2) is True True >>> int(str(c) + "1") 41 >>> "Ana are %d mere {}".format("rosii") % 3 'Ana are 3 mere rosii' >>>
  • 7.
    tuple >>> a, b= (1, 2, 3), (1,) >>> a (1, 2, 3) >>> b (1,) >>> a + b (1, 2, 3, 1) >>> a[0] 1
  • 8.
    tuple >>> a[-1] 3 >>> a[1:2] (2,) >>>a[0:10:2] (1, 3) >>> a[::-1] (3, 2, 1)
  • 9.
    list >>> a =["text", 1, 0xFF, sum] >>> a[0] * 3 'texttexttext' >>> a[3]([a[1], a[1], a[1]]) 3 >>> a[2] 255 >>> a.append(True)
  • 10.
    list >>> a.insert(0, False) >>>a [False, 'text', 1, 255, <built-in function sum>, True] >>> dir(a) [..., 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>>
  • 11.
    set >>> a =set([1, 1, 2, 3]) >>> a set([1, 2, 3]) >>> b = {2, 4, -1, 0} >>> b set([0, 2, 4, -1]) >>> help(set.union) Help on method_descriptor: union(...) Return the union of sets as a new set. (i.e. all elements that are in either set.) (END)
  • 12.
    set >>> a.union(b) set([0, 1,2, 3, 4, -1]) >>> a.intersection(b) set([2]) >>> b.difference(a) set([0, 4, -1]) >>>
  • 13.
    dict >>> a =dict() >>> b = {1: "a", 2: "b"} >>> b.keys() [1, 2] >>> a[_[0]] = b[2] >>> a {1: 'b'} >>> a.update({True: False, False: True})
  • 14.
    dict >>> a {False: True,1: False} >>> hash(1), hash(True) (1, 1) >>> a.pop(True) False >>> a {False: True} >>>
  • 15.
    Referinte >>> a =[1, 2, 3] >>> b = a >>> b.append(4) >>> a [1, 2, 3, 4] >>> del b >>> a [1, 2, 3, 4] >>> del a >>>
  • 16.
    Instrucțiuni condiționale >>> a= 3 >>> if a == 3: ... print 1 ... elif a in (4, 5): ... print 2 ... else: ... print 3 ... 1 >>> b = "impar" if a % 2 else "par"
  • 17.
    Instrucțiuni condiționale >>> printb impar >>> if True and (any([False, 0, None, 1]) or 0): ... print all([1, 2, 3, False]) ... False >>> * Nu exista switch
  • 18.
    Instrucțiuni repetitive >>> a= range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> pare = list() >>> for i in a: ... if not i % 2: ... pare.append(i) ... >>> pare [0, 2, 4, 6, 8]
  • 19.
    Instrucțiuni repetitive >>> total= 0 >>> while pare: ... total += pare.pop() ... >>> total 20 >>> sum([i for i in a if i % 2 == 0]) 20 * Nu exista do-while
  • 20.
    Funcții >>> def func(nr): ...return func(nr - 1) * nr if nr > 1 else 1 ... >>> func(4) 24 >>> def func2(nr): ... return func(nr) / (func(func2.k) * func(nr - func2.k)) ... >>> func2.k = 2
  • 21.
    Funcții >>> func2(3) 3 >>> func2(4) 6 >>>func3 = lambda arg: arg ** (2 if arg % 2 else 3) >>> func3(2) 8 >>> func3(3) 9 >>>
  • 22.
    Funcții (2) >>> deffunc4(a, b, c=2): ... if a or b: ... return c * (a + b) ... >>> func4(1, 1) 4 >>> func4(1, 0, c=3) 3 >>> func4(c=10, a=0, b=0) >>> func4(c=10, a=0, b=1) 10
  • 23.
    Funcții (2) >>> deffunc5(*args, **kwargs): ... print args ... print kwargs ... >>> func5(1, 2, c=4, d=5) (1, 2) {'c': 4, 'd': 5} >>>
  • 24.
    Clase >>> class A(object): ...def __init__(self, x=1): ... self.x = x ... def pow(self, e=2): ... return self.x ** e ... >>> a = A() >>> a.pow() 1 >>> A(3).pow(3) 27
  • 25.
    Biblioteci >>> import math >>>math.sin(math.pi / 2) 1.0 >>> math.sin(math.pi / 4) 0.7071067811865475 >>> math.pow((_ * 2), 2) 1.9999999999999996 >>> math.log(2) 0.6931471805599453 >>> math.sqrt(1024) 32.0
  • 26.
    Biblioteci ● Python 2.x importurllib2 >>> urllib2.urlopen("http://ipv4.icanhazip.com/").read() '89.137.142.53n' ● Python 3.x >>> import urllib.request >>> urllib.request.urlopen("http://ipv4.icanhazip.com/") .read() b'89.137.142.53n'
  • 27.
    Biblioteci >>> import re >>>text = """ ... Abcdef 22 33 45 http://www.site.com/ ... }{*| ---- ... 11 ... """ >>> re.findall("d{2}", text) ['22', '33', '45', '11'] >>> re.findall("(http://.+)", text) ['http://www.site.com/'] >>> re.findall("[a-zA-Z]+", text) ['Abcdef', 'http', 'www', 'site', 'com'] >>> re.findall("[^swd]+", text) ['://', '.', '.', '/', '}{*|', '----']
  • 28.
    Biblioteci ● StringIO ● time ●copy ● decimal ● os ● sys ● shutil ● hashlib ● threading ● json ● socket ● smtplib ● ftplib ● Tkinter
  • 29.
    I/O ● Python 3.x >>>print(1, 2, 3, sep=" - ") 1 - 2 - 3 ● Python 2.x >>> print 1, 2, 3 1 2 3 >>> print "int: %d, float: %f, str: %s" % (1, 2.0, "text") int: 1, float: 2.000000, str: text >>> print "int: %d, float: %.2f, str: %s" % (1, 2.0, "text") int: 1, float: 2.00, str: text >>> print "{0} {1} {key}".format(1, "a", key=True) 1 a True
  • 30.
    I/O (2) >>> a= raw_input("Input: ") Input: test >>> a 'test' >>> f = open("out.txt", "w") >>> f.write(a + "n") >>> f.close() :~$ cat out.txt test
  • 31.
    I/O (3) >>> fromsocket import * >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.bind(("0.0.0.0", 51234)) >>> sock.listen(5) >>> cl = sock.accept() >>> from socket import * >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.connect(("127.0.0 .1", 51234))
  • 32.
    I/O (3) >>> cl (<socket._socketobjec tobject at 0x7f09118627c0>, ('127.0.0.1', 58003)) >>> cl[0].send("Salut!") 6 >>> cl[0].recv(1024) 'Salut!Salut!' >>> a = sock.recv(1024) >>> sock.send(a * 2) 12
  • 33.
    Resurse ● https://www.python.org/ ● http://learnpythonthehardway.org/ ●http://corepython.com/ ● http://www.codecademy.com/tracks/python ● http://www.checkio.org/