├── aula_02 ├── file.csv ├── Curso introdutório de Python - FURB 2017 - Aula 02 - Slides.pdf ├── arquivo.txt ├── chuck_norris_jokes.py └── structures.py ├── aula_01 ├── Curso introdutório de Python - FURB 2017 - Aula 01 - Slides.pdf ├── format_strings.py ├── exercicios.py ├── exercicios_solucao.py └── aula_01_history.txt ├── README.md └── aula_03 ├── exercicios.py ├── exercicios_solucao.py └── examples.py /aula_02/file.csv: -------------------------------------------------------------------------------- 1 | Spam Spam Spam Spam Spam |Baked Beans| 2 | -------------------------------------------------------------------------------- /aula_01/Curso introdutório de Python - FURB 2017 - Aula 01 - Slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andresmachado/python-intro-furb/HEAD/aula_01/Curso introdutório de Python - FURB 2017 - Aula 01 - Slides.pdf -------------------------------------------------------------------------------- /aula_02/Curso introdutório de Python - FURB 2017 - Aula 02 - Slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andresmachado/python-intro-furb/HEAD/aula_02/Curso introdutório de Python - FURB 2017 - Aula 02 - Slides.pdf -------------------------------------------------------------------------------- /aula_02/arquivo.txt: -------------------------------------------------------------------------------- 1 | Esta e uma linha 2 | Esta e uma linha 3 | Esta e uma linha 4 | Esta e uma linha 5 | Esta e uma linha 6 | Esta e uma linha 7 | Esta e uma linha 8 | Esta e uma linha 9 | Esta e uma linha 10 | Esta e uma linha 11 | -------------------------------------------------------------------------------- /aula_02/chuck_norris_jokes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Apr 19 09:01:14 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | from urllib.request import urlopen 10 | import json 11 | 12 | url = 'http://api.icndb.com/jokes/' 13 | request = urlopen(url) 14 | response = request.read() 15 | 16 | data = json.loads(response) 17 | 18 | # List comprehension - Identificada pelas colchetes 19 | jokes = [v['joke'] for v in data['value']] 20 | 21 | # Generator expressions - É o mesma sintaxe que o List comprehension, só que com parenteses. 22 | jokes_iterator = (v['joke'] for v in data['value']) 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Slide da palestra 2 | 3 | [Slides - Speakerdeck](https://speakerdeck.com/andresmachado/minicurso-de-python-na-furb-2017) 4 | 5 | # Ementa do Curso 6 | 7 | * ## Aula 01 - Introdução a linguagem Python 8 | * Um pouco de história 9 | * O Zen do Python 10 | * O que podemos fazer com Python 11 | * Cases de sucesso no mundo 12 | * Características da linguagem 13 | * Tipagem e dados primitivos no Python (Listas e Strings) 14 | 15 | 16 | * ## Aula 02 - Indo mais a fundo 17 | * Python data model e os "__magicmethods__" 18 | * Estruturas de dados no Python e suas diferenças 19 | * Compreensão de listas e expressões geradoras 20 | * Dicionários e Manipulação de arquivos (context managers com "with") 21 | * Mini-projeto: Desenvolvendo uma lista de convidados Pythonica 22 | 23 | * ## Aula 03 - Conclusão 24 | * DefaultDict e namedtuple - Estruturas de dados avançada 25 | * Orientação a objetos com Python 26 | * Uma introdução a @decorators (decoradores) 27 | * Introdução ao paradigma funcional com Python e o módulo functools 28 | * Mini-projeto: Concluindo a lista de convidados Pythonica 29 | * Conclusão: o que fazer agora? 30 | -------------------------------------------------------------------------------- /aula_01/format_strings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Apr 18 18:35:26 2017 5 | 6 | @author: andre 7 | """ 8 | from math import pi 9 | 10 | formato_tabela = '{0:^6} | {1:^9} | {2:^10}' 11 | produtos = [ 12 | (2, 'Amarelo', 18.50), 13 | (5, 'Verde', 48.50), 14 | (2, 'Azul', 78.50), 15 | ] 16 | 17 | """ 18 | '{} + {} = {}'.format(10, 10, 20) 19 | '{0} + {1} = {2}'.format(10, 10, 20) # esse é o padrão 20 | '{0} + {0} = {1}'.format(10, 20) 21 | '{1} + {0} = {2}'.format(30, 20, 10) # evite fazer isso para não confundir 22 | 23 | a_string = '{cidade} é muito bonito(a) durante o(a) {estação}' 24 | a_string.format(cidade='Bruxelas', estação='Inverno') 25 | 26 | 'O total é R${0}'.format(59.8912313) 27 | 'O total é R${0:.2f}'.format(59.8912313) 28 | 'A porcentagem é de {0:.2%}'.format(0.8912313) 29 | 30 | '{0:<10} | {1:<10} | {2:<10}'.format('Qtd.', 'Cor', 'Valor') 31 | '{0:>10} | {1:>10} | {2:>10}'.format('Qtd.', 'Cor', 'Valor') 32 | '{0:^6} | {1:^9} | {2:^10}'.format('Qtd.', 'Cor', 'Valor') 33 | '{0:+^6} | {1:=^9} | {2:-^10}'.format('Qtd.', 'Cor', 'Valor') 34 | '{0:+^6} | {1:=^9} | {2:-^10}'.format('Qtd.', 'Cor', 'Valor') 35 | 36 | print(formato_tabela.format('Qtd.', 'Cor', 'Valor R$')) 37 | for qtd, cor, valor in produtos: 38 | print(formato_tabela.format(qtd, cor, valor)) 39 | 40 | '{0:e} {0:f} {0:%}'.format(.0000031) 41 | 42 | format(math.pi, '6.3f') 43 | format('Python', '.<12') 44 | format('Python', '.>12') 45 | format('Python', '.^12') 46 | """ 47 | -------------------------------------------------------------------------------- /aula_03/exercicios.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Apr 20 13:29:15 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | # A. is_key_there 10 | # Dado um dicionario e uma chave, verifique 11 | # se esta chave existe naquele dicionario 12 | # se existir retorne 'Chave encontrada: !' 13 | # caso contrário, retorne 'Não encontrado a chave no dict !' 14 | def is_key_there(d, k): 15 | # seu codigo aqui 16 | return 17 | 18 | # B. dict_union 19 | # Dado uma lista de dicionarios, crie um 20 | # unico dicionario com todos os outros 21 | # dica: o metodo d.update(d) pode ser 22 | # usado para ajudar nesta tarefa 23 | # ex.: dict_list = [{1: 20, 2:30}, {3: 120, 4:310}, {5: 220, 6:430}] 24 | # retorna {1: 20, 2:30, 3: 120, 4:310, 5: 220, 6:430} 25 | def dict_union(dict_list): 26 | # seu codigo aqui 27 | return 28 | 29 | # C. sum_dict_values 30 | # Dado um dicionario, some todos os valores 31 | # e retorne o total dessa soma. O dicionario pode ter 32 | # valores heterogeneos, neste caso retorne a string 'impossivel' 33 | # dica: Voce pode verificar o tipo do valor 34 | # com a funcao isinstance(object, classinfo) 35 | # Tudo em Python é objeto! 36 | def sum_dict_values(d): 37 | # seu codigo aqui 38 | return 39 | 40 | 41 | # D. get_min_max 42 | # Dado um dicionario, retorne o maior e o menor valor 43 | # ex.: my_dict = {'x':500, 'y':5874, 'z': 560} 44 | # returna "Maximo: 5874, Minimo: 500" 45 | def get_min_max(d): 46 | # seu codigo aqui 47 | return 48 | -------------------------------------------------------------------------------- /aula_03/exercicios_solucao.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Apr 20 13:29:15 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | me = {'name': 'Andre', 'idade':29} 10 | 11 | # A. is_key_there 12 | # Dado um dicionario e uma chave, verifique 13 | # se esta chave existe naquele dicionario 14 | # se existir retorne 'Chave encontrada: !' 15 | # caso contrário, retorne 'Não encontrado a chave no dict !' 16 | def is_key_there(d, k): 17 | if k in d: 18 | return 'Chave encontrada: {}!'.format(d[k]) 19 | else: 20 | return 'Não encontrado a chave {} no dict {}!'.format(k, d) 21 | 22 | 23 | # B. dict_union 24 | # Dado uma lista de dicionarios, crie um 25 | # unico dicionario com todos os outros 26 | # dica: o metodo d.update(d) pode ser 27 | # usado para ajudar nesta tarefa 28 | # ex.: dict_list = [{1: 20, 2:30}, {3: 120, 4:310}, {5: 220, 6:430}] 29 | # retorna {1: 20, 2:30, 3: 120, 4:310, 5: 220, 6:430} 30 | def dict_union(dict_list): 31 | # seu codigo aqui 32 | dic4 = {} 33 | for d in dict_list: 34 | dic4.update(d) 35 | return dic4 36 | 37 | 38 | # C. sum_dict_values 39 | # Dado um dicionario, some todos os valores 40 | # e retorne o total dessa soma. O dicionario pode ter 41 | # valores heterogeneos, neste caso retorne a string 'impossivel' 42 | # dica: Voce pode verificar o tipo do valor 43 | # com a funcao isinstance(object, classinfo) 44 | # Tudo em Python é objeto! 45 | def sum_dict_values(d): 46 | total = 0 47 | for v in d.values(): 48 | if not isinstance(v, (int, float)): 49 | return 'Impossivel!' 50 | total += v 51 | return total 52 | 53 | 54 | # D. get_min_max 55 | # Dado um dicionario, retorne o maior e o menor valor 56 | # ex.: my_dict = {'x':500, 'y':5874, 'z': 560} 57 | # returna "Maximo: 5874, Minimo: 500" 58 | def get_min_max(d): 59 | key_max = max(d.keys(), key=(lambda k: d[k])) 60 | key_min = min(d.keys(), key=(lambda k: d[k])) 61 | return "Maximo: {}, Minimo: {}".format(d[key_max], d[key_min]) 62 | -------------------------------------------------------------------------------- /aula_02/structures.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Apr 18 23:54:11 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | """ 10 | a = set('abracadabra') 11 | b = set('alacazam') 12 | a # unique letters in a 13 | a - b # letters in a but not in b 14 | a | b # letters in either a or b 15 | a & b # letters in both a and b 16 | a ^ b # letters in a or b but not both 17 | """ 18 | 19 | """ 20 | O metodo zip() 21 | questions = ['name', 'quest', 'favorite color'] 22 | answers = ['lancelot', 'the holy grail', 'blue'] 23 | """ 24 | 25 | """ 26 | Agrupando objetos com dict() 27 | 28 | names = ['carlos', 'marcelo', 'charles', 'felipe', 'andre', 'suelle', 29 | 'gustavo'] 30 | 31 | d = {} 32 | for name in names: 33 | key = len(name) 34 | if key not in d: 35 | d[key] = [] 36 | d[key].append(name) 37 | 38 | """ 39 | 40 | """ 41 | Contando com dicionarios 42 | cores = ['vermelho', 'verde', 'azul', 'amarelo', 'verde', 'azul', 'amarelo', 43 | 'amarelo'] 44 | 45 | d = {} 46 | for cor in cores: 47 | if cor not in d: 48 | d[cor] = 0 49 | d[cor] += 1 50 | """ 51 | 52 | """ 53 | Utilizando dicionarios para formatar strings 54 | a_dict = dict(nome='Andre', idade='29') 55 | "Meu nome é {nome} e eu tenho {idade} anos".format(**a_dict) 56 | """ 57 | 58 | 59 | 60 | """ 61 | Exemplo de iterador 62 | def g123(): 63 | yield 1 64 | yield 2 65 | yield 3 66 | """ 67 | 68 | """ 69 | ranks = [str(n) for n in range(2, 11)] + list('JQKA') 70 | suits = 'spades diamonds clubs hearts'.split() 71 | 72 | cards = [(rank, suit) for suit in suits 73 | for rank in ranks] 74 | 75 | colors = ['black', 'white'] 76 | sizes = ['S', 'M', 'L'] 77 | tshirts = [(color, size) for color in colors for size in sizes] 78 | """ 79 | 80 | """ 81 | - namedtuples 82 | 83 | somenamedtuple._make(iterable) 84 | somenamedtuple._asdict() 85 | somenamedtuple._replace(kwargs) 86 | somenamedtuple._fields 87 | 88 | - Transformar dict em uma namedtuple 89 | 90 | City = namedtuple('City', 'name lat lng') 91 | d = {'name': 'LAX', 'lat': 33.9425, 'lng': -118.408056} 92 | lax = City(**d) 93 | """ -------------------------------------------------------------------------------- /aula_01/exercicios.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | @author: Andre 4 | """ 5 | 6 | # A. donuts 7 | # Dado um contador (int) de donuts, retorne uma string 8 | # na forma 'Quantidade de: ', aonde é 9 | # o número informado. Entretanto, se o contador for 10 ou mais, 10 | # user a palavra 'muitos' no lugar do contador atual 11 | # Ex.: donuts(5) retorna 'Quantidade de donuts: 5' 12 | # e donuts(24) retorna 'Quantidade de donuts: muitos! 13 | def donuts(count): 14 | if count < 10: 15 | return 'Number of donuts: ' + str(count) 16 | else: 17 | return 'Number of donuts: many' 18 | 19 | donuts(5) 20 | donuts(10) 21 | # B. both_ends 22 | # Dado uma string 's', retorne a string feita os 2 primeiros 23 | # e os 2 ultimos caracteres da string original. 24 | # Entao, 'spring' retorna 'spng', entretanto se a string for 25 | # menor que dois, o retorno é vazio 26 | def both_ends(s): 27 | if len(s) < 2: 28 | return '' 29 | first2 = s[0:2] 30 | last2 = s[-2:] 31 | return first2 + last2 32 | 33 | 34 | # C. fix_start 35 | # Dado uma string s, retorne uma string aonde todas as 36 | # ocorrências da primeira letra sejam alteradas por '*' 37 | # apenas nao altere o primeiro caractere 38 | # ex.: 'babble' retorna 'ba**le' 39 | # Dica: s.replace(stra, strb) retorna uma versao da string s 40 | # aonde todas as ocorrencias de sao trocadas por strb. 41 | def fix_start(s): 42 | front = s[0] 43 | back = s[1:] 44 | fixed_back = back.replace(front, '*') 45 | return front + fixed_back 46 | 47 | 48 | # D. MixUp 49 | # Dado duas strings, retorne uma unica string com 50 | # as strings a e b separadas por espaço, trocando os 2 primeiros 51 | # caracteres de cada string 52 | # Ex. 53 | # 'mix', pod' -> 'pox mid' 54 | # 'dog', 'dinner' -> 'dig donner' 55 | # Assume a and b are length 2 or more. 56 | def mix_up(a, b): 57 | # +++your code here+++ 58 | return 59 | 60 | 61 | # A. match_ends 62 | # Dada uma lista de strings, retorne a contagem de 63 | # strings com tamanho maior que ou igual a 2 e que 64 | # a primeira e o ultimo caracteres sejam os mesmos 65 | 66 | def match_ends(words): 67 | # +++ seu codigo aqui +++ 68 | return 69 | 70 | 71 | # B. front_x 72 | # Dado uma lista de strings, retorne uma lista com as 73 | # strings ordenadas, exceto o grupo de caracteres que 74 | # que começam com a letra 'x'. 75 | # ex.: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] resulta em 76 | # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 77 | # Dica: Voce pode fazer isso criando duas listas e ordenando-as 78 | # antes de concatena-las 79 | 80 | def front_x(words): 81 | # +++seu codigo aqui+++ 82 | return 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /aula_01/exercicios_solucao.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | @author: Andre 4 | """ 5 | 6 | # A. donuts 7 | # Dado um contador (int) de donuts, retorne uma string 8 | # na forma 'Quantidade de: ', aonde é 9 | # o número informado. Entretanto, se o contador for 10 ou mais, 10 | # user a palavra 'muitos' no lugar do contador atual 11 | # Ex.: donuts(5) retorna 'Quantidade de donuts: 5' 12 | # e donuts(24) retorna 'Quantidade de donuts: muitos! 13 | def donuts(count): 14 | if count < 10: 15 | return 'Quantidade de donuts: ' + str(count) 16 | else: 17 | return 'Quantidade de donuts: muitos' 18 | 19 | # print(donuts(5)) 20 | # print(donuts(10)) 21 | 22 | # B. both_ends 23 | # Dado uma string 's', retorne a string feita os 2 primeiros 24 | # e os 2 ultimos caracteres da string original. 25 | # Entao, 'spring' retorna 'spng', entretanto se a string for 26 | # menor que dois, o retorno é vazio 27 | def both_ends(s): 28 | if len(s) < 2: 29 | return '' 30 | first2 = s[0:2] 31 | last2 = s[-2:] 32 | return first2 + last2 33 | 34 | # print(both_ends('spring')) 35 | # print(both_ends('winter')) 36 | # print(both_ends('summer')) 37 | # print(both_ends('s')) 38 | 39 | # C. fix_start 40 | # Dado uma string s, retorne uma string aonde todas as 41 | # ocorrências da primeira letra sejam alteradas por '*' 42 | # apenas nao altere o primeiro caractere 43 | # ex.: 'babble' retorna 'ba**le' 44 | # Dica: s.replace(stra, strb) retorna uma versao da string s 45 | # aonde todas as ocorrencias de sao trocadas por strb. 46 | def fix_start(s): 47 | front = s[0] 48 | back = s[1:] 49 | fixed_back = back.replace(front, '*') 50 | return front + fixed_back 51 | 52 | # print(fix_start('babble')) 53 | # print(fix_start('abracadabra')) 54 | # print(fix_start('alakazam')) 55 | 56 | # D. MixUp 57 | # Dado duas strings, retorne uma unica string com 58 | # as strings a e b separadas por espaço, trocando os 2 primeiros 59 | # caracteres de cada string 60 | # Ex. 61 | # 'mix', 'pod' -> 'pox mid' 62 | # 'dog', 'dinner' -> 'dig donner' 63 | # Assume a and b are length 2 or more. 64 | def mix_up(a, b): 65 | a_swapped = b[:2] + a[2:] 66 | b_swapped = a[:2] + b[2:] 67 | return a_swapped + ' ' + b_swapped 68 | 69 | # print(mix_up('mix', 'pod')) 70 | # print(mix_up('dog', 'dinner')) 71 | # print(mix_up('cat', 'fish')) 72 | 73 | # A. match_ends 74 | # Dada uma lista de strings, retorne a contagem de 75 | # strings com tamanho maior que ou igual a 2 e que 76 | # a primeira e o ultimo caracteres sejam os mesmos 77 | 78 | def match_ends(words): 79 | count = 0 80 | for word in words: 81 | if len(word) >= 2 and word[0] == word[-1]: 82 | count = count + 1 83 | return count 84 | 85 | # print(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb'])) 86 | # print(match_ends(['', 'x', 'xy', 'xyx', 'xx'])) 87 | # print(match_ends(['aaa', 'be', 'abc', 'hello'])) 88 | 89 | # B. front_x 90 | # Dado uma lista de strings, retorne uma lista com as 91 | # strings ordenadas, exceto o grupo de caracteres que 92 | # que começam com a letra 'x'. 93 | # ex.: ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] resulta em 94 | # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 95 | # Dica: Voce pode fazer isso criando duas listas e ordenando-as 96 | # antes de concatena-las 97 | 98 | def front_x(words): 99 | x_list = [] 100 | other_list = [] 101 | for w in words: 102 | if w[0] == 'x': 103 | x_list.append(w) 104 | else: 105 | other_list.append(w) 106 | return sorted(x_list) + sorted(other_list) 107 | 108 | # print(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])) 109 | # print(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa'])) 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /aula_03/examples.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Apr 20 13:08:17 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | import collections 10 | import random 11 | 12 | Card = collections.namedtuple('Card', ['rank', 'suit']) 13 | 14 | class FrenchDeck: 15 | """Cria um baralho tradicional iterável.""" 16 | ranks = [str(n) for n in range(2, 11)] + list('JQKA') 17 | suits = 'spades diamonds clubs hearts'.split() 18 | 19 | def __init__(self): 20 | self._cards = [Card(rank, suit) for suit in self.suits 21 | for rank in self.ranks] 22 | 23 | def __len__(self): 24 | return len(self._cards) 25 | 26 | def __getitem__(self, position): 27 | return self._cards[position] 28 | 29 | 30 | # Card('Q', 'hearts') in deck 31 | # Card('7', 'beats') in deck 32 | 33 | # Podemos reverter a ordem do nosso deck() 34 | for card in reversed(deck): 35 | print(card) 36 | 37 | # Podemos ordenar o deck() de acordo com a carta mais alta 38 | 39 | # Define o critério de ordenação 40 | suits_value = dict(spades=3, hearts=2, diamonds=1, clubs=0) 41 | def spades_high(card): 42 | rank_value = FrenchDeck.ranks.index(card.rank) 43 | return rank_value * len(suits_value) + suits_value[card.suit] 44 | 45 | # Ordena, revertido ou não (basta definir o reverse) 46 | sorted(deck, key=spades_high, reverse=True) 47 | 48 | # +++++++++++++ # 49 | # Mixin, não inicializa valores, por não implementar o __init__() 50 | class Mammal: 51 | 52 | def drink_milk(self): 53 | return True 54 | 55 | # Classe pai, que será herdada futuramente 56 | class Animal: 57 | """Classe para criar Animais genéricos.""" 58 | 59 | # Construtor da classe, pode receber argumentos. 60 | def __init__(self, name): 61 | print('Dentro da classe') 62 | self.name = name 63 | 64 | def __repr__(self): 65 | return self.name.title() 66 | 67 | def talk(self): 68 | return '{} is talking'.format(self.name) 69 | 70 | 71 | class Dog(Animal, Mammal): 72 | """Especialização da classe Animal e com o mixin Mammal""" 73 | 74 | # Atributos da classe, cada instancia terá sua versão 75 | paws = 4 76 | hungry = False 77 | angry = False 78 | 79 | def __init__(self, name, tricks=None): 80 | """ 81 | Metodo construtor da subclasse, recebe um novo argumento chamado tricks 82 | que deve ser uma lista 83 | 84 | :param tricks: argumento que deve ser uma lista 85 | :param name: string que define um nome 86 | :usage: dog = Dog('nome', tricks=['Rolar','Falar']) 87 | :return: instancia da classe Dog() 88 | """ 89 | if tricks: 90 | self.tricks = list(tricks) 91 | else: 92 | self.tricks = [] 93 | 94 | print('Dentro da subclasse') 95 | # Chama o metodo da classe pai de acordo com o MRO cls.__mro__ ou help(Cls) 96 | # para mais informações 97 | super(Dog, self).__init__(name) 98 | 99 | def talk(self): 100 | """Metodo para sobrescrever o original da classe Pai.""" 101 | times = 2 if not self.angry else 4 102 | bark = 'Wof! ' * times 103 | return '{}: barks - {}'.format(self.name, bark) 104 | 105 | 106 | def set_hungry(self): 107 | """Metodo que deixa o dog faminto.""" 108 | if not self.hungry: 109 | self.hungry = True 110 | self.angry = True 111 | print('{} is now hungry and angry.'.format(self.name)) 112 | else: 113 | self.angry = True 114 | print('{} is already hungry feed him!'.format(self.name)) 115 | 116 | def feed(self): 117 | """Metodo que deixa o dog calmo e alimentado.""" 118 | self.hungry = False 119 | self.angry = False 120 | print('{} is now fed and calm.'.format(self.name)) -------------------------------------------------------------------------------- /aula_01/aula_01_history.txt: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Apr 18 21:40:48 2017 5 | 6 | @author: andre 7 | """ 8 | 9 | IPython 5.2.1 -- An enhanced Interactive Python. 10 | ? -> Introduction and overview of IPython's features. 11 | %quickref -> Quick reference. 12 | help -> Python's own help system. 13 | object? -> Details about 'object', use 'object??' for extra details. 14 | In [1]: a = " Ola 'Mundo' " 15 | In [1]: a = " Ola 'Mundo' " 16 | 17 | In [2]: a 18 | Out[2]: " Ola 'Mundo' " 19 | 20 | In [3]: a[0] 21 | Out[3]: ' ' 22 | 23 | In [4]: a = "FURB" 24 | 25 | In [5]: a[0] 26 | Out[5]: 'F' 27 | 28 | In [6]: a[0] = "B" 29 | --------------------------------------------------------------------------- 30 | TypeError Traceback (most recent call last) 31 | in () 32 | ----> 1 a[0] = "B" 33 | 34 | TypeError: 'str' object does not support item assignment 35 | 36 | In [7]: a_string = 'Python is a beautiful programming language' 37 | 38 | In [8]: a_string 39 | Out[8]: 'Python is a beautiful programming language' 40 | 41 | In [9]: len(a_string) 42 | Out[9]: 42 43 | 44 | In [10]: len(a_string) > len(a) 45 | Out[10]: True 46 | 47 | In [11]: resultado = len(a_string) > len(a) 48 | 49 | In [12]: resultado 50 | Out[12]: True 51 | In [13]: a_string[5:20] 52 | In [13]: a_string[5:20] 53 | Out[13]: 'n is a beautifu' 54 | 55 | In [14]: a_string[5:len(a_string) -1:2] 56 | Out[14]: 'ni euiu rgamn aga' 57 | 58 | In [15]: a_string 59 | Out[15]: 'Python is a beautiful programming language' 60 | 61 | In [16]: a[0] 62 | Out[16]: 'F' 63 | 64 | In [17]: a_string[0] == a[0] 65 | Out[17]: False 66 | 67 | In [18]: a 68 | Out[18]: 'FURB' 69 | 70 | In [19]: a_string 71 | Out[19]: 'Python is a beautiful programming language' 72 | 73 | In [20]: a_string[:-1] 74 | Out[20]: 'Python is a beautiful programming languag' 75 | 76 | In [21]: a_string[:-10] 77 | Out[21]: 'Python is a beautiful programmin' 78 | 79 | In [22]: a_string[::-1] 80 | Out[22]: 'egaugnal gnimmargorp lufituaeb a si nohtyP' 81 | 82 | In [23]: a_string 83 | Out[23]: 'Python is a beautiful programming language' 84 | 85 | In [24]: s_inverted = a_string[::-1] 86 | 87 | In [25]: s_inverted 88 | Out[25]: 'egaugnal gnimmargorp lufituaeb a si nohtyP' 89 | 90 | In [26]: a 91 | Out[26]: 'FURB' 92 | 93 | In [27]: b = a 94 | 95 | In [28]: a 96 | Out[28]: 'FURB' 97 | 98 | In [29]: b 99 | Out[29]: 'FURB' 100 | 101 | In [30]: b = a[:] 102 | 103 | In [31]: b 104 | Out[31]: 'FURB' 105 | 106 | In [32]: id(b) 107 | Out[32]: 4585719872 108 | 109 | In [33]: id(a) 110 | Out[33]: 4585719872 111 | In [34]: help(a) 112 | In [34]: help(a) 113 | no Python documentation found for 'FURB' 114 | 115 | 116 | In [35]: dir(a) 117 | Out[35]: 118 | ['__add__', 119 | '__class__', 120 | '__contains__', 121 | '__delattr__', 122 | '__doc__', 123 | '__eq__', 124 | '__format__', 125 | '__ge__', 126 | '__getattribute__', 127 | '__getitem__', 128 | '__getnewargs__', 129 | '__getslice__', 130 | '__gt__', 131 | '__hash__', 132 | '__init__', 133 | '__le__', 134 | '__len__', 135 | '__lt__', 136 | '__mod__', 137 | '__mul__', 138 | '__ne__', 139 | '__new__', 140 | '__reduce__', 141 | '__reduce_ex__', 142 | '__repr__', 143 | '__rmod__', 144 | '__rmul__', 145 | '__setattr__', 146 | '__sizeof__', 147 | '__str__', 148 | '__subclasshook__', 149 | '_formatter_field_name_split', 150 | '_formatter_parser', 151 | 'capitalize', 152 | 'center', 153 | 'count', 154 | 'decode', 155 | 'encode', 156 | 'endswith', 157 | 'expandtabs', 158 | 'find', 159 | 'format', 160 | 'index', 161 | 'isalnum', 162 | 'isalpha', 163 | 'isdigit', 164 | 'islower', 165 | 'isspace', 166 | 'istitle', 167 | 'isupper', 168 | 'join', 169 | 'ljust', 170 | 'lower', 171 | 'lstrip', 172 | 'partition', 173 | 'replace', 174 | 'rfind', 175 | 'rindex', 176 | 'rjust', 177 | 'rpartition', 178 | 'rsplit', 179 | 'rstrip', 180 | 'split', 181 | 'splitlines', 182 | 'startswith', 183 | 'strip', 184 | 'swapcase', 185 | 'title', 186 | 'translate', 187 | 'upper', 188 | 'zfill'] 189 | 190 | In [36]: a.upper() 191 | Out[36]: 'FURB' 192 | 193 | In [37]: a = 'furb' 194 | 195 | In [38]: a 196 | Out[38]: 'furb' 197 | 198 | In [39]: a.upper() 199 | Out[39]: 'FURB' 200 | 201 | In [40]: a.swapcase() 202 | Out[40]: 'FURB' 203 | 204 | In [41]: a.title() 205 | Out[41]: 'Furb' 206 | 207 | In [42]: a_string 208 | Out[42]: 'Python is a beautiful programming language' 209 | 210 | In [43]: a_string = " amosidopsidjpo aposijpaoisjdoi .lll " 211 | 212 | In [44]: a 213 | Out[44]: 'furb' 214 | 215 | In [45]: a_string 216 | Out[45]: ' amosidopsidjpo aposijpaoisjdoi .lll ' 217 | 218 | In [46]: a_string.strip() 219 | Out[46]: 'amosidopsidjpo aposijpaoisjdoi .lll' 220 | 221 | In [47]: a_string 222 | Out[47]: ' amosidopsidjpo aposijpaoisjdoi .lll ' 223 | 224 | In [48]: a_string.split() 225 | Out[48]: ['amosidopsidjpo', 'aposijpaoisjdoi', '.lll'] 226 | 227 | In [49]: 'maca banana melao abacaxi'.split() 228 | Out[49]: ['maca', 'banana', 'melao', 'abacaxi'] 229 | In [50]: list() 230 | In [50]: list() 231 | Out[50]: [] 232 | 233 | In [51]: a = list() 234 | 235 | In [52]: a 236 | Out[52]: [] 237 | 238 | In [53]: a.append(10) 239 | 240 | In [54]: a 241 | Out[54]: [10] 242 | 243 | In [55]: list(a_string) 244 | Out[55]: 245 | [' ', 246 | ' ', 247 | ' ', 248 | ' ', 249 | ' ', 250 | ' ', 251 | 'a', 252 | 'm', 253 | 'o', 254 | 's', 255 | 'i', 256 | 'd', 257 | 'o', 258 | 'p', 259 | 's', 260 | 'i', 261 | 'd', 262 | 'j', 263 | 'p', 264 | 'o', 265 | ' ', 266 | ' ', 267 | ' ', 268 | 'a', 269 | 'p', 270 | 'o', 271 | 's', 272 | 'i', 273 | 'j', 274 | 'p', 275 | 'a', 276 | 'o', 277 | 'i', 278 | 's', 279 | 'j', 280 | 'd', 281 | 'o', 282 | 'i', 283 | ' ', 284 | ' ', 285 | ' ', 286 | ' ', 287 | ' ', 288 | ' ', 289 | '.', 290 | 'l', 291 | 'l', 292 | 'l', 293 | ' ', 294 | ' '] 295 | 296 | In [56]: a_string 297 | Out[56]: ' amosidopsidjpo aposijpaoisjdoi .lll ' 298 | 299 | In [57]: list(a_string) 300 | Out[57]: 301 | [' ', 302 | ' ', 303 | ' ', 304 | ' ', 305 | ' ', 306 | ' ', 307 | 'a', 308 | 'm', 309 | 'o', 310 | 's', 311 | 'i', 312 | 'd', 313 | 'o', 314 | 'p', 315 | 's', 316 | 'i', 317 | 'd', 318 | 'j', 319 | 'p', 320 | 'o', 321 | ' ', 322 | ' ', 323 | ' ', 324 | 'a', 325 | 'p', 326 | 'o', 327 | 's', 328 | 'i', 329 | 'j', 330 | 'p', 331 | 'a', 332 | 'o', 333 | 'i', 334 | 's', 335 | 'j', 336 | 'd', 337 | 'o', 338 | 'i', 339 | ' ', 340 | ' ', 341 | ' ', 342 | ' ', 343 | ' ', 344 | ' ', 345 | '.', 346 | 'l', 347 | 'l', 348 | 'l', 349 | ' ', 350 | ' '] 351 | 352 | In [58]: len(list(a_string)) 353 | Out[58]: 50 354 | 355 | In [59]: for i in list(a_string): print(i) 356 | 357 | 358 | 359 | 360 | 361 | 362 | a 363 | m 364 | o 365 | s 366 | i 367 | d 368 | o 369 | p 370 | s 371 | i 372 | d 373 | j 374 | p 375 | o 376 | 377 | 378 | 379 | a 380 | p 381 | o 382 | s 383 | i 384 | j 385 | p 386 | a 387 | o 388 | i 389 | s 390 | j 391 | d 392 | o 393 | i 394 | 395 | 396 | 397 | 398 | 399 | 400 | . 401 | l 402 | l 403 | l 404 | 405 | 406 | 407 | In [60]: 'a' + 'b' 408 | Out[60]: 'ab' 409 | 410 | In [61]: 10 + 'a' 411 | --------------------------------------------------------------------------- 412 | TypeError Traceback (most recent call last) 413 | in () 414 | ----> 1 10 + 'a' 415 | 416 | TypeError: unsupported operand type(s) for +: 'int' and 'str' 417 | In [62]: for i in list(a_string):print(i) 418 | In [62]: for i in list(a_string):print(i) 419 | 420 | 421 | 422 | 423 | 424 | 425 | a 426 | m 427 | o 428 | s 429 | i 430 | d 431 | o 432 | p 433 | s 434 | i 435 | d 436 | j 437 | p 438 | o 439 | 440 | 441 | 442 | a 443 | p 444 | o 445 | s 446 | i 447 | j 448 | p 449 | a 450 | o 451 | i 452 | s 453 | j 454 | d 455 | o 456 | i 457 | 458 | 459 | 460 | 461 | 462 | 463 | . 464 | l 465 | l 466 | l 467 | 468 | 469 | 470 | In [63]: for i in list(a_string): print(i) 471 | 472 | 473 | 474 | 475 | 476 | 477 | a 478 | m 479 | o 480 | s 481 | i 482 | d 483 | o 484 | p 485 | s 486 | i 487 | d 488 | j 489 | p 490 | o 491 | 492 | 493 | 494 | a 495 | p 496 | o 497 | s 498 | i 499 | j 500 | p 501 | a 502 | o 503 | i 504 | s 505 | j 506 | d 507 | o 508 | i 509 | 510 | 511 | 512 | 513 | 514 | 515 | . 516 | l 517 | l 518 | l 519 | 520 | 521 | 522 | In [64]: for i in list(a_string): 523 | ...: print(i),,,,, 524 | File "", line 2 525 | print(i),,,,, 526 | ^ 527 | SyntaxError: invalid syntax 528 | 529 | 530 | In [65]: for i in list(a_string): print(i) 531 | 532 | 533 | 534 | 535 | 536 | 537 | a 538 | m 539 | o 540 | s 541 | i 542 | d 543 | o 544 | p 545 | s 546 | i 547 | d 548 | j 549 | p 550 | o 551 | 552 | 553 | 554 | a 555 | p 556 | o 557 | s 558 | i 559 | j 560 | p 561 | a 562 | o 563 | i 564 | s 565 | j 566 | d 567 | o 568 | i 569 | 570 | 571 | 572 | 573 | 574 | 575 | . 576 | l 577 | l 578 | l 579 | 580 | 581 | In [66]: help(a) 582 | 583 | Help on list object: 584 | 585 | class list(object) 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | In [66]: help(a) 594 | 595 | 596 | In [67]: a 597 | Out[67]: [10] 598 | 599 | In [68]: help(a) 600 | 601 | 602 | In [69]: 'a' + 'b' 603 | Out[69]: 'ab' 604 | 605 | In [70]: ('a').__add__('b') 606 | Out[70]: 'ab' 607 | 608 | In [71]: '{:.5}'.format 609 | Out[71]: 610 | 611 | In [72]: '{:.5}'.format(a_string) 612 | Out[72]: ' ' 613 | 614 | In [73]: a_string = 'Python is a beautiful language.' 615 | 616 | In [74]: '{:.5}'.format(a_string) 617 | Out[74]: 'Pytho' 618 | 619 | In [75]: '{:.10}'.format(a_string) 620 | Out[75]: 'Python is ' 621 | 622 | In [76]: '{}'.format(a_string[:10]) 623 | Out[76]: 'Python is ' 624 | In [77]: '{}'.format(a_string[:10]) 625 | In [77]: '{}'.format(a_string[:10]) 626 | Out[77]: 'Python is ' 627 | 628 | In [78]: a_string 629 | Out[78]: 'Python is a beautiful language.' 630 | 631 | In [79]: '{:.10}'.format(a_string) 632 | Out[79]: 'Python is ' 633 | 634 | In [80]: '{:.5}'.format(a_string) 635 | Out[80]: 'Pytho' 636 | 637 | In [81]: '{:.1}'.format(a_string) 638 | Out[81]: 'P' 639 | In [82]: a_list = 'aaa aaaa aaaaa'.split() 640 | In [82]: a_list = 'aaa aaaa aaaaa'.split() 641 | 642 | In [83]: a_list 643 | Out[83]: ['aaa', 'aaaa', 'aaaaa'] 644 | 645 | In [84]: sorted(a_list) 646 | Out[84]: ['aaa', 'aaaa', 'aaaaa'] 647 | 648 | In [85]: a_list = 'aaaaaa aaa a'.split() 649 | 650 | In [86]: a_list 651 | Out[86]: ['aaaaaa', 'aaa', 'a'] 652 | 653 | In [87]: sorted(a_list) 654 | Out[87]: ['a', 'aaa', 'aaaaaa'] 655 | 656 | In [88]: a_list 657 | Out[88]: ['aaaaaa', 'aaa', 'a'] 658 | 659 | In [89]: a_list = 'bc, xyz, ayd, edc'.split(',') 660 | 661 | In [90]: a_list_ 662 | --------------------------------------------------------------------------- 663 | NameError Traceback (most recent call last) 664 | in () 665 | ----> 1 a_list_ 666 | 667 | NameError: name 'a_list_' is not defined 668 | 669 | In [91]: a_list 670 | Out[91]: ['bc', ' xyz', ' ayd', ' edc'] 671 | 672 | In [92]: a_list = 'bc,xyz,ayd,edc'.split(',') 673 | 674 | In [93]: a_list 675 | Out[93]: ['bc', 'xyz', 'ayd', 'edc'] 676 | 677 | In [94]: sorted(a_list) 678 | Out[94]: ['ayd', 'bc', 'edc', 'xyz'] 679 | 680 | In [95]: sorted(a_list, key=len) 681 | Out[95]: ['bc', 'xyz', 'ayd', 'edc'] 682 | 683 | In [96]: len('abc') 684 | Out[96]: 3 685 | 686 | In [97]: a_list = 'bDDc,AAyz,aaBBaAAyd,AAAedc'.split(',') 687 | 688 | In [98]: a_list 689 | Out[98]: ['bDDc', 'AAyz', 'aaBBaAAyd', 'AAAedc'] 690 | 691 | In [99]: sorted(a_list, key=str.lower) 692 | Out[99]: ['AAAedc', 'aaBBaAAyd', 'AAyz', 'bDDc'] 693 | 694 | In [100]: a_list 695 | Out[100]: ['bDDc', 'AAyz', 'aaBBaAAyd', 'AAAedc'] 696 | 697 | In [101]: sorted(a_list, key=str.upper) 698 | Out[101]: ['AAAedc', 'aaBBaAAyd', 'AAyz', 'bDDc'] 699 | 700 | In [102]: a_list = '100022233 001112222 01010101 00222'.split(',') 701 | 702 | In [103]: a_list 703 | Out[103]: ['100022233 001112222 01010101 00222'] 704 | 705 | In [104]: a_list = '100022233 001112222 01010101 00222'.split() 706 | 707 | In [105]: a_list 708 | Out[105]: ['100022233', '001112222', '01010101', '00222'] 709 | 710 | In [106]: sorted(a_list, key=lambda x: x.count(0)) 711 | --------------------------------------------------------------------------- 712 | TypeError Traceback (most recent call last) 713 | in () 714 | ----> 1 sorted(a_list, key=lambda x: x.count(0)) 715 | 716 | in (x) 717 | ----> 1 sorted(a_list, key=lambda x: x.count(0)) 718 | 719 | TypeError: expected a string or other character buffer object 720 | 721 | In [107]: sorted(a_list, key=lambda x: x.count('0')) 722 | Out[107]: ['001112222', '00222', '100022233', '01010101'] 723 | 724 | In [108]: def count_zero(l): 725 | ...: return l.count('0') 726 | ...: 727 | 728 | In [109]: sorted(a_list, key=count_zero) 729 | Out[109]: ['001112222', '00222', '100022233', '01010101'] 730 | 731 | In [110]: sorted(a_list, key=lambda x: x.count('0')) 732 | Out[110]: ['001112222', '00222', '100022233', '01010101'] 733 | 734 | In [111]: a_list 735 | Out[111]: ['100022233', '001112222', '01010101', '00222'] 736 | 737 | In [112]: sorted(a_list) 738 | Out[112]: ['001112222', '00222', '01010101', '100022233'] 739 | 740 | In [113]: a_list.sort() 741 | 742 | In [114]: a_list 743 | Out[114]: ['001112222', '00222', '01010101', '100022233'] 744 | In [115]: 745 | 746 | 747 | --------------------------------------------------------------------------------