SlideShare uma empresa Scribd logo
1 de 72
Baixar para ler offline
EM 4 HORASEM 4 HORASPYTHONPYTHON
Alan Justino da Silva
alan.justino@yahoo.com.br
@alanjds
slides.com/alanjds/python/live
MOTIVAÇÃOMOTIVAÇÃO
BÁSICOBÁSICO
WEBWEB
EXTRASEXTRAS
BÁSICOBÁSICO
WEBWEB
EXTRASEXTRAS
MOTIVAÇÃOMOTIVAÇÃO
MOTIVAÇÃOMOTIVAÇÃO
Por que Python?
Como é o código Python?
Quem usa Python?
QUEM USA PYTHON?QUEM USA PYTHON?
QUEM USA PYTHON?QUEM USA PYTHON?
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
MOTIVAÇÃOMOTIVAÇÃO
Quem usa Python?
Como é o código Python?
Por que Python?
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)
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)
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)
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!
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
POR QUEPOR QUE ??PYTHONPYTHON
Interpretado
XKCD 303: Compiling
POR QUEPOR QUE ??PYTHONPYTHON
Interpretado
REPL: Read–Eval–Print-Loop
POR QUEPOR QUE ??PYTHONPYTHON
Muitas Bibliotecas Disponíveis
XKCD 353: Python
Python Package Index ( )PyPI
Github
MOTIVAÇÃOMOTIVAÇÃO
Quem usa Python?
Por que Python?
Como é o código Python?
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
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()
MOTIVAÇÃOMOTIVAÇÃO
WEBWEB
EXTRASEXTRAS
BÁSICOBÁSICO
BÁSICOBÁSICO
Decisão
Repetição
Exceções
Funções
Módulos
Classes
Variáveis e Tipos
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
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
TRUE, FALSE, NONETRUE, FALSE, NONE
>>> True, False
(True, False)
>>> bool(True), bool(1), bool('texto')
(True, True, True)
>>> bool(False), bool(0), bool(''), bool(None)
(False, False, False, False)
>>> bool('False'), bool(-1), bool(' ')
(True, True, True)
TEXTOTEXTO
>>> 'texto', "texto", type('texto')
('texto', 'texto', str)
>>> u'texto com acentuação', type(u'texto')
(u'texto com acentuaxe7xe3o', unicode)
>>> 'texto' + 'com' + 'texto'
'textocomtexto'
>>> """texto de
muitas
linhas"""
'texto den muitasn linhas'
>>> u'texto mesclado: %s %s %s %s %s' % (1, '+', 1, '=', 1+1)
u'texto mesclado: 1 + 1 = 2'
NÚMEROSNÚMEROS
>>> type(123), type(3.14), type(5+2j)
(int, float, complex)
>>> float(123), int(3.14), complex(123)
(123.0, 3, 123+0j)
>>> int('3'), float('5'), float('+inf')
(3, 5.0, inf)
>>> float('inf') - 10*1000
inf
>>> float('inf') + float('inf') + float('inf')
inf
>>> float('inf') - float('inf')
nan
NÚMEROSNÚMEROS
>>> 1+1
2
>>> 2*2
4
>>> 3**2
9
>>> 5/2
2
>>> 5%2
1
>>> round(3.14)
3.0
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(16)
4.0
>>> math.sqrt(15)
3.872983346207417
>>> math.floor(3.14)
3.0
>>> math.ceil(3.14)
4.0
LISTAS E TUPLASLISTAS E TUPLAS
>>> [1,2,3] + [3,4,5,6]
[1, 2, 3, 3, 4, 5, 6]
>>> lista = [] # list()
>>> lista.append(123)
>>> lista += [456]
>>> lista
[123, 456]
>>> lista[0]
123
>>> 123 in lista
True
>>> lista.pop(123)
123
>>> 123 in lista
False
>>> (1,2,3) + (3, 4,5,6)
(1, 2, 3, 3, 4, 5, 6)
>>> tupla = () # tuple()
>>> tupla.append(123)
AttributeError: 'tuple'
object has no 'append'
>>> tupla = (123, 456)
>>> tupla
(123, 456)
>>> tupla[0]
123
>>> 123 in tupla
True
>>> list(tupla)
[123, 456]
DICTDICT
>>> dicionario = {} # dict()
>>> cores_css = {'azul': '#0000FF', 'laranja': '#FFA500'}
>>> frutas_en = {u'maçã': 'apple', 'laranja': 'orange'}
>>> numeros = {'um': 1, 'pi': 3.14, 0: 'zero', None: None}
>>> cores_css['azul']
'#0000FF'
>>> numeros[0]
'zero'
>>> cores_css['laranja'] == frutas_en['laranja']
False
>>> numeros.keys() # não garante ordem
['um', 0, 'pi', None]
>>> numeros.values() # não garante ordem
[1, 'zero', 3.14, None]
>>> numeros.items() # não garante ordem
[('um', 1), (0, 'zero'), ('pi', 3.14), (None, None)]
( )Vetor Associativo
SETSET
>>> conjunto_a = {1, 2, 3} # set([1,2,3])
>>> conjunto_b = {3, 4, 5, 6}
>>> conjunto_a.union(conjunto_b)
{1, 2, 3, 4, 5, 6}
>>> conjunto_a.update(123)
>>> conjunto_a
{1, 2, 3, 123}
>>> 123 in conjunto_a
True
( )Conjunto sem repetições
BÁSICOBÁSICO
Variáveis e Tipos
Repetição
Exceções
Funções
Módulos
Classes
Decisão
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
BÁSICOBÁSICO
Variáveis e Tipos
Decisão
Exceções
Funções
Módulos
Classes
Repetição
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]
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
BÁSICOBÁSICO
Variáveis e Tipos
Decisão
Repetição
Funções
Módulos
Classes
Exceções
>>> for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]:
... print a/b
1
2
3
ZeroDivisionError Traceback (most recent call last)
<ipython-input-15-5be9e7c9049a> in <module>()
1 for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]:
--> 2 print a/b
ZeroDivisionError: integer division or modulo by zero
>>> for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]:
... try:
... print a/b
... except ZeroDivisionError:
... print 'infinito'
... except Exception as error:
... print 'Erro inesperado:', error
1
2
3
'infinito'
-1
EXCEÇÕESEXCEÇÕES
>>> a, b = 1, 0
>>> c = a/b
ZeroDivisionError: integer division or modulo by zero
EXCEÇÕESEXCEÇÕES
conecta_na_base_de_dados()
try:
faz_algo_perigoso()
except Exception as error:
print u'Erro: Não consegui fazer "algo perigoso"'
raise error
finally:
desconecta_da_base_de_dados()
try:
faz_coisas_perigosas()
except FalhaEsperadaException:
trata_falha_comum()
except:
trata_todas_as_outras_falhas()
raise
finally:
limpa_o_lixo()
EXCEÇÕESEXCEÇÕES
raise NotImplementedError('Caso não implementado')
raise RuntimeError('Deu errado.')
BÁSICOBÁSICO
Variáveis e Tipos
Decisão
Repetição
Exceções
Módulos
Classes
Funções
FUNÇÕESFUNÇÕES
def nome_da_funcao():
print u'O retorno padrão é None'
def soma(a, b):
return a+b
>>> def soma_muitos(*numeros): # *args
... total = 0
... for numero in numeros:
... total += numero
... return total
>>> soma_muitos(1, 2, 3, 4)
10
FUNÇÕESFUNÇÕES
def soma_ou_subtrai(a, b, operacao='soma'):
if operacao == 'soma':
return a+b
elif operacao == 'subtracao':
return a-b
else:
raise NotImplementedError('Como faz "%s"?' % operacao)
>>> soma_ou_subtrai(1, 2)
3
>>> soma_ou_subtrai(3, 4, operacao='subtracao')
-1
>>> soma_ou_subtrai(5, 6, operacao='divisao')
Traceback (most recent call last)
(...)
NotImplementedError: Como faz "divisao"?
FUNÇÕESFUNÇÕES
def soma(a, b):
return a+b
def multiplicacao(a, b):
return a*b
def faz_uma_conta(a, b, conta=soma):
return conta(a, b)
>>> faz_uma_conta(3, 4) # conta=soma
7
>>> faz_uma_conta(3, 4, conta=multiplicacao)
12
>>> faz_uma_conta(3, 4, multiplicacao) # conta=multiplicacao
12
como parâmetro de funções
É 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)
FUNÇÕESFUNÇÕES
def soma(a, b):
return a+b
def multiplicacao(a, b):
return a*b
def faz_contas(a, b, **contas): # **kwargs
for nome, funcao in contas.items():
print 'Conta: %s %s %s' % (a, nome, b)
print 'Resultado: %s' % funcao(a,b)
>>> faz_contas(3, 4, mais=soma, vezes=multiplicacao)
Conta: 3 mais 4
Resultado: 7
Conta: 3 vezes 4
Resultado: 12
BÁSICOBÁSICO
Variáveis e Tipos
Decisão
Repetição
Exceções
Funções
Classes
Módulos
MÓDULOSMÓDULOS
import modulo
# funcoes.py
# coding: utf-8
def soma(a, b):
return a+b
def subtracao(a, b):
return a-b
def multiplicacao(a, b):
return a*b
def divisao(a, b):
return a/b
# print u'módulo pronto!'
import funcoes
funcoes.soma(3, 4)
from funcoes import soma
soma(3, 4)
from funcoes import soma as mais
mais(3, 4)
from funcoes import soma, subtracao
subtracao(5, 4)
from funcoes import (soma, divisao,
multiplicacao)
MÓDULOSMÓDULOS
from funcoes import soma
# funcoes.py
# coding: utf-8
def soma(a, b):
return a+b
def subtracao(a, b):
return a-b
def multiplicacao(a, b):
return a*b
def divisao(a, b):
return a/b
# print u'módulo pronto!'
main.py
funcoes/
└── __init__.py # <- código aqui
main.py
funcoes.py # <- código aqui
main.py
funcoes/
├── __init__.py # <- arquivo vazio
├── aumentam.py # <- soma, multi
└── diminuem.py # <- subt. divisao
# funcoes/__init__.py
# coding: utf-8
def soma(a, b):
return a+b
def subtracao(a, b):
return a-b
def multiplicacao(a, b):
return a*b
def divisao(a, b):
return a/b
# print u'módulo pronto!'
# funcoes/aumentam.py
def soma(a, b):
return a+b
def multiplicacao(a, b):
return a*b
# funcoes/diminuem.py
def subtracao(a, b):
return a-b
def divisao(a, b):
return a/b
from funcoes.aumentam import soma
# main.py
from funcoes import soma
# main.py
from funcoes.aumentam import soma
BÁSICOBÁSICO
Variáveis e Tipos
Decisão
Repetição
Exceções
Funções
Módulos
Classes
CLASSES PYTHONCLASSES PYTHON
Tudo é objeto
Descoberta de métodos/atributos
Classes simples
Herança múltipla
Duck typing
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
Módulo
contém as funções: e
__builtin__
help() dir()
DESCOBERTA DEDESCOBERTA DE
MÉTODOS E ATRIBUTOSMÉTODOS E ATRIBUTOS
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
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
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
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)
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'
MOTIVAÇÃOMOTIVAÇÃO
BÁSICOBÁSICO
EXTRASEXTRAS
WEBWEB
# coding: utf-8
from flask import Flask # pip install flask
app = Flask(__name__)
@app.route('/')
def hello():
return '<h1>Hello World!</h1>'
@app.route('/vezesdois/<int:numero>/')
def vezes_dois(numero):
resposta = numero * 2
return '<h1> %s </h1>' % str(resposta)
if __name__ == '__main__':
# app.debug = True
app.run()
MOTIVAÇÃOMOTIVAÇÃO
BÁSICOBÁSICO
WEBWEB
EXTRASEXTRAS
HEROKUHEROKU
PROGRAMAÇÃOPROGRAMAÇÃO
FUNCIONALFUNCIONAL
??
PERGUNTASPERGUNTAS
alan.justino@yahoo.com.br
@alanjds
"QUERIA QUE TIVESSEM ME"QUERIA QUE TIVESSEM ME
CONTADO ANTES"CONTADO ANTES"
(fonte: )http://slides.com/chrissim/deck#/10
-- Allen & Chris, Pycon 2015 --
"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?
PRÓXIMA ESTAÇÃOPRÓXIMA ESTAÇÃO
Evernote:
https://www.evernote.com/referral/Registration.action?
uid=7061982&sig=8f288240c4119c5fe5e3a0ef401ab29a
Curso:
https://www.evernote.com/l/AD26fy9bIbxK8YTFof-4Eo-a-
J4pQkWd8mo
EMPIRE OF CODEEMPIRE OF CODE
http://www.checkio.org/
Venha para a Boo
ENVIE À BOOENVIE À BOO
Envie para contato@boolabs.com.br
OBRIGADOOBRIGADO
alan.justino@yahoo.com.br
@alanjds
PERGUNTAS:PERGUNTAS:
slides.com/alanjds/python/
SLIDES:SLIDES:

