12.07.2015 Views

Breve Introdução a Linguagem Python - INF-Unioeste

Breve Introdução a Linguagem Python - INF-Unioeste

Breve Introdução a Linguagem Python - INF-Unioeste

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

$whoamiMaridoPai de um adolescente e 8 gatos• Ok, 3 cães também...Apaixonado por programação (desde os 12)CinéfiloBacharel em Informática (<strong>Unioeste</strong>, 1999)Mestre em Ciência da Computação (UFSC, 2002)Professor na UTFPR-TD (desde 2009)Prof. Fabio Alexandre Spanhol, M.Sc.2


é uma linguageminterpretada, interativa,funcional, orientada aobjetos, dinamicamentetipada e com gerenciamentoautomático de memóriaSimilar, em certos aspectos, aPerl, Ruby, Scheme, Smalltalk eTclProf. Fabio Alexandre Spanhol, M.Sc.3


Entre todas aslinguagens queaprendi, <strong>Python</strong> é aque menosinterfere entre mim eo problema. É a maisefetiva para traduzirpensamentos emações.Eric RaymondProf. Fabio Alexandre Spanhol, M.Sc.4


Life is BetterWithout Braces.Bruce EckelProf. Fabio Alexandre Spanhol, M.Sc.5


<strong>Python</strong> has been animportant part of Googlesince the beginning, andremains so as the systemgrows and evolves. Todaydozens of Google engineersuse <strong>Python</strong>, and we'relooking for more peoplewith skills in thislanguage.Peter Norvik, director of search quality atGoogle, IncProf. Fabio Alexandre Spanhol, M.Sc.6


<strong>Python</strong> is everywhere atILM. It's used to extend thecapabilities of ourapplications, as well asproviding the glue betweenthem. Every CG image wecreate has involved <strong>Python</strong>somewhere in the process.Philip Peterson, Principal Engineer,Research & Development, Industrial Light &MagicProf. Fabio Alexandre Spanhol, M.Sc.7


Prof. Fabio Alexandre Spanhol, M.Sc.8


Guido van Rossum é referidopela comunidade python,desde 1995, comoBenevolent Dictator For Life(BDFL)Prof. Fabio Alexandre Spanhol, M.Sc.De dezembro de 2005 a 2012Guido trabalhou na Google,dedicando 50% do seu tempocom a linguagem• 7/12/2012 passou a trabalhar naDropbox• www.python.org/~guido• neopythonic.blogspot.com/9


Não veio da cobra!"Over six years ago, in December 1989,I was looking for a "hobby"programming project that would keepme occupied during the week aroundChristmas. My office ... would beclosed, but I had a home computer,and not much else on my hands. Idecided to write an interpreter for thenew scripting language I had beenthinking about lately: a descendant ofABC that would appeal to Unix/Chackers. I chose <strong>Python</strong> as a workingtitle for the project, being in a slightlyirreverent mood (and a big fan ofMonty <strong>Python</strong>´s Flying Circus)”.Prof. Fabio Alexandre Spanhol, M.Sc.10


Prof. Fabio Alexandre Spanhol, M.Sc.11


NADA!<strong>Python</strong> foi desenvolvido como umprojeto open source, sem finslucrativos e gerenciado pela PSF(<strong>Python</strong> Software Foundation)Prof. Fabio Alexandre Spanhol, M.Sc.12


Para obter o interpretador <strong>Python</strong>acessarhttp://www.python.org/download/Versões<strong>Python</strong> 2.7.5 foi liberada em 15 de maiode 2013<strong>Python</strong> 3.3.2* foi liberada em 15 demaio de 2013Prof. Fabio Alexandre Spanhol, M.Sc.13


http://www.python.org/about/success/GoogleNASAYahooInfoSeekMCI WorldcomIBMHigwayIndustrial Light and MagicAstraZenecaHoneywell...Prof. Fabio Alexandre Spanhol, M.Sc.14


Governo FederalPetrobrasSerproEmbratelGlobo.comStarOneConectivaCPqDAsyncHaxentUTFPR...Prof. Fabio Alexandre Spanhol, M.Sc.15


Vários projetos da comunidade SoftwareLivreBlenderOpenOfficeZope/PloneMoinMoinMailmanBitTorrentChandlerGimpPloneDjangoOpenERPinVesaliusProf. Fabio Alexandre Spanhol, M.Sc.16


Canivete suíçoWeb e InternetDatabaseGUIsCientífico e processamento numéricoEducaçãoProgramação de redeConstrução e teste de softwareDesenvolvimento de jogos e renderização3DOnde mais sua imaginação mandar!Prof. Fabio Alexandre Spanhol, M.Sc.17


Prof. Fabio Alexandre Spanhol, M.Sc.18


