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/

More Related Content

PDF
Pre-Bootcamp introduction to Elixir
KEY
Haskellで学ぶ関数型言語
PPTX
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
PDF
Python fundamentals - basic | WeiYuan
PDF
Python Programming: Data Structure
PDF
Frege is a Haskell for the JVM
PDF
Javascript
PDF
Python dictionary : past, present, future
Pre-Bootcamp introduction to Elixir
Haskellで学ぶ関数型言語
Ciklum net sat12112011-alexander fomin-expressions and all, all, all
Python fundamentals - basic | WeiYuan
Python Programming: Data Structure
Frege is a Haskell for the JVM
Javascript
Python dictionary : past, present, future

What's hot (20)

PDF
Lập trình Python cơ bản
PDF
Swift에서 꼬리재귀 사용기 (Tail Recursion)
PPTX
Python 내장 함수
PDF
ClojurianからみたElixir
PDF
밑바닥부터 시작하는 의료 AI
PPTX
Groovy puzzlers jug-moscow-part 2
PPTX
Super Advanced Python –act1
PDF
Palestra sobre Collections com Python
PDF
Python Usage (5-minute-summary)
PDF
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
PDF
Python postgre sql a wonderful wedding
PDF
ECMAScript 6 new features
PDF
Groovy collection api
PDF
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
PDF
The Ring programming language version 1.5.3 book - Part 25 of 184
PDF
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
PPTX
Groovy vs Boilerplate and Ceremony Code
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Lập trình Python cơ bản
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Python 내장 함수
ClojurianからみたElixir
밑바닥부터 시작하는 의료 AI
Groovy puzzlers jug-moscow-part 2
Super Advanced Python –act1
Palestra sobre Collections com Python
Python Usage (5-minute-summary)
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Python postgre sql a wonderful wedding
ECMAScript 6 new features
Groovy collection api
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
The Ring programming language version 1.5.3 book - Part 25 of 184
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Groovy vs Boilerplate and Ceremony Code
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Ad

Viewers also liked (20)

PPT
Crm User Training Chinese
PPTX
Another Introduce to Redis
PDF
AOA_Report_TrapX_AnatomyOfAttack-Healthcare
PDF
Crew, Foia, Documents 012522 - 012567
ODP
PPTX
PPT母版_简约_v0.1
PDF
Introduction toyun
PDF
4826 201211071011
KEY
Post-It Girl
PPT
The ABC's of Dad and Me
DOC
Cv Nicolas Odier V2011 English
PDF
Chase Oaks VBX - Tuesday - The Trials Of The Journey
PPT
Top lista najboljih poza u krevetu
PPSX
Supervision - Replacing Carrots and Sticks
PPT
What's happening @ the Wadleigh
PPSX
Old Greens Vs Almost
PPT
Hr2all offer to AIMS
PDF
Crew, Foia, Documents 010156 - 010573
PPT
Aims conference 20 3 12
PDF
USART
Crm User Training Chinese
Another Introduce to Redis
AOA_Report_TrapX_AnatomyOfAttack-Healthcare
Crew, Foia, Documents 012522 - 012567
PPT母版_简约_v0.1
Introduction toyun
4826 201211071011
Post-It Girl
The ABC's of Dad and Me
Cv Nicolas Odier V2011 English
Chase Oaks VBX - Tuesday - The Trials Of The Journey
Top lista najboljih poza u krevetu
Supervision - Replacing Carrots and Sticks
What's happening @ the Wadleigh
Old Greens Vs Almost
Hr2all offer to AIMS
Crew, Foia, Documents 010156 - 010573
Aims conference 20 3 12
USART
Ad

Similar to Intro (20)

PPTX
Python and Data Analysis
PDF
Python Fundamentals - Basic
PDF
Python-3-compiled-Cheat-Sheet-version-3.pdf
PPTX
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
PPT
python within 50 page .ppt
PDF
python.pdf
PDF
Python 2.5 reference card (2009)
PDF
Intro to Python
PPTX
PPTX
Python 培训讲义
PDF
Τα Πολύ Βασικά για την Python
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
PDF
Beautiful python - PyLadies
PDF
Python: The Dynamic!
PPT
Python tutorial
PDF
Introduction to python
PPTX
Introduction to Python and TensorFlow
PDF
Programming RPi for IoT Applications.pdf
PDF
A tour of Python
PDF
An overview of Python 2.7
Python and Data Analysis
Python Fundamentals - Basic
Python-3-compiled-Cheat-Sheet-version-3.pdf
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
python within 50 page .ppt
python.pdf
Python 2.5 reference card (2009)
Intro to Python
Python 培训讲义
Τα Πολύ Βασικά για την Python
ComandosDePython_ComponentesBasicosImpl.ppt
Beautiful python - PyLadies
Python: The Dynamic!
Python tutorial
Introduction to python
Introduction to Python and TensorFlow
Programming RPi for IoT Applications.pdf
A tour of Python
An overview of Python 2.7

Intro

  • 1. 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
  • 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 structuri de 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 >>> print b 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) >>> 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
  • 23. Funcții (2) >>> def func5(*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 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'
  • 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) >>> 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))
  • 32. 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
  • 33. Resurse ● https://www.python.org/ ● http://learnpythonthehardway.org/ ● http://corepython.com/ ● http://www.codecademy.com/tracks/python ● http://www.checkio.org/