Mais conteúdo relacionado

Mais procurados

Curso java 01 - molhando os pés com java
Curso java   01 - molhando os pés com javaCurso java   01 - molhando os pés com java
Curso java 01 - molhando os pés com javaMaurício Linhares
 
Python para quem sabe Python (aula 2)
Python para quem sabe Python (aula 2)Python para quem sabe Python (aula 2)
Python para quem sabe Python (aula 2)Luciano Ramalho
 
Python: Iteraveis, geradores etc
Python: Iteraveis, geradores etcPython: Iteraveis, geradores etc
Python: Iteraveis, geradores etcLuciano Ramalho
 
Curso java 06 - mais construtores, interfaces e polimorfismo
Curso java   06 - mais construtores, interfaces e polimorfismoCurso java   06 - mais construtores, interfaces e polimorfismo
Curso java 06 - mais construtores, interfaces e polimorfismoMaurício Linhares
 
Python: a primeira mordida
Python: a primeira mordidaPython: a primeira mordida
Python: a primeira mordidaLuciano Ramalho
 
Iteraveis e geradores em Python
Iteraveis e geradores em PythonIteraveis e geradores em Python
Iteraveis e geradores em PythonLuciano Ramalho
 
Orientação a Objetos em PHP
Orientação a Objetos em PHPOrientação a Objetos em PHP
Orientação a Objetos em PHPzehzinho
 
Objetos Pythonicos - compacto
Objetos Pythonicos - compactoObjetos Pythonicos - compacto
Objetos Pythonicos - compactoLuciano Ramalho
 
Perl Moderno, dia2
Perl Moderno, dia2Perl Moderno, dia2
Perl Moderno, dia2garux
 
Perl Moderno, dia4
Perl Moderno, dia4Perl Moderno, dia4
Perl Moderno, dia4garux
 
Perl Moderno, dia5
Perl Moderno, dia5Perl Moderno, dia5
Perl Moderno, dia5garux
 
[Curso Java Basico] Aula 63: printf
[Curso Java Basico] Aula 63: printf[Curso Java Basico] Aula 63: printf
[Curso Java Basico] Aula 63: printfLoiane Groner
 
Orientação a Objetos em Python
Orientação a Objetos em PythonOrientação a Objetos em Python
Orientação a Objetos em PythonLuciano Ramalho
 
Introdução ao Framework Grails
Introdução ao Framework GrailsIntrodução ao Framework Grails
Introdução ao Framework GrailsBruno Catão
 

Mais procurados (20)

Curso java 01 - molhando os pés com java
Curso java   01 - molhando os pés com javaCurso java   01 - molhando os pés com java
Curso java 01 - molhando os pés com java
 
