Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Básico

Python Básico

Avatar for Luan Fonseca de Farias

Luan Fonseca de Farias

August 23, 2014
Tweet

More Decks by Luan Fonseca de Farias

Other Decks in Programming

Transcript

  1. 3 Sobre mim Luan Fonseca, desenvolvedor na Evolux, 4Soft e

    estudante de Engenharia de Software. fb.com/luanfonceca! twitter.com/luanfonceca! github.com/luanfonceca
  2. Resumindo Python foi criado por Guido Van Rossum no começo

    dos anos 90. Atualmente é uma das linguagens de programação mais populares. Eu me apaixonei por Python, por sua clareza de sintaxe. É basicamente pseudocódigo executável.
  3. Notações • Código Python: ! >>> ! • Código do

    Terminal: ! $ ! • Comentário: ! #
  4. Python • Código Aberto! • Criado por Guido Van Rossum

    em ~1990! • Simples, limpa, intuitiva! • Alto nível de Abstração, Orientada a objetos, Multi-paradigma! • Baterias Incluídas! • Comunidade forte: GrupyRN! • Muitas empresas usam, assumidamente:! • Dropbox, Google, Facebook, Globo, Evolux, IFRN
  5. Por que usar • Legível! • Rápido Ciclo de Desenvolvimento!

    • Multi-plataforma! • Facilidade no Aprendizado! • Divertido
  6. Bem Vindo ao Python • Vários Tipos Básicos:! • Inteiro!

    • Flutuante! • String! • Lista! • Dicionário! • Tuplas
  7. Tipagem Forte >>> print("1" + 2) Traceback (most recent call

    last) string + number TypeError: cannot concatenate 'int' and 'str' objects
  8. Identação Importa, MUITO >>> eh_divertido = True >>> if eh_divertido:

    >>> print("Python eh show!") >>> else: >>> print("Voce deve estar usando Java")
  9. Usando comentários >>> eh_divertido = True >>> if eh_divertido: #

    Checa se Python é divertido >>> print("Python eh show!") >>> else: # Se não for, deve ser Java D: >>> print("Voce deve estar usando Java")
  10. Matemática >>> x = 3 >>> y = 2 >>>

    x + y 5 >>> 3 - y 1 >>> (x * y) + (2 * x) 12
  11. Expressões >>> x = 3 >>> 1 < x <

    3 False >>> 2 < x < 5 True >>> 3 == x True
  12. Strings >>> nome = "Python" >>> print("O " + nome

    + " eh muito divertido") >>> print("O %s eh muito divertido" % nome) >>> print("O {0} eh muito divertido".format(nome))
  13. Manipulando Strings >>> print("PYTHON IS GREAT".lower()) python is great >>>

    print("python is great".upper()) PYTHON IS GREAT >>> print("python is great"[:6]) python
  14. Funções >>> all([True, True, False) False >>> any([False, True, False)

    True >>> min([1, 2, 3]) 1 >>> max([1, 2, 3]) 3
  15. Conversões >>> int("1") 1 >>> str(1) "1" >>> float(1) 1.0

    >>> int("a") Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'a'
  16. Listas >>> x = [] >>> x.append(5) >>> x.extend([6, 7,

    8]) >>> x [5, 6, 7, 8] >>> x.reverse() >>> x [8, 7, 6, 5] >>> sorted(x) [5, 6, 7, 8]
  17. Dicionários >>> d = {'a': 5, ‘b’: 4} >>> print(d)

    {'a': 5, 'b': 4} >>> print(d['a']) 5 >>> e = dict(a=5, b=4) >>> print(e) {'a': 5, 'b': 4} >>> 'a' in e and e['a'] == 5 True
  18. Criando Funções >>> def exibir(nome): print("Ola, %s" % nome) >>>

    exibir("Luan") Ola, Luan >>> exibir() Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: exibir() takes exactly 1 argument (0 given)
  19. Argumentos de Funções >>> def exibir(nome="Fulano"): print("Ola, %s" % nome)

    >>> exibir("Luan") Ola, Luan >>> exibir() Ola, Fulano
  20. Usando Pacotes >>> import funcoes >>> funcoes.exibir() Ola, Fulano >>>

    from funcoes import exibir >>> exibir("Python") Ola, Python
  21. Testando Pacotes # Conteúdo do arquivo teste_funcoes.py import unittest from

    funcoes import exibir ! class TestExibir(unittest.TestCase): def test_exibir_fulano(self): assert(exibir() == 'Ola, Fulano') ! if __name__ == '__main__': unittest.main()
  22. Criando novo Teste # Conteúdo do arquivo teste_pessoa.py import unittest

    from pessoa import Pessoa ! class TestPessoa(unittest.TestCase): def test_dar_ola(self): p = Pessoa() assert(p.dar_ola() == 'Ola, Fulano') ! if __name__ == '__main__': unittest.main()
  23. Rodando o Teste $ python teste_pessoa.py Traceback (most recent call

    last): File "teste_pessoa.py", line 3, in <module> from pessoa import Pessoa ImportError: No module named pessoa
  24. Criando o novo Pacote # Conteúdo do arquivo pessoa.py class

    Pessoa(): nome = "Fulano" ! def dar_ola(self): return("Ola, %s" % self.nome)
  25. Permitir Passar o Nome # Conteúdo do arquivo teste_pessoa.py ...

    class TestPessoa(unittest.TestCase): ... def test_dar_ola_para_luan(self): p = Pessoa("Luan") assert(p.dar_ola() == 'Ola, Luan') ! if __name__ == '__main__': unittest.main()
  26. Rodando o Teste $ python teste_pessoa.py .E ====================================================================== ERROR: test_dar_ola_para_luan

    (__main__.TestPessoa) ---------------------------------------------------------------------- Traceback (most recent call last): File "teste_pessoa.py", line 11, in test_dar_ola_para_luan p = Pessoa("Luan") TypeError: this constructor takes no arguments ! ---------------------------------------------------------------------- Ran 2 tests in 0.000s ! FAILED (errors=1)
  27. Aceitando parametro em Pessoa() # Conteúdo do arquivo pessoa.py class

    Pessoa(): def __init__(self, nome="Fulano"): self.nome = nome ! def dar_ola(self): return("Ola, %s" % self.nome)