Share
Embed
Transcript
39 slides
-
3 Sobre mim Luan Fonseca, desenvolvedor na Evolux, 4Soft e
estudante de Engenharia de Software. fb.com/luanfonceca! twitter.com/luanfonceca! github.com/luanfonceca -
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. -
Notações • Código Python: ! >>> ! • Código do
Terminal: ! $ ! • Comentário: ! # -
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 -
Por que usar • Legível! • Rápido Ciclo de Desenvolvimento!
• Multi-plataforma! • Facilidade no Aprendizado! • Divertido -
Bem Vindo ao Python • Vários Tipos Básicos:! • Inteiro!
• Flutuante! • String! • Lista! • Dicionário! • Tuplas -
Tipagem Forte >>> print("1" + 2) Traceback (most recent call
last) string + number TypeError: cannot concatenate 'int' and 'str' objects -
Identação Importa, MUITO >>> eh_divertido = True >>> if eh_divertido:
>>> print("Python eh show!") >>> else: >>> print("Voce deve estar usando Java") -
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") -
Matemática >>> x = 3 >>> y = 2 >>>
x + y 5 >>> 3 - y 1 >>> (x * y) + (2 * x) 12 -
Expressões >>> x = 3 >>> 1 < x <
3 False >>> 2 < x < 5 True >>> 3 == x True -
Strings >>> print("Python") >>> print('Python') >>> print(""" Python """) >>>
print(''' Python ''') -
Strings >>> nome = "Python" >>> print("O " + nome
+ " eh muito divertido") >>> print("O %s eh muito divertido" % nome) >>> print("O {0} eh muito divertido".format(nome)) -
Manipulando Strings >>> print("PYTHON IS GREAT".lower()) python is great >>>
print("python is great".upper()) PYTHON IS GREAT >>> print("python is great"[:6]) python -
Funções >>> all([True, True, False) False >>> any([False, True, False)
True >>> min([1, 2, 3]) 1 >>> max([1, 2, 3]) 3 -
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' -
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] -
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 -
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) -
Argumentos de Funções >>> def exibir(nome="Fulano"): print("Ola, %s" % nome)
>>> exibir("Luan") Ola, Luan >>> exibir() Ola, Fulano -
Criando Classes >>> class Pessoa(): nome = "Luan" >>> p
= Pessoa() >>> print(p.nome) Luan -
Usando Pacotes >>> import funcoes >>> funcoes.exibir() Ola, Fulano >>>
from funcoes import exibir >>> exibir("Python") Ola, Python -
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() -
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() -
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 -
Criando o novo Pacote # Conteúdo do arquivo pessoa.py class
Pessoa(): nome = "Fulano" ! def dar_ola(self): return("Ola, %s" % self.nome) -
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() -
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) -
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)