Python para quem sabe Python (aula 2)
Python para quem sabe Python (aula 2)Python para quem sabe Python (aula 2)
Python para quem sabe Python (aula 2)
 
Python: Iteraveis, geradores etc
Python: Iteraveis, geradores etcPython: Iteraveis, geradores etc
Python: Iteraveis, geradores etc
 
Curso java 06 - mais construtores, interfaces e polimorfismo
Curso java   06 - mais construtores, interfaces e polimorfismoCurso java   06 - mais construtores, interfaces e polimorfismo
Curso java 06 - mais construtores, interfaces e polimorfismo
 
Python: a primeira mordida
Python: a primeira mordidaPython: a primeira mordida
Python: a primeira mordida
 
Iteraveis e geradores em Python
Iteraveis e geradores em PythonIteraveis e geradores em Python
Iteraveis e geradores em Python
 
Orientação a Objetos em PHP
Orientação a Objetos em PHPOrientação a Objetos em PHP
Orientação a Objetos em PHP
 
Aprendendo ruby
Aprendendo rubyAprendendo ruby
Aprendendo ruby
 
Objetos Pythonicos - compacto
Objetos Pythonicos - compactoObjetos Pythonicos - compacto
Objetos Pythonicos - compacto
 
Python
PythonPython
Python
 
Python 02
Python 02Python 02
Python 02
 
Python 01
Python 01Python 01
Python 01
 
Perl Moderno, dia2
Perl Moderno, dia2Perl Moderno, dia2
Perl Moderno, dia2
 
Perl Moderno, dia4
Perl Moderno, dia4Perl Moderno, dia4
Perl Moderno, dia4
 
Perl Moderno, dia5
Perl Moderno, dia5Perl Moderno, dia5
Perl Moderno, dia5
 
Meta-programacao em python
Meta-programacao em pythonMeta-programacao em python
Meta-programacao em python
 
[Curso Java Basico] Aula 63: printf
[Curso Java Basico] Aula 63: printf[Curso Java Basico] Aula 63: printf
[Curso Java Basico] Aula 63: printf
 
Orientação a Objetos em Python
Orientação a Objetos em PythonOrientação a Objetos em Python
Orientação a Objetos em Python
 
Introdução ao Framework Grails
Introdução ao Framework GrailsIntrodução ao Framework Grails
Introdução ao Framework Grails
 
Aula Prolog 02
Aula Prolog 02Aula Prolog 02
Aula Prolog 02
 

Destaque (20)

B2 2-albert chen
B2 2-albert chenB2 2-albert chen
B2 2-albert chen
 
