Mini Curso de Python para Coding Dojo

download Mini Curso de Python para Coding Dojo

If you can't read please download the document

Transcript of Mini Curso de Python para Coding Dojo

Introducing a New Product

Mini Curso de Python para Coding Dojo

Fabricio Erdmann

Verso Abr/2011 Python 2.7

Tpicos

A linguagem Python Introduo Controles de fluxo Estruturas de dados Classes Mdulos Consideraes Finais Referncias

A linguagem

Concebida pelo Holands Guido van Rossum Amsterd, 1990 Definies de Python Nome popular a uma grande cobra Monty Pythons Flying Circus Entidades Python Software Foundation Pgina oficial www.python.org Comunidade brasileira www.pythonbrasil.com.br

Ol, mundo!

Sada padro - print 1 >>> print "Ol, mundo!" Ol mundo! 2 >>> nome = "mundo" >>> print "Ol, %s!" %nome Ol, mundo! 3 >>> nome = "mundo" >>> print "Ol,", nome Ol, mundo! 4 >>> nome = "mundo" >>> print "Ol, "+nome Ol, mundo!

Entrada de dados

Entrada de string raw_input >>> nome = raw_input("Entre com seu nome: ") Entre com seu nome: Alexandre >>> print nome Alexandre >>> type(nome) Entrada de valor input >>> idade = input("Entre com sua idade: ") Entre com sua idade: 20 >>> print idade 20 >>> type(idade)

Nmeros

Inteiros Reais Complexos1 >>> 12341 >>> 1.2341 >>> >>> complex(2, 1J) 1234 1.234 (2-1J)2 >>> 99999999L 2 >>> 123.4e-22 >>> 1j * 1J 99999999L123.4e- (-1+0j)3 >>> (16-3*2)/23 >>> 7.0 / 2 3 >>> a = 3.0 + 4.0j 53.5 >>> a.real4 >>> 7 / 2 4 >>> 2.0**3 3.0 3 8.0 4 >>> a.imag5 >>> 7 % 2>>> round(9.6) 4.0 1 105 >>> abs(a) 5.0

Atribuio e Igualdade

Atribuio (=) >>> valor = 9.5 >>> a, b, c = 10, 20, 30 >>> x = y = 100 Igualdade (is ou ==) e Diferena (is not ou !=) >>> x = 5 1 >>> TESTE = x == 5 >>> print TESTE True 2 >>> TESTE = x != 5 >>> print TESTE False

Lgicos e Relacionais

