Vous êtes sur la page 1sur 22

Python

O que Python?
Linguagem de altssimo nvel
Suporte nativo a estruturas de dados de alto nivel

Multiplataforma
Linux, Unix, Windows, Mac OS, Solaris, etc...

Multiparadigma
Procedural, OO, funcional

Opensource
Integra com outras linguagens:
(.NET) IronPython, (Java) Jython, C e C++

Por que Python?

Fcil aprendizado
Sintaxe limpa e de fcil leitura
Forte suporte da comunidade
Forte documentao
Biblioteca padro enorme
Divertida
Mais com menos [cdigo]
Liberdade

Quem usa Python?

Google
NASA
Gimp/Inkscape/Blender
Governo (brasil.gov.br)
Entre outras...
http://www.python.org/about/success/
http://www.python.org.br/wiki/EmpresasPython

Conceitos Bsicos
Case sensitive

It it

Blocos por endentao


se condio:
bloco

Tipagem dinmica
a=2

a = alguma coisa

Tudo objeto
No tem ponto e virgula no final (;)
Comentrios comeam com #

a = 2.3

Interpretador Interativo

print Hello, World!

Rodando do Arquivo

Salve como hello.py


Abra o terminal/CMD
Entre na pasta do arquivo hello.py
Execute o comando:
C:\Python27\python.exe hello.py

Comandos importantes
dir( objeto )
Retorna uma lista de atributos e mtodos do objeto
help( objeto)
Mostra a documentao do objeto
type( objeto)
- Informa o tipo do objeto

Variveis e Tipos Bsicos


Atribuio:
nome_da_variavel = alguma_coisa
Inteiros, Inteiros Longos, Reais, Strings e Booleanos
>>> a = 4
>>>
type(a)
<type
'int'>

>>> a = 5.3209>>> a = True


>>> type(a)
>>> b = False
<type 'float'> >>> type(a)
<type 'bool'>
>>> type(b)
<type 'bool'>

>>> a = 'texto'
>>> b = "texto"
>>> type(a)
<type 'str'>
>>> type(b)
<type 'str'>

Converso dos Tipos Bsicos


int(), float(), str(), bool(), long()
>>> int(3.1415)
3

>>> str(True)
'True'

>>> float(3)
3.0

>>> bool(1)
True

>>> str(25)
'25'

>>> bool(0)
False

10

Operadores Aritmticos
+, -, *, /, //, **, >>>
% a=2
Diviso com
nmeros inteiros
resulta em um
nmero inteiro

>>>
>>>
5
>>>
-1
>>>
6
>>>
0
>>>
0
>>>
8

b=3
a+b
a-b
a*b
a/b
a // b
a ** b

>>> a = 2
>>> b = 3.5
>>> a + b
5.5
>>> a - b
-1.5
>>> a * b
7.0
>>> a / b
0.5714285714285714
>>> a // b
0.0
>>> a ** b
11.313708498984761

>>> 4 // 1.3
3.0
>>> 10 // 1.3
7.0
>>> 10 // 3.3
3.0
>>> 10%3
1
>>> 10%2
0
>>> 5%3
2

11

Operadores Lgicos
and, or, not
>>>
True
>>>
False
>>>
False
>>>
True
>>>
0

True and True


True and False
False and False
1 and True
0 and True

>>>
True
>>>
True
>>>
False
>>>
1
>>>
False

True or True
False or True
False or False

>>> not True


False
>>> not False
True
>>> not 1
False

1 or False
0 or False

>>> not ((a or False) and (False or False))


True

12

Operadores Relacionais
>, <, >=, <=, ==, !=,
<>
>>>
2 > 3 >>> 2 == 2 >>> x = 3
False
True
>>> 2 < 3 >>> 2
True
False
>>> 3 >= 3>>> 3
True
True
>>> 4 <= 3>>> 3
False
False
>>> 3
False
>>> 2
False
!= e <> significam diferente

>>> 2 < x < 4


== 1 True
>>> 7 > x > 1
!= 2 True
>>> 3 <= x <4
!= 3 True
<> 3
<> 2

13

Operaes com Strings


+, *

[...]

>>> st = 'SPAM'
>>> st + 'SPAM'
'SPAMSPAM'
>>>
>>>
'a'
>>>
'. '
>>>
'3'

>>> st = SPAM
>>> st*3
'SPAMSPAMSPAM'

st = 'arquivo.mp3' >>> st = 'arquivo.mp3'


>>> st[2:]
st[0]
'quivo.mp3'
>>> st[0:-4]
st[-4]
'arquivo'
>>> st[-3:]
st[-1]
'mp3

14

Mtodos de Strings
split(char)
Retorna uma lista com os elementos separados pelo
char
>>> a = '1+2+3+4+5+6'
>>> a.split('+')
['1', '2', '3', '4', '5', '6']

strip(chars)
Retorna uma string onde os chars da direita e da
esquerda foram removidos
>>> a = ' !!! STRING DE RETORNO!
!! ! !'
>>> a.strip(' !')
'STRING DE RETORNO'
15

Mtodos de Strings
find(substring)
Retorna a posio da primeira substring se for
encontrada, seno retorna -1

>>> a = 'is this the


real life?'
>>> a.find('real')
lower(),
12 upper()

>>> a = 'is this the


real life?'
>>> a.find('abacate')
-1

Retornam uma string em minusculo/maisculo


>>> a = 'StRinG!'
>>> a.lower()
'string!'

>>> a = 'StRinG!'
>>> a.upper()
'STRING!'

16

Exerccios
A partir da string !! ! a;b;c;d;e;f;gh!#########
gere o resultado:
[a, b, c, d, e, f, g]
string = '!! ! a;b;c;d;e;f;gh!#########'
print string.strip(' !#h').split(';')

17

Exerccios
A partir da string ring ring! - hello! gere o resultado:
hello!

string = 'ring ring! - hello!'


print string[string.find('hello'):]

string = 'ring ring! - hello!'


print string[13:]

18

Exerccios
Transformar a string isso deve ser bom para Isso
Deve Ser Bom
string = 'isso deve ser bom'
print string.title()
Transformar a string abacate azul em 4b4c4te 4zul
string = 'abacate azul'
print string.replace('a', '4')

19

Desvio Condicional
if condicao:
comandos
elif condicao:
comandos
else:
comandos

>>> a = input('Digite um numero: ')


Digite um numero: 4
>>> if a%2 == 0:
... print Par
... else:
... print Impar
Par

No precisa do ( parntesis ), mas pode ser usado

20

Desvio Condicional
No existe SWITCH/CASE, quando necessrio vrias
comparaes, usamos elifs ou dicionario (explicado
mais frente)
Pode ser escrito em uma linha:
SETRUE if condio else SEFALSE
>>> numero = input('entre com um
numero: ')
entre com um numero: 5
>>> print 'par' if numero%2 == 0
else 'impar'
impar

21

Exerccios
1)Leia dois nmeros e imprima o maior deles
2)Leia uma letra, se for M imprima Masculino, se for
F imprima Feminino, seno imprima Sexo
invalido.
3)Faa um programa em Python o qual receba uma
temperatura em graus Celsius e converta para
Fahrenheit.

IMPORTANTE:
variavel = input() #Para nmeros
variavel = raw_input() #Para strings
22

Vous aimerez peut-être aussi