FGV - Escola de Matemática Aplicada

Curso de Verão - Introdução à Programação com a Linguagem Python

Tipos padrão do Python

O que são tipos?

Tipos são classificações de dados que em Python são objetos. Dessa forma um objeto de determinado tipo possui as propriedades (métodos/funções e atributos) específicos do tipo. Podemos descobrir o tipo de cada objeto usando o comando:

type(objeto)

Tipos Numéricos:

Em Python (3.x) os tipos numéricos são divididos em três classes: os inteiros (int), os pontos flutuantes (float) e os complexos (complex).

In [1]:
a = 12
In [2]:
type(a)
Out[2]:
int
In [4]:
b = 2.7
In [5]:
type(b)
Out[5]:
float
In [6]:
b.is_integer()
Out[6]:
False
In [8]:
c = 3 + 1j
In [9]:
type(c)
Out[9]:
complex
In [10]:
c.conjugate()
Out[10]:
(3-1j)

Operações com tipos numéricos:

In [1]:
print(9 + 8) # Soma.
print(12 - 34) # Subtração.
print(12 * 3) # Multiplicação.
print(34 / 23) # Divisão.
print(3 ** 5) # Exponenciação.
print(9 ** 0.5) # Radiciação.
print(501 % 10) # resto da divisão
17
-22
36
1.4782608695652173
243
3.0
1
In [2]:
a = 23.
print(type(a))
<class 'float'>
In [3]:
b = 2 + 3j
print(type(b))
<class 'complex'>
In [4]:
c = a + b
print(type(c))
<class 'complex'>
Operações com > (maior), < (menor), >= (maior ou igual) e <= (menor ou igual)
In [7]:
c = 2.5
d = 4
c > d
Out[7]:
False
In [8]:
c = 2.5
d = 4
c <= d
Out[8]:
True
In [ ]:
c = 1 + 3j
d = 2 + 4j
c > d
Operação de igualdade (==) e desigualdade (!=)
In [9]:
c == d
Out[9]:
False
In [10]:
d != c
Out[10]:
True

Tipo Lista:

Listas são sequências ordenadas de itens (não necessariamente do mesmo tipo) que são postos entre colchetes e separados por vírgula. Uma característica que faz com que as listas sejam tão utilizadas é a mutabilidade, isto é, seus elementos podem ser alterados.

In [3]:
lista = [1,2,2, [2,3,4], 3.9, 4, 2.8,'uma string']
In [4]:
lista
Out[4]:
[1, 2, 2, [2, 3, 4], 3.9, 4, 2.8, 'uma string']
Acessando elementos da lista

obs.: O primeiro elemento possui índice 0.

In [5]:
lista[3]
Out[5]:
[2, 3, 4]
In [6]:
lista[3][2]
Out[6]:
4
In [25]:
lista[-1]
Out[25]:
'uma string'
Adicionando novos elementos
In [13]:
seu_novo_nome = [2,6,3,8]
In [14]:
seu_novo_nome.append(23)
In [15]:
seu_novo_nome
Out[15]:
[2, 6, 3, 8, 23]

Removendo elementos de uma lista

In [16]:
seu_novo_nome.pop()
Out[16]:
23
In [17]:
seu_novo_nome
Out[17]:
[2, 6, 3, 8]

Inserindo listas e elementos

In [18]:
seu_novo_nome
Out[18]:
[2, 6, 3, 8]
In [19]:
seu_novo_nome.append(4)
In [20]:
seu_novo_nome.extend([0,7,3])
In [21]:
seu_novo_nome
Out[21]:
[2, 6, 3, 8, 4, 0, 7, 3]
In [34]:
seu_novo_nome.append([9,9])
In [35]:
seu_novo_nome.insert(2,5678)
In [36]:
seu_novo_nome
Out[36]:
[2, 6, 5678, 3, 8, 4, 0, 7, 3, [9, 9]]
In [37]:
seu_novo_nome.pop()
Out[37]:
[9, 9]
In [38]:
seu_novo_nome.sort() #Colocando em ordem
seu_novo_nome
Out[38]:
[0, 2, 3, 3, 4, 6, 7, 8, 5678]

Acessando elementos