Cleaning Out Your IT Closet - SPSRED 2013
Cleaning Out Your IT Closet - SPSRED 2013Cleaning Out Your IT Closet - SPSRED 2013
Cleaning Out Your IT Closet - SPSRED 2013
 
Torax
ToraxTorax
Torax
 
Inserire ultimi articoli su blogger
Inserire ultimi articoli su bloggerInserire ultimi articoli su blogger
Inserire ultimi articoli su blogger
 
____
  ____  ____
____
 
How To Get Your Startup Funded By A VC
How To Get Your Startup Funded By A VCHow To Get Your Startup Funded By A VC
How To Get Your Startup Funded By A VC
 
「アンケート」=「一者一択の踏み絵」 長野市役所の説
「アンケート」=「一者一択の踏み絵」 長野市役所の説「アンケート」=「一者一択の踏み絵」 長野市役所の説
「アンケート」=「一者一択の踏み絵」 長野市役所の説
 
Mobilediagnosis 2015
Mobilediagnosis 2015 Mobilediagnosis 2015
Mobilediagnosis 2015
 
Apna Bazaar India
Apna Bazaar IndiaApna Bazaar India
Apna Bazaar India
 
Aspek spiritual resort based management
Aspek spiritual resort based managementAspek spiritual resort based management
Aspek spiritual resort based management
 
MobileDiagnosis 2013
MobileDiagnosis 2013 MobileDiagnosis 2013
MobileDiagnosis 2013
 
New era
New eraNew era
New era
 
Parle-G campaign- The future genius
Parle-G campaign- The future geniusParle-G campaign- The future genius
Parle-G campaign- The future genius
 
#malafimmina® jewels
#malafimmina® jewels#malafimmina® jewels
#malafimmina® jewels
 
E cote solutions ltd
E cote solutions ltdE cote solutions ltd
E cote solutions ltd
 
Quote Collector
Quote CollectorQuote Collector
Quote Collector
 
Social Media
Social MediaSocial Media
Social Media
 
Testing 4
Testing 4Testing 4
Testing 4
 
Open source พื้นฐานที่ควรมี
Open source พื้นฐานที่ควรมีOpen source พื้นฐานที่ควรมี
Open source พื้นฐานที่ควรมี
 
Agile testing organizational mindshift
Agile testing organizational mindshiftAgile testing organizational mindshift
Agile testing organizational mindshift
 

Semelhante a Minicurso: Python em 4 horas - FATEC SCS 2015

Introducao ao python - Luciana Mota
Introducao ao python - Luciana MotaIntroducao ao python - Luciana Mota
Introducao ao python - Luciana Motalucianacmota
 
Introdução à Linguagem de programação Python
Introdução à Linguagem de programação PythonIntrodução à Linguagem de programação Python
Introdução à Linguagem de programação Pythondmmartins
 
Python 3.x - Ihh.. E agora ? Como faço ?
Python 3.x - Ihh.. E agora ? Como faço ?Python 3.x - Ihh.. E agora ? Como faço ?
Python 3.x - Ihh.. E agora ? Como faço ?Marcel Caraciolo
 
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop Python
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop PythonIEEEweek 2017 @ DETI Univ. Aveiro - Workshop Python
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop PythonDiogo Gomes
 
Bogosort e Técnicas Realmente Avançadas de Programação
Bogosort e Técnicas Realmente Avançadas de ProgramaçãoBogosort e Técnicas Realmente Avançadas de Programação
Bogosort e Técnicas Realmente Avançadas de ProgramaçãoRodolpho Eckhardt
 
Desenvolvendo com mongodb
Desenvolvendo com mongodbDesenvolvendo com mongodb
Desenvolvendo com mongodbThiago Avelino
 
Aulas de estrutura de dados por Ayrton Yagami
Aulas de estrutura de dados por Ayrton YagamiAulas de estrutura de dados por Ayrton Yagami
Aulas de estrutura de dados por Ayrton YagamiAyrton Yagami
 
Estruturas de dados em Python
Estruturas de dados em PythonEstruturas de dados em Python
Estruturas de dados em PythonRicardo Paiva
 
Minicurso-Python-01.pptx
Minicurso-Python-01.pptxMinicurso-Python-01.pptx
Minicurso-Python-01.pptxPapirusDig
 
Python Introdução e Orientação a Objetos.pdf
Python Introdução e Orientação a Objetos.pdfPython Introdução e Orientação a Objetos.pdf
Python Introdução e Orientação a Objetos.pdfMarioAthayde
 
De Zero à Web com Python e Django
De Zero à Web com Python e DjangoDe Zero à Web com Python e Django
De Zero à Web com Python e DjangoOsvaldo Santana Neto
 
Minicurso de Django - Desenvolvimento ágil web com Django e Python
Minicurso de Django - Desenvolvimento ágil web com Django e PythonMinicurso de Django - Desenvolvimento ágil web com Django e Python
Minicurso de Django - Desenvolvimento ágil web com Django e PythonGuilherme Garcia
 
Aprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaAprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaFelipe Pedroso
 
Python em (mais de) 10 minutinhos
Python em (mais de) 10 minutinhosPython em (mais de) 10 minutinhos
Python em (mais de) 10 minutinhosRudá Moura
 
Introdução à Programação em Python
Introdução à Programação em PythonIntrodução à Programação em Python
Introdução à Programação em PythonRodrigo Hübner
 
Python e tipagem estática
Python e tipagem estáticaPython e tipagem estática
Python e tipagem estáticaVinta Software
 

Semelhante a Minicurso: Python em 4 horas - FATEC SCS 2015 (20)

Introducao ao python - Luciana Mota
Introducao ao python - Luciana MotaIntroducao ao python - Luciana Mota
Introducao ao python - Luciana Mota
 
Introdução à Linguagem de programação Python
Introdução à Linguagem de programação PythonIntrodução à Linguagem de programação Python
Introdução à Linguagem de programação Python
 
Python 3.x - Ihh.. E agora ? Como faço ?
Python 3.x - Ihh.. E agora ? Como faço ?Python 3.x - Ihh.. E agora ? Como faço ?
Python 3.x - Ihh.. E agora ? Como faço ?
 
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop Python
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop PythonIEEEweek 2017 @ DETI Univ. Aveiro - Workshop Python
IEEEweek 2017 @ DETI Univ. Aveiro - Workshop Python
 
Bogosort e Técnicas Realmente Avançadas de Programação
Bogosort e Técnicas Realmente Avançadas de ProgramaçãoBogosort e Técnicas Realmente Avançadas de Programação
Bogosort e Técnicas Realmente Avançadas de Programação
 
Desenvolvendo com mongodb
Desenvolvendo com mongodbDesenvolvendo com mongodb
Desenvolvendo com mongodb
 
Aulas de estrutura de dados por Ayrton Yagami
Aulas de estrutura de dados por Ayrton YagamiAulas de estrutura de dados por Ayrton Yagami
Aulas de estrutura de dados por Ayrton Yagami
 
Estruturas de dados em Python
Estruturas de dados em PythonEstruturas de dados em Python
Estruturas de dados em Python
 
Minicurso-Python-01.pptx
Minicurso-Python-01.pptxMinicurso-Python-01.pptx
Minicurso-Python-01.pptx
 
Python Introdução e Orientação a Objetos.pdf
Python Introdução e Orientação a Objetos.pdfPython Introdução e Orientação a Objetos.pdf
Python Introdução e Orientação a Objetos.pdf
 
De Zero à Web com Python e Django
De Zero à Web com Python e DjangoDe Zero à Web com Python e Django
De Zero à Web com Python e Django
 
Minicurso de Django - Desenvolvimento ágil web com Django e Python
Minicurso de Django - Desenvolvimento ágil web com Django e PythonMinicurso de Django - Desenvolvimento ágil web com Django e Python
Minicurso de Django - Desenvolvimento ágil web com Django e Python
 
Dojo de Python
Dojo de PythonDojo de Python
Dojo de Python
 
Aprendendo Kotlin na Prática
Aprendendo Kotlin na PráticaAprendendo Kotlin na Prática
Aprendendo Kotlin na Prática
 
Introdução a python
Introdução a pythonIntrodução a python
Introdução a python
 
Minicurso de jQuery
Minicurso de jQueryMinicurso de jQuery
Minicurso de jQuery
 
Python em (mais de) 10 minutinhos
Python em (mais de) 10 minutinhosPython em (mais de) 10 minutinhos
Python em (mais de) 10 minutinhos
 
Introdução à Programação em Python
Introdução à Programação em PythonIntrodução à Programação em Python
Introdução à Programação em Python
 
Pilha e Fila Estática
Pilha e Fila EstáticaPilha e Fila Estática
Pilha e Fila Estática
 
Python e tipagem estática
Python e tipagem estáticaPython e tipagem estática
Python e tipagem estática
 

