Conhecendo o Python

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    Conhecendo o Python - Presentation Transcript

    1. Conhecendo o Python 'Hello world'.replace('world', 'python') Arthur Furlan arthur.furlan@gmail.com http://arthurfurlan.org CI214 – Estruturas de Linguagem de Programação (UFPR)
    2. shit mistakes happens!
    3. Características gerais ● Criada por Guido van Rossum em 1991 ● Usada em grandes empresas: Google, Yahoo, Youtube, AppEngine, DreamWorks, Nokia, Red Hat, Canonical, Novell, Mandriva, CIA, Governo Brasileiro (http://www.brasil.gov.br) ● Linguagem de código aberto, compatível com a GPL ● Linguagem de propósito geral ● Linguagem de altíssimo nível (VHLL) ● Linguagem multiparadigma ● Linguagem multiplataforma ● Linguagem híbrida ● Linguagem de cola
    4. Características gerais ● Sintaxe simples e fácil de ser assimiliada ● Foco na simplicidade e legibilidade ● Tipagem dinâmica (duck 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.” ● Tipagem forte ● Passagem de parametros: “referência por valor” ● Associação de parametros: posicional, nominal e opicional ● Suporta herança múltipla
    5. The Zen of Python afurlan@merlin:~$ python >>> import this 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! >>>
    6. talk is cheap, show me the code!
    7. Variáveis ● Variáveis contém referências a objetos ● Variáveis não têm tipo, objetos tem tipos ● Não existe “criação automática” de variáveis ● Variáveis são como post-its (ou rótulos) ● Atribuir valor é o mesmo que colar um rotulo no valor a = [1,2,3] b=a a a b [1,2,3] [1,2,3]
    8. Atribuição ● Atribuição simples: ● reais = euros * taxa ● Atribuição com operação: ● a += 10 ● Atribuição múltipla: ● x=y=z=0 ● Atribuição posicional de itens de sequências: ● a,b,c = lista ● i,j = j,i
    9. Tipos de dados básicos ● Números: int, long, float, complex ● Strings: str e unicode ● Listas e tuplas: list, tuple ● Dicionários: dict ● Arquivos: file ● Booleanos: bool (True, False) ● Conjuntos: set, frozenset ● None
    10. Blocos por indentação dois-pontos marca o início do bloco for i in range(1,11): indentação dentro j = i*i do bloco deve ser constante* print i, j print 'FIM' retorno ao nível anterior de indentação marca o final do bloco * por convenção, usa-se 4 espaços por nível (mas basta ser consistente)
    11. Blocos ● Todos os comandos que aceitam blocos: ● if/elif/else ● try/except ● for/else ● try/finally ● while/else ● class ● def ● Se o bloco tem apenas um comando, pode-se escrever tudo em uma linha: if n < 0: print 'Valor inválido'
    12. Listas ● Coleções de itens heterogêneos que podem ser acessados sequencialmente ou diretamente através de índice numérico. ● Constantes do tipo lista são delimitadas por colchetes []. a = [] b = [1,10,7,5] c = ['casa',43,b,[9,8,7],u'coisa']
    13. Abrangência de listas ● Sintaxe emprestada da linguagem funcional Haskell ● Processar todos os elementos: l = [1,-2,3,-1,-3,4] l2 = [n*10 for n in l]
    14. Abrangência de listas ● Filtrar alguns elementos: l3 = [n for n in l if n > 0] ● Processar e filtrar: l4 = [n*10 for n in l if n > 0]
    15. Argumentos de funções ● Valores default indicam argumentos opcionais ● Argumentos obrigatórios vêm antes de argumentos opcionais def exibir(texto, estilo=None, cor='preto'): ● Palavras-chave podem ser usadas como argumentos fora de ordem ● Como a função acima pode ser invocada: exibir('abacaxi') exibir('abacaxi', 'negrito', 'amarelo') exibir('abacaxi', cor='azul')
    16. Herança múltipla class ContadorTolerante(Contador): def contar(self, item): return self.dic.get(item, 0) class ContadorTotalizador(Contador): def __init__(self): super(ContadorTotalizador, self).__init__() self.total = 0 def incluir(self, item): super(ContadorTotalizador, self).incluir(item) self.total += 1 class ContadorTT(ContadorTotalizador,ContadorTolerante): pass ● pass indica um bloco vazio
    17. Palavras reservadas ● and ● elif ● global ● or ● assert ● else ● if ● pass ● break ● except ● import ● print ● class ● exec ● in ● raise ● continue ● finally ● is ● return ● def ● for ● lambda ● try ● del ● from ● not ● while ● yield
    18. Aprendendo a aprender ● Use o interpretador interativo! ● Determinar o tipo de um objeto: ● type(obj) ● Ver docs de uma classe ou comando ● help(list) ● Obter uma lista de (quase) todos os atributos de um objeto ● dir(list) ● Listar símbolos do escopo corrente ● dir()
    19. O último exemplo >>> fib = lambda x: x if x < 2 else fib(x-1)+fib(x-2) >>> for i in xrange(10): ... print fib(i) ... 0 1 1 2 3 5 8 13 21 34 >>>
    20. Créditos Apresentação desenvolvida a partir dos materiais de: ● Marco André Lopes Mendes <marco@sociesc.org.br> ● Luciano Ramalho <luciano@occam.com.br>
    21. python.mordida[0] Arthur Furlan arthur.furlan@gmail.com http://arthurfurlan.org
    SlideShare Zeitgeist 2009

    + Arthur FurlanArthur Furlan Nominate

    custom

    78 views, 0 favs, 0 embeds more stats

    This presentation describes some main characteristi more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 78
      • 78 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 3
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories