"mostrando a cobra" - ou breve introdução à linguagem python

Post on 18-Dec-2014

582 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Palestra ministrada no 5 JavaTech, Univel, Cascavel, PR, em 08/06/2011.

TRANSCRIPT

2Prof. Fabio Alexandre Spanhol, M.Sc.

é uma linguagem interpretada, interativa, funcional, orientada a objetos, dinamicamente tipada e com gerenciamento automático de memória Similar em certos aspectos a Perl, Ruby, Scheme, Smalltalke Tcl

3Prof. Fabio Alexandre Spanhol, M.Sc.

4Prof. Fabio Alexandre Spanhol, M.Sc.

Guido van Rossum é referido pela comunidade python, desde 1995, como BenevolentDictator For Life (BDFL) ◦ Desde dezembro de 2005 Guido

trabalha na Google, dedicando 50% do seu tempo com a linguagem◦ www.python.org/~guido◦ neopythonic.blogspot.com/

5Prof. Fabio Alexandre Spanhol, M.Sc.

Não veio da cobra!◦ "Over six years ago, in December 1989,

I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python´s Flying Circus)”.

Prof. Fabio Alexandre Spanhol, M.Sc. 6

NADA!Python foi desenvolvido como um projeto open source, sem fins lucrativos e gerenciado pela PSF (Python Software Foundation)

7Prof. Fabio Alexandre Spanhol, M.Sc.

Prof. Fabio Alexandre Spanhol, M.Sc. 8

Para obter o interpretador Python acessar http://www.python.org/download/ Versões◦ Python 2.7.1 foi liberada em 27 de

novembro de 2010◦ Python 3.2* foi liberada em 20 de fevereiro

de 2011

9Prof. Fabio Alexandre Spanhol, M.Sc.

http://www.python.org/about/success/◦ Google◦ NASA◦ Yahoo◦ InfoSeek◦ MCI Worldcom◦ IBM ◦ Higway◦ Industrial Light and Magic◦ AstraZeneca◦ Honeywell◦ ...

Governo FederalPetrobrasSerproEmbratelGlobo.comStarOneConectivaCPqDAsyncHaxentUTFPR...

10Prof. Fabio Alexandre Spanhol, M.Sc.

11Prof. Fabio Alexandre Spanhol, M.Sc.

Vários projetos da comunidade Software Livre◦ Blender◦ OpenOffice◦ Zope/Plone◦ MoinMoin◦ Mailman◦ BitTorrent◦ Chandler◦ Gimp◦ Plone◦ Django◦ OpenERP◦ inVesalius

Web e Internet DatabaseGUIsCientífico e processamento numéricoEducaçãoProgramação de rede Construção e teste de softwareDesenvolvimento de jogos e renderização 3DOnde mais sua imaginação mandar!

12Prof. Fabio Alexandre Spanhol, M.Sc.

13Prof. Fabio Alexandre Spanhol, M.Sc.

14Prof. Fabio Alexandre Spanhol, M.Sc.

Unix: HP-UX, Solaris ...Linux (freqüentemente pré-instalada)Mac OSX (sempre pré-instalada)Windows: 9x, ME, 2K, XP, Vista, Seven(ctypes, win32all)Nokia Série 60 e MaemoPalmOS (PipPy)

Compilação Híbridacomo Java, programas Python sãocompilados, porém para uma linguagemintermediária, destinada a um interpretador◦ Tal como Java, isso isola Python de muitas das

excentricidades das máquinas reais na qual eleroda, provendo um nível de portabilidadeequivalente a Java

15Prof. Fabio Alexandre Spanhol, M.Sc.

16Prof. Fabio Alexandre Spanhol, M.Sc.

De altíssimo nível e poderosaElegante, com sintaxe simples e concisaFácil de aprender, “cabe” no seu cérebro !Multiparadigma: Funcional, Procedural e Orientado a ObjetosPossui suporte nativo a estruturas de dados complexas

17Prof. Fabio Alexandre Spanhol, M.Sc.

18Prof. Fabio Alexandre Spanhol, M.Sc.

19Prof. Fabio Alexandre Spanhol, M.Sc.

20Prof. Fabio Alexandre Spanhol, M.Sc.

Extensa biblioteca padrãoUm módulo para o que você precisarsys, 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. 21Prof. Fabio Alexandre Spanhol, M.Sc.

22Prof. Fabio Alexandre Spanhol, M.Sc.

23Prof. Fabio Alexandre Spanhol, M.Sc.

29 palavras reservadas ◦ (Java tem 52 e C# 77)and exec notassert finally orbreak for passclass from printContinue global raisedef if returndel import tryelif in whileelse is yeldexcept lambda

IDLEinterpretador

24Prof. Fabio Alexandre Spanhol, M.Sc.

Cython◦ onde existir um compilador C ISO/IEC 9899:1990Jython◦ máquina virtual JavaPyPy◦ Python implementado em PythonPython for .NET◦ [Brian Lloyd], IronPython (da M$)Python for DelphiLunaticPython◦ interoperando com LuaRuby/Python◦ em Ruby importar módulos Python)

