Loading

Python em 4 horas

alanjds

This is a live streamed presentation. You will automatically follow the presenter and see the slide they're currently on.

Python em 4 horas

Alan Justino da Silva

alan.justino@yahoo.com.br

@alanjds

Motivação
Básico

WEB

EXTRAS

Motivação
Básico

WEB

EXTRAS

Motivação

Quem usa Python?

Quem usa Python?

Quem usa Python?

  • Google Search
  • Youtube
  • Dropbox
  • Instagram
  • Pinterest
  • Rdio (server)
  • Spotify (server)
  • NewRelic
  • PayPal & eBay
  • JPMorgan
  • Bank of America
  • Battlefield (server)
  • Civilization IV
  • Second Life (IBM)
  • Globo.com
  • Magazine Luiza

e muitos outros

Motivação

Por que Python?

P: Que problema Python tenta resolver?

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 que Python?

(...) programmer productivity measured in lines of code perhour (LOC/hour) is roughly independent of the programming language. (PRECHELT, 2010)

Por que Python?

[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 maintainability of code is what counts most: 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)

  • Facil escrita de código (baixa curva de aprendizagem)
  • Fácil leitura e modificação de código (manutenção)

Por que Python?

Fácil Manutenção

(Tim Peters, 2004)

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 darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import this

como filosofia!

Por que Python?

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!

PEP 0008 -- Style Guide for Python Code

Por que Python?

Interpretado

XKCD 303: Compiling

Por que Python?

Interpretado

REPL: Read–Eval–Print-Loop

Por que Python?

Muitas Bibliotecas Disponíveis

XKCD 353: Python

Python Package Index (PyPI)

Motivação

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?

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ção
Básico

WEB

EXTRAS

Básico

Variá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

Dinâ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 Forte

True, 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)

Texto

>>> 'texto', "texto", type('texto')
('texto', 'texto', str)

>>> u'texto com acentuação', type(u'texto')
(u'texto com acentua\xe7\xe3o', unicode)

>>> 'texto' + 'com' + 'texto'
'textocomtexto'

>>> """texto de
        muitas
         linhas"""
'texto de\n        muitas\n         linhas'

>>> u'texto mesclado: %s %s %s %s %s' % (1, '+', 1, '=', 1+1)
u'texto mesclado: 1 + 1 = 2'

Nú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ú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 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]

DICT

>>> 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)]

Set

>>> 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

Básico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

Decisão: IF

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ásico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

Repetiçã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çã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.items():
    print 'Keyword:', key
    print 'Valor:', val
from zipfile import ZipFile
for linha in ZipFile.open('/tmp/arquivo.zip'):
    print linha

Básico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

ExceÇões

>>> 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
>>> a, b = 1, 0
>>> c = a/b
ZeroDivisionError: integer division or modulo by zero
>>> 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

EXCEÇÕ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ÇÕES

raise NotImplementedError('Caso não implementado')
raise RuntimeError('Deu errado.')

Básico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

Funçõ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çõ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çõ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

Tudo é Objeto

Inclusive funções

Função: objeto que tem o método __call__

funcao(a, b) <-> funcao.__call__(a, b)

Funçõ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ásico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

Mó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ó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ásico

  • Variáveis e Tipos
  • Decisão
  • Repetição
  • Exceções
  • Funções
  • Módulos
  • Classes

Classes Python

  • Tudo é objeto
  • Descoberta de métodos/atributos
  • Classes simples
  • Herança múltipla
  • Duck typing

Tudo é 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 __builtin__

contém as funções: help() e dir()

Descoberta de Métodos e Atributos

Classes 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.met()
chamando de B.met...
chamando de A.met...
(1, 2)
>>> isinstance(outra, A)
True
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

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)

>>> 2 * 3
6
>>> 'dois' * 3
'doisdoisdois'

int e str implementam __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 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'
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

Motivação
Básico

WEB

EXTRAS

# 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ção
Básico

WEB

EXTRAS

Heroku

Programação Funcional

Perguntas

alan.justino@yahoo.com.br

@alanjds

?

"queria que tivessem me contado antes"

-- Allen & Chris, Pycon 2015 --

"queria que tivessem me 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ção

Venha para a Boo

1) FizzBuzz: (http://j.mp/boo-fizzbuzz)
Imprimir na tela uma lista de 1 a 100, um "número" por linha, respeitando a regra do FizzBuzz

4) Números Primos: (http://j.mp/boo-primos)
"Primo" é o número natural, maior que um e divisível apenas por 1 e por si mesmo. Faça uma função que encontre o 40º número primo.

3) Ordenação:
Faça uma função que receba uma sequência e retorne os elementos ordenados. Exemplo: [1, -1, 0, 8, 3, -5, 0, 6, 7]

2) Sequencia de Fibonacci:

 

 


Escreva uma função que diga o 40º e 100º elemento da sequência.

Envie à BOO

Obrigado

alan.justino@yahoo.com.br

Perguntas:

Slides:

Made with Slides.com