Prof. Fabio Alexandre Spanhol, M.Sc.19


Unix: HP-UX, Solaris ...Linux (frequentemente pré-instalada)Mac OSX (sempre pré-instalada)Windows: 9x, ME, 2K, XP, Vista, Seven(ctypes, win32all)Apple iPhoneGoogle AndroidProf. Fabio Alexandre Spanhol, M.Sc.20


SIM: Compilação Híbrida!Como ficou “famoso” com Java, programas <strong>Python</strong>são compilados, porém para uma linguagemintermediária, destinada a um interpretador• Isola <strong>Python</strong> de muitas das excentricidades dasmáquinas reais na qual ele roda• provê um nível de portabilidadeProf. Fabio Alexandre Spanhol, M.Sc.21


Prof. Fabio Alexandre Spanhol, M.Sc.De altíssimo nível epoderosaElegante, com sintaxesimples e concisaFácil de aprender,“cabe” no seu cérebro !MultiparadigmaFuncional, Procedural eOrientado a ObjetosPossui suporte nativo aestruturas de dadoscomplexas22


Prof. Fabio Alexandre Spanhol, M.Sc.23


Prof. Fabio Alexandre Spanhol, M.Sc.24


Prof. Fabio Alexandre Spanhol, M.Sc.25


Prof. Fabio Alexandre Spanhol, M.Sc.26


Código é muito mais lido que escrito!Readability importa! (muito)• <strong>Python</strong> te ajuda a escrever código maislegível!Prof. Fabio Alexandre Spanhol, M.Sc.27


Extensa biblioteca padrãoUm módulo para o que vocêprecisar• sys, random, re, datetime,calendar, csv, os, webbrowser,string, urlib, tkinter,codecs, pickle, types, array,mutex, queue, zlib, gzip, md5,thread, socket, email,xml.dom, locale, etc.Prof. Fabio Alexandre Spanhol, M.Sc.28


Prof. Fabio Alexandre Spanhol, M.Sc.29


33 palavras reservadasJava tem 53 e C# 77• and except nonlocal False• as finally not None• assert for or True• break from pass• class global raise• continue if return• def import try• del in while• elif is with• else lambda yeldProf. Fabio Alexandre Spanhol, M.Sc.30


Prazer em lhe conhecer!Cython• onde existir um compilador C ISO/IEC 9899:1990Jython• máquina virtual JavaPyPy• <strong>Python</strong> implementado em <strong>Python</strong><strong>Python</strong> for .NET• [Brian Lloyd], Iron<strong>Python</strong> (da M$)<strong>Python</strong> for DelphiLunatic<strong>Python</strong>• interoperando com LuaRuby/<strong>Python</strong>• em Ruby importar módulos <strong>Python</strong>)Prof. Fabio Alexandre Spanhol, M.Sc.31


Prof. Fabio Alexandre Spanhol, M.Sc.32


Programas maiores codificados emarquivos (scripts)normalmente usando um IDEextensão pyO script pode ser executado diretamenteda linha de comando do SOpython oi.pyOu carregado para o interpretadorinterativo>>> import oiProf. Fabio Alexandre Spanhol, M.Sc.33


InúmerosGeanyVimAptanaKomodoNetBeansPyCharmPyDev (Eclipse)Wing IDEPyshieldSpyderMS-Visual StudioEtc.Prof. Fabio Alexandre Spanhol, M.Sc.34


Ninja IDE (Ninja Is Not Just Another IDE)MultiplataformaEditor de código poderosoGerenciamento de ProjetosPlugins• http://ninja-ide.org/Prof. Fabio Alexandre Spanhol, M.Sc.35


Prof. Fabio Alexandre Spanhol, M.Sc.36


Prof. Fabio Alexandre Spanhol, M.Sc.37


<strong>Python</strong> Enhancement ProposalSão documentos padronizados da comunidade<strong>Python</strong>• Uma PEP propõe um padrão, melhoria,funcionalidade, estrutura, explicações sobrefuncionalidades, etc.Veja a PEP #0http://www.python.org/dev/peps/pep-0000/Prof. Fabio Alexandre Spanhol, M.Sc.38


<strong>Python</strong> é case-sensitiveCada linha é delimitada por enterTipagem forte e dinâmicaNão há declaração de variáveisAlguns operadoresAtribuição: =Aritméticos: +, -, *, /, **,//, %Relacionais: , >=,>,


Em <strong>Python</strong>, variáveis são referências aobjetosnão guardam os objetos em sinão têm tipo, mas os objetos aos quais elas sereferem têm tipoSão criadas dinamicamenteUma variável não pode ser utilizada emuma expressão sem ter sido inicializadanão existe “criação automática” de variáveisProf. Fabio Alexandre Spanhol, M.Sc.40