Operadores lgicos or and Operadores relacionais < >= Exemplos >>> x = 15 1 >>> TESTE = x < 5 or (x > 10 and x >> print TESTE True 2 >>> TESTE = x < 5 or 10 < x >> print TESTE True

Built-in

Exibio de atributos - dir() 1 >>> dir() # escopo global ['__builtins__', '__doc__', '__name__'] 2 >>> dir(__builtins__) # mostra os mtodos builtins

Ajuda - help() >>> help(max) Help on built-in function max in module __builtin__: max(...) max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

Identificao de tipo - type() >>> nota = 9.5 >>> type(nota)

Strings

Definio (' ou " ou ''' ou """) 1 >>> 'teste...' 'teste...' 2 >>> 'teste \'2\'...' "teste '2'..." 3 >>> "teste '3'..." "teste '3'..." 4 >>> '''"teste '4'..." foi escrito no quadro'' '"teste \'4\'..." foi escrito no quadro' 5 >>> """Esta string apresenta mais de uma linha.""" 'Esta string\napresenta mais\nde uma linha.'

Vazia >>> s1 = '' Tamanho len() >>> s2 = 'UDESC' >>> len(s2) 5 Concatenao (+) >>> 'DCC/' + s2 'DCC/UDESC' Replicao (*) >>> 3*s2 'UDESCUDESCUDESC'

Slicing - string[inicio:fim:passo] >>> palavra = 'UDESC' 1 >>> palavra[2] 'E' 2 >>> palavra[0:3] 'UDE' 3 >>> palavra[3:] 'SC' 4 >>> palavra[-1] 'C' 5 >>> palavra[-2:] 'SC' 6 >>> palavra[::2] 'UEC' 7 >>> palavra[::-1] 'CSEDU'

U D E S C

0 1 2 3 4

Transformao em string str(objeto) ou >>> complexo = 2.5-1.0j >>> type(complexo) >>> texto = `complexo` >>> type(texto) >>> complexo (2.5-1j) >>> texto '(2.5-1j)'

Listas

Definio, slicing, concatenao e replica 1 >>> lista = [] # lista 2 >>> lista = [10, 20, 'aa', 'bb', 8.5] # definio 3 >>> print lista [10, 20, 'aa', 'bb', 8.5] 4 >>> lista[2:4] # slicing ['aa', 'bb'] 5 >>> lista[:3] + [30, 40, 10*5] # concatenao [10, 20, 'aa', 30, 40, 50] 6 >>> 3*lista[-2:] + ['cc'] # replicao ['bb', 8.5, 'bb', 8.5, 'bb', 8.5, 'cc']

Alterao, remoo e insero 1 >>> lista = [10, 20, 'aa', 'bb', 8.5] 2 >>> lista[1] = lista[1] + 5 # alterao indiv >>> lista [10, 25, 'aa', 'bb', 8.5] 3 >>> lista[2:4] = [30, 40] # alterao de itens >>> lista [10, 25, 30, 40, 8.5] 4 >>> lista[0:2] = [] # remoo >>> lista [30, 40, 8.5] 5 >>> lista[1:1] = [100, 200] # insero >>> lista [30, 100, 200, 40, 8.5] 6 >>> lista.append(2.5) # mdodo append >>> lista [30, 100, 200, 40, 8.5, 2.5]

Sub-listas aninhadas >>> lista = [30, 40, 8.5] >>> lista[1] = [100, 200] >>> lista [30, [100, 200], 8.5] >>> lista[1][0] 100 >>> len(lista) 3

Controle condicional

Comando if-elif-else x = input('Entre com um inteiro: ') if x == 0: print 'Zero' elif x == 1: print 'Um' elif x < 0: print 'Negativo' else: print 'Positivo'

Controle iterativo

Comandos for e while for i in [1,2,3,4,5]: print 'Esta a iterao nmero', i x = 10 while x >= 0: print 'x ainda no negativo.' x = x - 1 Intervalos range(inicio,fim,passo) range(2,10,3) for valor in range(100): print valor nomes = ['Fulano', 'Ciclano', 'Beltrano'] ['Fulano' Ciclano' Beltrano' for i in range(len(nomes)): print i+1, nomes[i]

Comandos else, break e continue for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, '=', x, '*', n/x break else: print n, ' primo!'

Comando pass while True: pass Outro exemplo nomes = ['Fulano', 'Ciclano', 'Beltrano'] ['Fulano' Ciclano' Beltrano' for i in nomes: print i

Funes

Comandos def e return def soma(k1, k2=10): '''Soma de inteiros no intervalo [k1,k2]''' soma = 0 valores = [] for i in range(k1, k2+1): soma = soma + i valores.append(i) return soma, valores

Palavra-chave em parmetros def figura(nome, cor_borda='preto', cor_fundo='branco', altura=10, largura=10): print 'Nome da figura:', nome print 'Cores: borda=%s, fundo=%s' %(cor_bord print 'Dimensoes: altura=%d, largura=%d' %(a >>> figura('elipse',altura=50) Nome da figura: elipse Cores: borda=preto, fundo=branco Dimensoes: altura=50, largura=10

def teste(a, *parametros, **palavras_chave): for p in parametros: print p, print a chaves = palavras_chave.keys() for c in chaves: print c, ':', palavras_chav ':', palavras_chav >>> teste('abc',10,20,30,x='aaa',y='bbb',z='ccc') 10 20 30 abc y : bbb x : aaa z : ccc

Funo lambda: def incrementa(n): eturn lambda x: x + n >>> f = incrementa(10) >>> f(0) 10 >>> f(1) 11

def componha(f1, f2): return lambda x, f1=f1, f2=f2: f1(f2(x)) >>> from math import sin, cos >>> sincos = componha(sin, cos) >>> print sincos(3) -0.836021861538 >>> print sin(cos(3)) -0.83602186153

Ferramentas de programao funcional - filter - map - reduce 1 >>> def pares(x): return (x % 2) == 0 >>> filter(pares, range(10)) [0, 2, 4, 6, 8] 2 >>> def quadrado(x): return x*x >>> map(quadrado, range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 3 >>> def soma(x,y): return x+y >>> reduce(soma, range(10)) 45

Erros e Excees

Erros ZeroDivisionError NameError TypeError Excees def divisao_segura(a,b): try: return a/b except ZeroDivisionError: print "Erro: diviso por zero!" except: print "Erro inesperado..." return None

Estruturas de Dados

Tuplas 1 >>> tupla = 12345, 54321, 'oi!' 2 >>> tupla (12345, 54321, 'oi!') 3 >>> tupla[0] tupla[0] 12345 4 >>> x, y, z = tupla >>> x 12345 >>> y 54321 >>> z 'oi!'

Conjuntos 1 >>> cesta = ['maca', 'laranja', ' 'banana'] >>> frutas = set(cesta) >>> frutas set(['pera', 'laranja', 'banana',]) >>> 'laranja' in frutas True >>> 'melao' in frutas False >>> a = set('abracadabra')

Dicionrios 1 >>> fone= {"aa" : 3232, "bb" : 7575, "cc" : 7777} 2 >>> fone {'aa': 3232, 'cc': 7777, 'bb'} 3 >>> fone["bb"] 7575 4 >>> fone.keys() ['aa', 'cc', 'bb'] 5 >>> fone.has_key("cc") True

Classes

Exemplo class agenda: def __init__(self, cont=None): # construtor self.conteudo = cont or [] def adicione(self, nome): self.conteudo.append(nome) >>> a = agenda() >>> a.adicione('Fulano') >>> a.adicione('Ciclano') >>> a.conteudo ['Fulano', 'Ciclano']

Sobrecarga de operadores class racional: def __init__(self, num, den): self.num = num self.den = den def __str__(self): return str(self.num) + '/' + str(self.d def __mul__(a, b): c = racional(a.num*b.num, a.den*b.den) return c >>> a = racional(1,3) >>> b = racional(5,2) >>> c = a * b >>> printc.num, c.den, c 5 65/6

Herana class NomeClasseDerivada(NomeClasseBase): Herana mltipla class NomeClasseDerivada(Base1, Base2, Base3)

Arquivos

Leitura e escrita >>> f = open('/tmp/texto.txt', 'w') # 'r', 'w', 'a', 'b', 't', '+' Mtodos >>> f.read() 'Isto o que est dentro do arquivo.\n' >>> f.readline() 'Ista a primeira linha do arquivo.\n >>> f.readline() 'Ista a segunda linha do arquivo.\n' >>> f.write('Escrevendo este texto\n' >>> f.read(1) >>> f.close()

Mdulos

Mdulos Arquivos texto com cdigo Python Arquivo compilado em C/C++ Exemplos: 1 >>> import math >>> dir(math) >>> a = math.cos(math.pi) 2 >>> from math import sin, cos, tan >>> a = cos(math.pi) 3 >>> from math import * >>> a = cos(pi)

Referencia

Minicurso C3 de Alexandre Gonalves Silvahttp://www.joinville.udesc.br/portal/professores/alexandre/materiais/c3_minicurso.pdf