Minicurso apresentado no Dev Day da FATEC São Caetano em 2015
Patrocínio: Boolabs
Apoio: FATEC São Caetano, Centro Paula Souza, Governo do Estado de São Paulo
Python Básico:
- Variáveis e Tipos (Texto, Números, Booleanos, None, Listas, Tuplas, Dict, Set)
- Decisão
- Repetição
- Exceções
- Funções (com objetos de primeira classe)
- Módulos
- Classes (com herança múltipla)
- Duck typing
Extras:
- Heroku
- Programação Funcional
- Próximos tópicos
8. QUEM USA PYTHON?QUEM USA PYTHON?
Google Search
Youtube
Dropbox
Instagram
Pinterest
Rdio (server)
Spotify (server)
NewRelic
JPMorgan
Bank of America
Battlefield (server)
Civilization IV
Second Life (IBM)
Globo.com
Magazine Luiza
PayPal & eBay Rede Colibri
API Registro.com.br
Escolher Seguro
Omelete.com.br
Boomage ( )
( )
Scanboo ( )
Boolabs
Booska Boolabs
Boolabs
e outrosmuitos
10. POR QUEPOR QUE ??PYTHONPYTHON
P: Que problema Python tenta resolver?
R: .Produtividade do programador
“ My observation at the time was that
computers were getting faster and cheaper at
an incredible rate (...). [But] the cost of the
programmers to program them remained not
going down. (Guido van Rossum, 2008)
11. POR QUEPOR QUE ??PYTHONPYTHON
Produtividade do programador
“ (...) programmer productivity measured in lines of code
perhour (LOC/hour) is roughly independent of the
programming language. (PRECHELT, 2010)
12. POR QUEPOR QUE ??PYTHONPYTHON
Produtividade do programador
“ [How] about the indentation in Python?
It's the right thing to do from a code readability (...) [and]
from a maintenance point of view. And
: no program is perfect from the
start, and if it is successful, it will be extended. So
maintenance is a fact of life, not a necessary evil. (GvR, 2008)
maintainability of
code is what counts most
Facil escrita de código (baixa curva de aprendizagem)
Fácil leitura e modificação de código (manutenção)
13. Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darw
Type "help", "copyright", "credits" or "license" for more info
>>> import this
POR QUEPOR QUE ??PYTHONPYTHON
Fácil Manutenção
The Zen of Python
(Tim Peters, 2004)
como filosofia!
14. POR QUEPOR QUE ??PYTHONPYTHON
Fácil Manutenção
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
como filosofia!
-- Style Guide for Python CodePEP 0008
15. POR QUEPOR QUE ??PYTHONPYTHON
Interpretado
XKCD 303: Compiling
16. POR QUEPOR QUE ??PYTHONPYTHON
Interpretado
REPL: Read–Eval–Print-Loop
17. POR QUEPOR QUE ??PYTHONPYTHON
Muitas Bibliotecas Disponíveis
XKCD 353: Python
Python Package Index ( )PyPI
Github
19. COMO É O CÓDIGO?COMO É O CÓDIGO?
print 'Hello World'
Hello World
Variáveis
algum_numero = 1
algum_decimal = 3.14
algum_texto = 'Hello World'
# Algum comentário
Funções
def soma_ab(a, b):
return a + b
20. COMO É O CÓDIGO?COMO É O CÓDIGO?
Classes
class Veiculo(object):
posicao_x = 0
posicao_y = 0
def andar(self, x, y):
self.posicao_x += x
self.posicao_y += y
return self.posicao_x, self.posicao_y
carro = Veiculo()
23. VARIÁVEIS E NOMESVARIÁVEIS E NOMES
CONSTANTE_PI = 3.14
variavel_numerica = 12345
variavel_texto = 'um dois tres quatro'
class NomeDaClasse(object):
atributo_publico = 'um'
__atributo_privado = 'dois'
def nome_do_metodo(self, variavel_um):
# comentario
return None
a, b = 'um', 'dois'
b, a = a, b # sem variável intermediária
24. TIPAGEMTIPAGEM
DINÂMICA E FORTEDINÂMICA E FORTE
>>> a = 'texto'
>>> type(a)
str
>>> a = 123
>>> type(a)
int
>>> b = '456'
>>> type(b)
str
>>> a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
DINÂMICA E FORTEDINÂMICA E FORTE
33. DECISÃO:DECISÃO: IFIF
if 1+1 == 3:
return 'conte de novo'
elif None:
return 'None vale como False'
else:
return '1+1 != 3 (ao menos em Python)'
ternaria = 'sim' if True else u'não'
>>> True or False
True
>>> True and False
False
>>> not False
True
a = b or c
>>> True == False
False
>>> True != False
True
>>> True is None
False
35. REPETIÇÃOREPETIÇÃO
i = 0
while i<42:
print i
i += 1
lista = [1, -3.14, None, 'azul']
for i in lista:
if i is None:
continue
if i == 'sair':
break
print i*2
lista = [1, -3.14, None, 'azul']
for n, coisa in enumerate(lista):
print 'Indice:', n
print 'Coisa:', coisa # lista[n]
36. REPETIÇÃOREPETIÇÃO
arquivo = open('/tmp/meuarquivo.txt')
for linha in arquivo:
print linha
coisas = {1: 'um', 'pi': 3.14, 'azul': '#00F', None: 'nada'}
for key, val in coisas.values():
print 'Keyword:', key
print 'Valor:', val
from zipfile import ZipFile
for linha in ZipFile.open('/tmp/arquivo.zip'):
print linha
45. É OBJETOÉ OBJETOTUDOTUDO
INCLUSIVE FUNÇÕESINCLUSIVE FUNÇÕES
( )bad, bad Java. No donut for you
“ Função: objeto que tem o método __call__
funcao(a, b) <-> funcao.__call__(a, b)
52. TUDO É OBJETOTUDO É OBJETO
>>> type(123)
int
>>> type(int)
type
>>> type(type)
type
>>> type(None)
NoneType
>>> type(type(NoneType))
type
>>> type(True)
bool
>>> type(bool)
type
>>> type('txt')
str
>>> type(str)
type
>>> def func():
... pass
>>> type(func)
function
>>> type(function)
type
>>> import random
>>> type(random)
module
>>> type(type(random))
type
53. Módulo
contém as funções: e
__builtin__
help() dir()
DESCOBERTA DEDESCOBERTA DE
MÉTODOS E ATRIBUTOSMÉTODOS E ATRIBUTOS
54. CLASSES SIMPLESCLASSES SIMPLES
class A(object):
a = 1 # publico
__b = 2 # privado
def met(self):
print 'chamando A.met...'
return self.a, self.__b
class B(A):
__c = 3 # privado
def __init__(self):
# construtor
print 'Iniciando B...'
def met(self):
'Imprime a e __b'
print 'chamando B.met...'
return super(B, self).met()
>>> instancia = A()
>>> instancia.a
1
>>> instancia.met()
chamando A.met...
(1, 2)
>>> outra = B()
Iniciando B...
>>> outra.a
1
>>> outra.metodo()
chamando de B.met...
chamando de A.met...
(1, 2)
>>> isinstance(outra, A)
True
55. HERANÇA MULTIPLAHERANÇA MULTIPLA
class Veiculo(object):
lugares = 1
posicao_x = 0
posicao_y = 0
posicao_z = 0
class Carro(Veiculo):
lugares = 4
pneus = 4
def andar(x, y):
self.x += x
self.y += y
class Aviao(Veiculo):
lugares = 2
asas = 2
def voar(x, y, z):
self.x += x
self.y += y
self.z += z
class CarroVoador(Carro, Aviao):
pass
56. DUCK TYPINGDUCK TYPING
“ When I see a bird that walks like a duck
and swims like a duck and quacks like a
duck, I call that bird a duck.
( )James Whitcomb Riley
57. DUCK TYPINGDUCK TYPING
>>> 2 * 3
6
>>> 'dois' * 3
'doisdoisdois'
e implementamint str __mul__
f = open('arquivo.txt')
conteudo = f.read()
from StringIO import StringIO
sio = StringIO('texto')
conteudo = sio.read()f.seek(0)
for linha in f:
print linha
sio.seek(0)
for linha in sio:
print linha
def imprime_linhas(arquivo):
for linha in arquivo.read()
print linha
imprime_linhas(f)
imprime_linhas(sio)
58. class Personagem(object):
def __init__(self, nome):
self.nome = nome
def __mul__(self, coisa):
print self.nome, 'joga bomba em', coisa
>>> heroi = Personagem(u'Herói')
>>> heroi * 'monstro'
Herói joga bomba em monstro
class MinhaClasse(object):
def __init__(texto):
self.texto = texto
def __mul__(self, numero):
return self.texto * numero
>>> mc = MinhaClasse(4)
>>> mc * 3
12
>>> mc1 = MinhaClasse('um')
>>> mc1 * 3
'umumum'
65. "QUERIA QUE TIVESSEM ME"QUERIA QUE TIVESSEM ME
CONTADO ANTES"CONTADO ANTES"
(fonte: )http://slides.com/chrissim/deck#/10
-- Allen & Chris, Pycon 2015 --
66. "QUERIA QUE TIVESSEM ME"QUERIA QUE TIVESSEM ME
CONTADO ANTES"CONTADO ANTES"
1. Installing Python
2. Using virtualenv and the requirements.txt file
3. Useful Python libraries
4. Know the difference between mutable and immutable
data types
5. Positional argruments vs. keyword argruments
6. What is the __init__ file?
7. Functions return none implicitly
8. Which IDE should I use?