Variáveis não são “caixas” com valoresVariáveis são “rótulos” colados em objetosSão criadas pela atribuiçãoOperador =Prof. Fabio Alexandre Spanhol, M.Sc.41


Atribuição não gera uma cópia do objetoUma referência (variável) pode ser liberadaUsando del• Não existindo mais referências a um objeto, ele éremovido da memória (garbage collector)Prof. Fabio Alexandre Spanhol, M.Sc.42


Um bloco inicia com :A estrutura dos blocos é definida pelaindentaçãoA PEP #8 - Style Guide for <strong>Python</strong> Code - sugere 4espaços• Seja consistente• Não misturar tabulações com espaços!!!Prof. Fabio Alexandre Spanhol, M.Sc.43


Prof. Fabio Alexandre Spanhol, M.Sc.44


A partir do caractere #, o interpretadorignora o restante do código até o final dalinhaIsso não vale dentro de stringsPara várias linhas use asplas triplas(docstring)Documentar funções, classes, módulos, etc.Prof. Fabio Alexandre Spanhol, M.Sc.45


Inteirosx = 10y = 56859898958711346465165798798715654000000000000**2z = y + x• 3233048109594863662031421586618163610229539807267781773950479944647716000000000000000000000010LPonto flutuantef = 85.99984BooleanosTrue e FalseStringsDelimitadas por aspas ou apóstrofos = “python”s2 = ‘language’s3 = “%s %s” % (s,s2)Prof. Fabio Alexandre Spanhol, M.Sc.46


Usando typeProf. Fabio Alexandre Spanhol, M.Sc.47


Usando typeProf. Fabio Alexandre Spanhol, M.Sc.48


TuplasImutáveis(‘Fabio’,36, False, 89.2,186)Listasmutáveis[‘Fabio’,36, False, 89.2,186]DicionáriosChaves com valores associadosrefeicoes = {"café" : “cereal com leite e mel", "almoço" :"macarrão carbonara“,"jantar" : "sopa de champignon"}refeicoes["almoço"]ConjuntosNão permite elementos duplicadosset([1,2,3,4,5,6,8,9,8,1,2,7,1,2,5])Retorna• set([1, 2, 3, 4, 5, 6, 7, 8, 9])Prof. Fabio Alexandre Spanhol, M.Sc.49


Entrada com inputSaída com printProf. Fabio Alexandre Spanhol, M.Sc.50


ifif (expressao):bloco[elif (expressao):bloco][else:bloco]Prof. Fabio Alexandre Spanhol, M.Sc.51


exemploProf. Fabio Alexandre Spanhol, M.Sc.52


Forfor variavel in sequencia:bloco[else:bloco]Whilewhile (expressao):bloco[else:bloco]Prof. Fabio Alexandre Spanhol, M.Sc.53


Exemplo1Exemplo2Prof. Fabio Alexandre Spanhol, M.Sc.54


Modularizam o códigoComando def inicia a definição de uma funçãoComando return marca o fim da execução dafunção e define o resultado a ser devolvido• Pode ser NoneProf. Fabio Alexandre Spanhol, M.Sc.55


ExemploProf. Fabio Alexandre Spanhol, M.Sc.56


Prof. Fabio Alexandre Spanhol, M.Sc.57


Ei, não vamos complicar!Prof. Fabio Alexandre Spanhol, M.Sc.58


Estourar a pilha de execução é “fácil”E aí, tentou fat(1000)?Prof. Fabio Alexandre Spanhol, M.Sc.59


Mudando o tamanho da pilha de ativaçãoProf. Fabio Alexandre Spanhol, M.Sc.60


Prof. Fabio Alexandre Spanhol, M.Sc.61


Prof. Fabio Alexandre Spanhol, M.Sc.62


Inverter a ordem das cartasbaralho.reverse()Tirar a carta do topobaralho.pop()Adicionar 4 coringasbaralho.extend([‘Coringa’]*4)Colocar em ordembaralho.sort()• Pelo número de letras:baralho.sort(key=len)Prof. Fabio Alexandre Spanhol, M.Sc.63


TCL-TK é parte integrante, via tkinterDiversos outros bindings de frameworkswxWidgetsQTGTKetc.Prof. Fabio Alexandre Spanhol, M.Sc.64


Prof. Fabio Alexandre Spanhol, M.Sc.65


Também tem!Você pode fazer programação funcional semLost in Stupid Parenthesis (LISP)Prof. Fabio Alexandre Spanhol, M.Sc.66


Prof. Fabio Alexandre Spanhol, M.Sc.67


Prof. Fabio Alexandre Spanhol, M.Sc.68

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!