Minicurso: Python em 4 horas - FATEC SCS 2015

  • 1. EM 4 HORASEM 4 HORASPYTHONPYTHON Alan Justino da Silva alan.justino@yahoo.com.br @alanjds slides.com/alanjds/python/live
  • 4. MOTIVAÇÃOMOTIVAÇÃO Por que Python? Como é o código Python? Quem usa Python?
  • 5.
  • 6. QUEM USA PYTHON?QUEM USA PYTHON?
  • 7. QUEM USA PYTHON?QUEM USA PYTHON?
  • 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
  • 9. MOTIVAÇÃOMOTIVAÇÃO Quem usa Python? Como é o código Python? Por que Python?
  • 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
  • 18. MOTIVAÇÃOMOTIVAÇÃO Quem usa Python? Por que Python? Como é o código Python?
  • 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
  • 25. TRUE, FALSE, NONETRUE, FALSE, NONE >>> True, False (True, False) >>> bool(True), bool(1), bool('texto') (True, True, True) >>> bool(False), bool(0), bool(''), bool(None) (False, False, False, False) >>> bool('False'), bool(-1), bool(' ') (True, True, True)
  • 26. TEXTOTEXTO >>> 'texto', "texto", type('texto') ('texto', 'texto', str) >>> u'texto com acentuação', type(u'texto') (u'texto com acentuaxe7xe3o', unicode) >>> 'texto' + 'com' + 'texto' 'textocomtexto' >>> """texto de muitas linhas""" 'texto den muitasn linhas' >>> u'texto mesclado: %s %s %s %s %s' % (1, '+', 1, '=', 1+1) u'texto mesclado: 1 + 1 = 2'
  • 27. NÚMEROSNÚMEROS >>> type(123), type(3.14), type(5+2j) (int, float, complex) >>> float(123), int(3.14), complex(123) (123.0, 3, 123+0j) >>> int('3'), float('5'), float('+inf') (3, 5.0, inf) >>> float('inf') - 10*1000 inf >>> float('inf') + float('inf') + float('inf') inf >>> float('inf') - float('inf') nan
  • 28. NÚMEROSNÚMEROS >>> 1+1 2 >>> 2*2 4 >>> 3**2 9 >>> 5/2 2 >>> 5%2 1 >>> round(3.14) 3.0 >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(16) 4.0 >>> math.sqrt(15) 3.872983346207417 >>> math.floor(3.14) 3.0 >>> math.ceil(3.14) 4.0
  • 29. LISTAS E TUPLASLISTAS E TUPLAS >>> [1,2,3] + [3,4,5,6] [1, 2, 3, 3, 4, 5, 6] >>> lista = [] # list() >>> lista.append(123) >>> lista += [456] >>> lista [123, 456] >>> lista[0] 123 >>> 123 in lista True >>> lista.pop(123) 123 >>> 123 in lista False >>> (1,2,3) + (3, 4,5,6) (1, 2, 3, 3, 4, 5, 6) >>> tupla = () # tuple() >>> tupla.append(123) AttributeError: 'tuple' object has no 'append' >>> tupla = (123, 456) >>> tupla (123, 456) >>> tupla[0] 123 >>> 123 in tupla True >>> list(tupla) [123, 456]
  • 30. DICTDICT >>> dicionario = {} # dict() >>> cores_css = {'azul': '#0000FF', 'laranja': '#FFA500'} >>> frutas_en = {u'maçã': 'apple', 'laranja': 'orange'} >>> numeros = {'um': 1, 'pi': 3.14, 0: 'zero', None: None} >>> cores_css['azul'] '#0000FF' >>> numeros[0] 'zero' >>> cores_css['laranja'] == frutas_en['laranja'] False >>> numeros.keys() # não garante ordem ['um', 0, 'pi', None] >>> numeros.values() # não garante ordem [1, 'zero', 3.14, None] >>> numeros.items() # não garante ordem [('um', 1), (0, 'zero'), ('pi', 3.14), (None, None)] ( )Vetor Associativo
  • 31. SETSET >>> conjunto_a = {1, 2, 3} # set([1,2,3]) >>> conjunto_b = {3, 4, 5, 6} >>> conjunto_a.union(conjunto_b) {1, 2, 3, 4, 5, 6} >>> conjunto_a.update(123) >>> conjunto_a {1, 2, 3, 123} >>> 123 in conjunto_a True ( )Conjunto sem repetições
  • 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
  • 38. >>> for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]: ... print a/b 1 2 3 ZeroDivisionError Traceback (most recent call last) <ipython-input-15-5be9e7c9049a> in <module>() 1 for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]: --> 2 print a/b ZeroDivisionError: integer division or modulo by zero >>> for a,b in [(5,3), (4,2), (3,1), (2,0), (1,-1)]: ... try: ... print a/b ... except ZeroDivisionError: ... print 'infinito' ... except Exception as error: ... print 'Erro inesperado:', error 1 2 3 'infinito' -1 EXCEÇÕESEXCEÇÕES >>> a, b = 1, 0 >>> c = a/b ZeroDivisionError: integer division or modulo by zero
  • 39. EXCEÇÕESEXCEÇÕES conecta_na_base_de_dados() try: faz_algo_perigoso() except Exception as error: print u'Erro: Não consegui fazer "algo perigoso"' raise error finally: desconecta_da_base_de_dados() try: faz_coisas_perigosas() except FalhaEsperadaException: trata_falha_comum() except: trata_todas_as_outras_falhas() raise finally: limpa_o_lixo()
  • 40. EXCEÇÕESEXCEÇÕES raise NotImplementedError('Caso não implementado') raise RuntimeError('Deu errado.')
  • 42. FUNÇÕESFUNÇÕES def nome_da_funcao(): print u'O retorno padrão é None' def soma(a, b): return a+b >>> def soma_muitos(*numeros): # *args ... total = 0 ... for numero in numeros: ... total += numero ... return total >>> soma_muitos(1, 2, 3, 4) 10
  • 43. FUNÇÕESFUNÇÕES def soma_ou_subtrai(a, b, operacao='soma'): if operacao == 'soma': return a+b elif operacao == 'subtracao': return a-b else: raise NotImplementedError('Como faz "%s"?' % operacao) >>> soma_ou_subtrai(1, 2) 3 >>> soma_ou_subtrai(3, 4, operacao='subtracao') -1 >>> soma_ou_subtrai(5, 6, operacao='divisao') Traceback (most recent call last) (...) NotImplementedError: Como faz "divisao"?
  • 44. FUNÇÕESFUNÇÕES def soma(a, b): return a+b def multiplicacao(a, b): return a*b def faz_uma_conta(a, b, conta=soma): return conta(a, b) >>> faz_uma_conta(3, 4) # conta=soma 7 >>> faz_uma_conta(3, 4, conta=multiplicacao) 12 >>> faz_uma_conta(3, 4, multiplicacao) # conta=multiplicacao 12 como parâmetro de funções
  • 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)
  • 46. FUNÇÕESFUNÇÕES def soma(a, b): return a+b def multiplicacao(a, b): return a*b def faz_contas(a, b, **contas): # **kwargs for nome, funcao in contas.items(): print 'Conta: %s %s %s' % (a, nome, b) print 'Resultado: %s' % funcao(a,b) >>> faz_contas(3, 4, mais=soma, vezes=multiplicacao) Conta: 3 mais 4 Resultado: 7 Conta: 3 vezes 4 Resultado: 12
  • 48. MÓDULOSMÓDULOS import modulo # funcoes.py # coding: utf-8 def soma(a, b): return a+b def subtracao(a, b): return a-b def multiplicacao(a, b): return a*b def divisao(a, b): return a/b # print u'módulo pronto!' import funcoes funcoes.soma(3, 4) from funcoes import soma soma(3, 4) from funcoes import soma as mais mais(3, 4) from funcoes import soma, subtracao subtracao(5, 4) from funcoes import (soma, divisao, multiplicacao)
  • 49. MÓDULOSMÓDULOS from funcoes import soma # funcoes.py # coding: utf-8 def soma(a, b): return a+b def subtracao(a, b): return a-b def multiplicacao(a, b): return a*b def divisao(a, b): return a/b # print u'módulo pronto!' main.py funcoes/ └── __init__.py # <- código aqui main.py funcoes.py # <- código aqui main.py funcoes/ ├── __init__.py # <- arquivo vazio ├── aumentam.py # <- soma, multi └── diminuem.py # <- subt. divisao # funcoes/__init__.py # coding: utf-8 def soma(a, b): return a+b def subtracao(a, b): return a-b def multiplicacao(a, b): return a*b def divisao(a, b): return a/b # print u'módulo pronto!' # funcoes/aumentam.py def soma(a, b): return a+b def multiplicacao(a, b): return a*b # funcoes/diminuem.py def subtracao(a, b): return a-b def divisao(a, b): return a/b from funcoes.aumentam import soma # main.py from funcoes import soma # main.py from funcoes.aumentam import soma
  • 51. CLASSES PYTHONCLASSES PYTHON Tudo é objeto Descoberta de métodos/atributos Classes simples Herança múltipla Duck typing
  • 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'
  • 60. # coding: utf-8 from flask import Flask # pip install flask app = Flask(__name__) @app.route('/') def hello(): return '<h1>Hello World!</h1>' @app.route('/vezesdois/<int:numero>/') def vezes_dois(numero): resposta = numero * 2 return '<h1> %s </h1>' % str(resposta) if __name__ == '__main__': # app.debug = True app.run()
  • 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?
  • 67.
  • 69. EMPIRE OF CODEEMPIRE OF CODE http://www.checkio.org/
  • 71. ENVIE À BOOENVIE À BOO Envie para contato@boolabs.com.br