25Prof. Fabio Alexandre Spanhol, M.Sc.

Python é case-sensitiveCada linha é delimitada por enterTipagem forte e dinâmica◦ Não há declaração de variáveisComentários iniciam por #Comentários em várias linhas delimitadospor aspas triplas “””Alguns operadores◦ Atribuição: =◦ Aritméticos: +, -, *, /, **,//,%◦ Relacionais: <,>,>=,<=, ==,!=,<>,is, in◦ Lógicos: and,or,not◦ Bitwise: |,^,&,>>,<<,~

26Prof. Fabio Alexandre Spanhol, M.Sc.

for i in range(25):if i%3 == 0:

print iif i%5 == 0:

print "Bingo!"print “-”*5

Prof. Fabio Alexandre Spanhol, M.Sc.

A estrutura dos blocos é definida pelaindentação◦ Não misturar tabulações com espaços

27

Inteiros◦ x = 10◦ y = 56859898958711346465165798798715654000000000000**2◦ z = y + x 3233048109594863662031421586618163610229539807267781773950479944647716000000000000000000000010L

Ponto flutuante◦ f = 85.99984

Booleanos◦ True e False

Strings◦ Delimitadas por aspas ou apóstrofo◦ s = “python”◦ s2 = ‘language’◦ s3 = “%s %s” % (s,s2)

28Prof. Fabio Alexandre Spanhol, M.Sc.

Usando type>>> x = 2>>> print type(x)<type 'int'>>>> x = "dois">>> print type(x)<type 'string'>>>> x = 10.2>>> print type(x)<type 'float'>>>> x=round>>> print x<built-in function round>

29Prof. Fabio Alexandre Spanhol, M.Sc.

Tuplas◦ Imutáveis◦ (‘Fabio’,32, False, 92.5,186)

Listas◦ mutáveis◦ [‘Fabio’,32, False, 92.5,186]

Dicionários◦ Chaves com valores associados ◦ refeicoes = {"café" : “cereal com leite e mel", "almoço" : "macarrão carbonara“,"jantar" : "sopa de champignon"}

◦ print refeicoes["almoço"]

Conjuntos◦ Não permite elementos duplicados◦ set([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])

30Prof. Fabio Alexandre Spanhol, M.Sc.

Entrada com raw_input◦ nome=raw_input("Qual o seu nome?")◦ idade=int(raw_input(“Qual a sua idade?”)

Saída com print◦ print nome◦ print "Ola %s, sua nota:%10.2f" % (nome,nota)

31Prof. Fabio Alexandre Spanhol, M.Sc.

ifif (expressao):

bloco[elif (expressao):

bloco][else:

bloco]

32Prof. Fabio Alexandre Spanhol, M.Sc.

exemplos = raw_input(“número entre 0 e 100? ")n = int(s)if not 0 < n < 100:

print "Número inválido."if n % 2 == 0:

print "Número Par"else:

print "Número Ímpar"

33Prof. Fabio Alexandre Spanhol, M.Sc.

forfor variavel in sequencia:

bloco[else:

bloco]while

while (expressao):bloco

[else:bloco]

34Prof. Fabio Alexandre Spanhol, M.Sc.

Exemplo#encoding: utf-8cores=[‘verde',‘amarelo',‘azul',‘branco']for cor in cores:print cor ' é minha cor favorita!'

35Prof. Fabio Alexandre Spanhol, M.Sc.

36Prof. Fabio Alexandre Spanhol, M.Sc.

Modularizam o código#encoding: utf-8

#função que escreve n termos da série de fibonaccidef fibo(n):

a,b,t=0,1,1while t <= n:

print b a, b = b, a + bt+=1

x=int(raw_input("Quantos termos?"))fibo(x)

37Prof. Fabio Alexandre Spanhol, M.Sc.

Não vamos complicar!

Prof. Fabio Alexandre Spanhol, M.Sc. 38

39Prof. Fabio Alexandre Spanhol, M.Sc.

40Prof. Fabio Alexandre Spanhol, M.Sc.

41Prof. Fabio Alexandre Spanhol, M.Sc.

Inverter a ordem das cartas◦ baralho.reverse()Tirar a carta do topo◦ baralho.pop()Adicionar 4 coringas◦ baralho.extend([‘Coringa’]*4)Colocar em ordem◦ baralho.sort() Pelo número de letras: baralho.sort(key=len)

42Prof. Fabio Alexandre Spanhol, M.Sc.

43Prof. Fabio Alexandre Spanhol, M.Sc.

Também tem!Você pode fazer programação Funcional sem Lost in StupidParenthesis (LISP)

44Prof. Fabio Alexandre Spanhol, M.Sc.

45Prof. Fabio Alexandre Spanhol, M.Sc.

46Prof. Fabio Alexandre Spanhol, M.Sc.

47Prof. Fabio Alexandre Spanhol, M.Sc.

@_photon_

faspanhol@gmail.com

www.slideshare.net/_photon_

top related