In [22]:
nova2 = [[[2,1],7,9,3,3,2,[2,6]],4,5,7]
In [41]:
nova2[0]
Out[41]:
[[2, 1], 7, 9, 3, 3, 2, [2, 6]]
In [42]:
nova2[0].index(2)
Out[42]:
5
In [43]:
len(nova2) #len() serve para dar o tamanho do objeto
Out[43]:
4
In [26]:
nova2[0].count(3)
Out[26]:
2
In [27]:
nova2[0][3]
Out[27]:
3
In [46]:
nova2.index(4)
Out[46]:
1
In [28]:
nova2.reverse()
print(nova2)
[7, 5, 4, [[2, 1], 7, 9, 3, 3, 2, [2, 6]]]
In [30]:
nova_lista = [1,2,3,4,5,6]
In [31]:
nova_lista[2]
Out[31]:
3
In [32]:
nova_lista[2:5]
Out[32]:
[3, 4, 5]
In [33]:
nova_lista[-2]
Out[33]:
5

Tipo String:

Strings são sequências de caracteres dispostos, necessariamente, entre aspas simples ou duplas.

In [35]:
s1 = 'uma string'
s2 = "outra string"
In [36]:
print(s1)
uma string
In [37]:
s1
Out[37]:
'uma string'
In [38]:
s2
Out[38]:
'outra string'
In [39]:
s3 = "let's go to the classroom"
s3
Out[39]:
"let's go to the classroom"
In [48]:
s4 = "nesta string eu tenho aspas simples (') e aspas duplas(\")"
In [49]:
s4
Out[49]:
'nesta string eu tenho aspas simples (\') e aspas duplas(")'
In [50]:
print(s4)
nesta string eu tenho aspas simples (') e aspas duplas(")
In [ ]:
s5 = 'let\'s stress'
s5

Concatenando strings

In [ ]:
s1+s2
In [53]:
s1+' '+s2
Out[53]:
'uma string outra string'
In [66]:
print('um comando' + ' ' + 'que ocupe' + ' ' + 'duas ou mais linhas')
um comando que ocupe duas ou mais linhas
In [57]:
s6 = 'RIO - Brasília fechou 2015 com uma inflação de 11,95%, segundo o Índice de Preços \
ao Consumidor Semanal (IPC-S), medido pela Fundação Getulio Vargas (FGV). Entre as sete \
capitais pesquisadas pela FGV, a capital federal foi a que teve a maior alta de preços. \
Em 2014, Brasília havia registrado uma taxa de inflação de 6,74%.'
In [58]:
s6
Out[58]:
'RIO - Brasília fechou 2015 com uma inflação de 11,95%, segundo o Índice de Preços ao Consumidor Semanal (IPC-S), medido pela Fundação Getulio Vargas (FGV). Entre as sete capitais pesquisadas pela FGV, a capital federal foi a que teve a maior alta de preços. Em 2014, Brasília havia registrado uma taxa de inflação de 6,74%.'
In [59]:
print(s6)
RIO - Brasília fechou 2015 com uma inflação de 11,95%, segundo o Índice de Preços ao Consumidor Semanal (IPC-S), medido pela Fundação Getulio Vargas (FGV). Entre as sete capitais pesquisadas pela FGV, a capital federal foi a que teve a maior alta de preços. Em 2014, Brasília havia registrado uma taxa de inflação de 6,74%.
In [60]:
s7 = '''
RIO - Brasília fechou 2015 com uma inflação de 11,95%, 
segundo o Índice de Preços ao Consumidor Semanal (IPC-S), 
medido pela Fundação Getulio Vargas (FGV). 
Entre as sete capitais pesquisadas pela FGV, a capital federal foi 
a que teve a maior alta de preços. Em 2014, Brasília havia registrado 
uma taxa de inflação de 6,74%.
'''
In [61]:
s7
Out[61]:
'\nRIO - Brasília fechou 2015 com uma inflação de 11,95%, \nsegundo o Índice de Preços ao Consumidor Semanal (IPC-S), \nmedido pela Fundação Getulio Vargas (FGV). \nEntre as sete capitais pesquisadas pela FGV, a capital federal foi \na que teve a maior alta de preços. Em 2014, Brasília havia registrado \numa taxa de inflação de 6,74%.\n'
In [63]:
print(s7)
RIO - Brasília fechou 2015 com uma inflação de 11,95%, 
segundo o Índice de Preços ao Consumidor Semanal (IPC-S), 
medido pela Fundação Getulio Vargas (FGV). 
Entre as sete capitais pesquisadas pela FGV, a capital federal foi 
a que teve a maior alta de preços. Em 2014, Brasília havia registrado 
uma taxa de inflação de 6,74%.

In [64]:
texto = 'uma linha \noutra linha'
print(texto)
uma linha 
outra linha
In [65]:
s4
Out[65]:
'nesta string eu tenho aspas simples (\') e aspas duplas(")'

Contando o número de aparições de um caracter

In [66]:
s4.count('a')
Out[66]:
6

Modificando caracteres

In [75]:
s4 = s4.replace('a','@')
In [76]:
s4
Out[76]:
'nest@ string eu tenho @sp@s simples (\') e @sp@s dupl@s(")'

Encontrando a posição da palavra

In [77]:
s4.find('simples')
Out[77]:
28
In [81]:
s4[6]
Out[81]:
's'
In [78]:
s4[28:]
Out[78]:
'simples (\') e @sp@s dupl@s(")'
In [79]:
s4[s4.find('string'):s4.find('simples')+len('simples')]
Out[79]:
'string eu tenho @sp@s simples'
In [82]:
s4[6:35]
Out[82]:
'string eu tenho @sp@s simples'

Fazendo mais elegantemente

In [83]:
inicio = s4.find('string')
fim = s4.find('simples')+len('simples')
s4[inicio:fim]
Out[83]:
'string eu tenho @sp@s simples'
In [68]:
a = 12
b = int('12')
a + b
Out[68]:
24
In [71]:
c = str(12)
d = '12'
c + d
Out[71]:
'1212'
In [72]:
c.isdigit()
Out[72]:
True
In [69]:
x = 0xFFF
x
Out[69]:
4095
In [88]:
y = 0b111110001
y
Out[88]:
497
In [89]:
z = 0o777321
z
Out[89]:
261841
In [90]:
0b11111111
Out[90]:
255

Tipo Booleano:

Serve para criação de estruturas lógicas e criação de condicionais retornando somente True ou False.

In [91]:
'RENATO'.isupper()
Out[91]:
True
In [92]:
b1 = True
In [93]:
b2 = False
In [94]:
b1 == b2
Out[94]:
False
In [95]:
2 == 5
Out[95]:
False
In [96]:
type(2 == 7)
Out[96]:
bool
In [97]:
4 != 5
Out[97]:
True
In [98]:
if (9 > 10) and (2 == (1 + 1)) and (7 <= 8):
    print('Correto')
if x == 4095:
    print('Legal')
else:
    print('chato')
print('novo bloco')
Legal
novo bloco

Tipo Conjunto (sets):

Set são sequências nãoordenada de itens únicos. Os itens são postos entre chaves e separados por vírgula.

In [101]:
c1 = {1,2,3,3,3,3,3,4}
In [102]:
c1
Out[102]:
{1, 2, 3, 4}
In [103]:
c2 = set([1,2,3,4,1,2])
In [104]:
c2
Out[104]:
{1, 2, 3, 4}
In [105]:
lista3 = [1,2,3,'string']
In [106]:
conjunto = set(lista3)
In [107]:
conjunto
Out[107]:
{1, 2, 3, 'string'}
In [108]:
conjunto2 = conjunto.union([9,8,7])
In [109]:
conjunto2
Out[109]:
{1, 2, 3, 'string', 7, 8, 9}
In [115]:
conjunto.intersection(conjunto2)
Out[115]:
{1, 2, 3, 'string'}
In [116]:
lista3 = list(conjunto)
In [117]:
conjunto4 = set('uma string legal')
In [118]:
conjunto4
Out[118]:
{' ', 'a', 'e', 'g', 'i', 'l', 'm', 'n', 'r', 's', 't', 'u'}
In [119]:
print(len('uma string legal'))
print(len(set('uma string legal')))
16
12
In [147]:
texto = '''
There are two candidates for the TIOBE programming language of the year award that will be announced around the 1st of January 2015. These are statistical language R (+1.38%) and Apple's new Swift language (+1.06%). Apart from these, also JavaScript and Dart have a chance to win. The award is given to the language with the highest increase in ratings in 2014. Visual Basic has the highest delta but it doesn't qualify for the award because it has been introduced as a split off of the general Basic entry. 
'''
In [148]:
texto
Out[148]:
"\nThere are two candidates for the TIOBE programming language of the year award that will be announced around the 1st of January 2015. These are statistical language R (+1.38%) and Apple's new Swift language (+1.06%). Apart from these, also JavaScript and Dart have a chance to win. The award is given to the language with the highest increase in ratings in 2014. Visual Basic has the highest delta but it doesn't qualify for the award because it has been introduced as a split off of the general Basic entry. \n"
In [133]:
#texto = texto.replace('a','&&&&a')
In [135]:
lista_palavras = texto.split()
lista_palavras
Out[135]:
['There',
 'are',
 'two',
 'candidates',
 'for',
 'the',
 'TIOBE',
 'programming',
 'language',
 'of',
 'the',
 'year',
 'award',
 'that',
 'will',
 'be',
 'announced',
 'around',
 'the',
 '1st',
 'of',
 'January',
 '2015.',
 'These',
 'are',
 'statistical',
 'language',
 'R',
 '(+1.38%)',
 'and',
 "Apple's",
 'new',
 'Swift',
 'language',
 '(+1.06%).',
 'Apart',
 'from',
 'these,',
 'also',
 'JavaScript',
 'and',
 'Dart',
 'have',
 'a',
 'chance',
 'to',
 'win.',
 'The',
 'award',
 'is',
 'given',
 'to',
 'the',
 'language',
 'with',
 'the',
 'highest',
 'increase',
 'in',
 'ratings',
 'in',
 '2014.',
 'Visual',
 'Basic',
 'has',
 'the',
 'highest',
 'delta',
 'but',
 'it',
 "doesn't",
 'qualify',
 'for',
 'the',
 'award',
 'because',
 'it',
 'has',
 'been',
 'introduced',
 'as',
 'a',
 'split',
 'off',
 'of',
 'the',
 'general',
 'Basic',
 'entry.']
In [136]:
palavras_unicas = set(lista_palavras)
In [137]:
print(len(lista_palavras))
print(len(palavras_unicas))
89
65
In [140]:
' @ '.join(lista_palavras)
Out[140]:
"There @ are @ two @ candidates @ for @ the @ TIOBE @ programming @ language @ of @ the @ year @ award @ that @ will @ be @ announced @ around @ the @ 1st @ of @ January @ 2015. @ These @ are @ statistical @ language @ R @ (+1.38%) @ and @ Apple's @ new @ Swift @ language @ (+1.06%). @ Apart @ from @ these, @ also @ JavaScript @ and @ Dart @ have @ a @ chance @ to @ win. @ The @ award @ is @ given @ to @ the @ language @ with @ the @ highest @ increase @ in @ ratings @ in @ 2014. @ Visual @ Basic @ has @ the @ highest @ delta @ but @ it @ doesn't @ qualify @ for @ the @ award @ because @ it @ has @ been @ introduced @ as @ a @ split @ off @ of @ the @ general @ Basic @ entry."
In [141]:
import string
In [142]:
string.punctuation
Out[142]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
In [149]:
for punct in ['.','?','!']:
    texto = texto.replace(punct, '*****')
texto
Out[149]:
"\nThere are two candidates for the TIOBE programming language of the year award that will be announced around the 1st of January 2015***** These are statistical language R (+1*****38%) and Apple's new Swift language (+1*****06%)***** Apart from these, also JavaScript and Dart have a chance to win***** The award is given to the language with the highest increase in ratings in 2014***** Visual Basic has the highest delta but it doesn't qualify for the award because it has been introduced as a split off of the general Basic entry***** \n"
In [150]:
texto.split('*****')
Out[150]:
['\nThere are two candidates for the TIOBE programming language of the year award that will be announced around the 1st of January 2015',
 ' These are statistical language R (+1',
 "38%) and Apple's new Swift language (+1",
 '06%)',
 ' Apart from these, also JavaScript and Dart have a chance to win',
 ' The award is given to the language with the highest increase in ratings in 2014',
 " Visual Basic has the highest delta but it doesn't qualify for the award because it has been introduced as a split off of the general Basic entry",
 ' \n']
In [168]:
string5 = 'uma string'
string5 += ' outro texto'
In [169]:
string5
Out[169]:
'uma string outro texto'

Tipo Dicionário:

Dicionários são sequências não ordenadas de itens na forma de pares key:values que se encontram dentro de chaves e separados por vírgula. Como value podemos usar objetos de qualquer tipo, já como key só podemos usar objetos de tipos imutáveis (strings, números ou tuplas).

In [2]:
dic = {'chave1':[1,2,3],'chave2':2,'outra chave':4,45:26, 'outro':23}
dic
Out[2]:
{'outra chave': 4, 'chave2': 2, 45: 26, 'chave1': [1, 2, 3], 'outro': 23}
In [3]:
dic.update({2:3})
In [4]:
dic
Out[4]:
{'outra chave': 4, 'chave1': [1, 2, 3], 2: 3, 'chave2': 2, 45: 26, 'outro': 23}
In [6]:
ficha = {'Peso':73, 'Altura':183, 'Idade':44, 'Nome':'Renato'}
In [7]:
ficha
Out[7]:
{'Altura': 183, 'Idade': 44, 'Nome': 'Renato', 'Peso': 73}
In [8]:
ficha['Idade']
Out[8]:
44

Exercício:
Criar uma estrutura de dados para representar as notas de 3 avaliações (A1, A2 e AS) em três disciplinas (Matemática, História e Geografia)

In [12]:
boletim = {'Matemática':{'A1':9.0, 'A2':8.0,'AS':4.0},
           'História':{'A1':9.0, 'A2':8.0,'AS':4.0},
           'Geografia':{'A1':9.0, 'A2':8.0,'AS':4.0}}
boletim
Out[12]:
{'Geografia': {'A1': 9.0, 'A2': 8.0, 'AS': 4.0},
 'História': {'A1': 9.0, 'A2': 8.0, 'AS': 4.0},
 'Matemática': {'A1': 9.0, 'A2': 8.0, 'AS': 4.0}}
In [16]:
boletim['Matemática']['A2']
Out[16]:
24.0
In [23]:
boletim.items()
Out[23]:
dict_items([('Matemática', {'A1': 9.0, 'AS': 4.0, 'A2': 8.0}), ('História', {'A1': 9.0, 'AS': 4.0, 'A2': 8.0}), ('Geografia', {'A1': 9.0, 'AS': 4.0, 'A2': 8.0})])
In [28]:
'A2' in boletim['Matemática']
Out[28]:
True
In [33]:
boletim['Matemática'].values()
Out[33]:
dict_values([9.0, 4.0, 8.0])
In [43]:
boletim['Matemática']['AS'] = 10
boletim
Out[43]:
{'Geografia': {'A1': 9.0, 'A2': 8.0, 'AS': 4.0},
 'História': {'A1': 9.0, 'A2': 8.0, 'AS': 4.0},
 'Matemática': {'A1': 9.0, 'A2': 8.0, 'AS': 10}}
In [34]:
newdic = {}
In [35]:
newdic
Out[35]:
{}
In [36]:
newdic['elemento1'] = 23
In [37]:
newdic
Out[37]:
{'elemento1': 23}
In [38]:
newdic.update({'um':2})
In [39]:
newdic
Out[39]:
{'elemento1': 23, 'um': 2}
In [40]:
newdic['um'] = 1
In [44]:
newdic
Out[44]:
{'elemento1': 23, 'um': 1}
In [46]:
d2 = {}
d1 = {1:d2}
d2 = {2:d1}
In [51]:
d1
Out[51]:
{1: 'outra coisa'}
In [48]:
d2
Out[48]:
{2: {1: {}}}
In [50]:
d2[2][1] = 'outra coisa'
In [ ]:
d1[2]='outro elemento'
In [ ]:
d2

Tipo Tupla:

Tuplas, assim como listas, são sequências ordenadas de itens. As diferenças entre elas são: os elementos estão entre parênteses e as tuplas são imutáveis, seus elementos não podem ser modificados.

In [69]:
t = (1,2,3,4,7,4,3,1,'string',{1,2}, [1,2])
In [70]:
type(t)
Out[70]:
tuple
In [66]:
t[0]
Out[66]:
1
In [67]:
t[5]
Out[67]:
4
In [68]:
t[3:6]
Out[68]:
(4, 7, 4)
In [61]:
lista = [1,2,3]
In [62]:
tupla = tuple(lista)
In [63]:
tupla
Out[63]:
(1, 2, 3)
In [59]:
lista2 = list(tupla)
In [60]:
lista2
Out[60]:
[1, 2, 3]
In [72]:
d5 = {(1,2):'tupla'}
d5
Out[72]:
{(1, 2): 'tupla'}
In [76]:
t2 = (2,4,7,2,2,2,2)
In [77]:
t2.count(2)
Out[77]:
5
In [88]:
a = [1,2]
In [89]:
t = (a,a,a,a,a)
l = [a,a,a,a,a]

Várias formas para importação de módulos:

Importando o pacote inteiro:

In [2]:
import string
import random
import math
import numpy
In [5]:
string.punctuation
Out[5]:
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
In [6]:
random.random()
Out[6]:
0.7554019509574217
In [7]:
math.pi
Out[7]:
3.141592653589793
In [8]:
numpy.pi
Out[8]:
3.141592653589793

Importando do pacote determinada função

In [9]:
from math import *
In [10]:
pi
Out[10]:
3.141592653589793
In [12]:
e = [1,2,3]
In [13]:
from math import *
In [14]:
e
Out[14]:
2.718281828459045
In [17]:
from numpy import mean, pi
In [16]:
mean([1,2,3,4,5,6,7,8,9])
Out[16]:
5.0
In [18]:
pi
Out[18]:
3.141592653589793
In [19]:
math.pi == numpy.pi
Out[19]:
True

Importando o pacote e atribuindo-o outro nome

In [25]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
In [26]:
plt.plot([1,2,3,4,5,6,4,3,2,1])
Out[26]:
[<matplotlib.lines.Line2D at 0x8d255f8>]
In [27]:
plt.show()
In [73]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [ ]: