DEV Community

Anna Karolina
Anna Karolina

Posted on

Introdução de Python

Para quem usa Windows vá em www.python.org/downloads/ e baixe Python 3.5.2. Ao instalar não esqueça de marcar o check 'Add Python 3.5 to PATH'.

Para quem usa Linux ou Mac sugiro este tutorial de instalação com pyenv.

python -V
IPython
sudo -H pip install ipython

Python é interpretado
O que são os *.pyc?

Contém os bytecodes compilados a partir do arquivo .py.

Python é uma linguagem interpretada. Mas também compila. Leia mais aqui.

O Python também pode gerar um .exe para Windows. Veja py2exe.

Tipagem Dinâmica

exemplo:

>>> a = 42
>>> type(a)
<class 'int'>
>>> b = 3.14
>>> type(b)
<class 'float'>
>>> t = 'palavra'
>>> type(t)
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

O interpretador Python

$ python
Python 3.5.0 (default, Dec  8 2015, 01:17:16) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Enter fullscreen mode Exit fullscreen mode

Executando programas Python direto pelo terminal.

$ python -c "print(40 + 2)"

Enter fullscreen mode Exit fullscreen mode

Indo além do Hello World

from datetime import datetime
from time import sleep

while True:
    hora = datetime.now()
    print(hora.strftime('%H:%M:%S'))
    sleep(1)
Enter fullscreen mode Exit fullscreen mode

eu quero ir para:

for i in range(1, 11):
    j = i * i
    print(i, j)

print('fim')
Enter fullscreen mode Exit fullscreen mode

Mão na massa

lanches.py

import sys
from random import choice

lanches = ['Hot-Dog', 'X-Salada', 'Tapioca', 'Pizza', 'Batata Frita']
bebidas = ['Coca-Cola', 'Fanta', 'Guaraná', 'Suco de Laranja', 'Cerveja']
numero = input('Digite um número de 0 a 4: ')


if int(numero) > 4:
    print('O número digitado está fora do intervalo.')
    # Experimente digitar -5 e -6
    sys.exit(1)


def bebida():
    return choice(bebidas)


for i in range(3):
    if i == 0:
        print('Primeira refeição: %s + %s' % (lanches[int(numero)], bebida()))
    elif i == 1:
        print('Segunda refeição: %s + %s' % (lanches[int(numero)], bebida()))
    else:
        print('Terceira refeição: %s + %s' % (lanches[int(numero)], bebida()))
Enter fullscreen mode Exit fullscreen mode

O módulo principal do Python

def hello():
    print('Hello World')


if __name__ == '__main__':
    print('Oi')
Enter fullscreen mode Exit fullscreen mode

O segredo de um código pythônico

'''
Um comentário de múltiplas linhas.
Também conhecido como Docstring.
'''
Enter fullscreen mode Exit fullscreen mode
import os


def main():
    print('Hello world!')
    print("O'Relly")
    print('O\'Relly')

    my_sum(5, 10)

    print('=' * 10)
    text = 'O diretório atual é '
    print(text + os.getcwd())

    foods = ['maçãs', 'laranjas', 'bananas']

    for food in foods:
        print('Eu gosto de', food)

    print('Contando até dez:')
    for i in range(1, 11):
        print(i)


def my_sum(a, b):
    value = a + b

    print('%s mais %s é igual a %s' % (a, b, value))

    if value < 50:
        print('foo')
    elif (value >= 50) and \
         ((a == 42) or (b == 24)):
        print('bar')
    else:
        print('moo')

    return value  # comentário de uma linha


if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Importando sua própria biblioteca

mycapitalize.py

def _capitalize(texto):
    return texto.capitalize()
Enter fullscreen mode Exit fullscreen mode

palavras.py

from mycapitalize import _capitalize

palavras = 'joaquim josé da silva xavier'
nome = []

for palavra in palavras.split():
    print(_capitalize(palavra))
    nome.append(_capitalize(palavra))

print(' '.join(nome))
Enter fullscreen mode Exit fullscreen mode

Operadores

(2 ** 10 + 3 * 2) / (48 - 46 + 1976 / 2 + 40)

7 / 3

7 // 3

7 % 3
Enter fullscreen mode Exit fullscreen mode

Operadores = + - * / ** % //


bin(4)
bin(7)

import math
math.sqrt(25)
math.log(100,10)
math.log(27,3)
math.sin(math.pi/2)
math.pi
from math import radians, pi
radians(180)
radians(180) == pi
Enter fullscreen mode Exit fullscreen mode

Strings

'k' * 5
'Guido' + ' Van' + ' Rossum'
'Av. ' + str(23) + ' de Maio'
nome = 'joaquim josé da silva xavier'
nome.capitalize()
nome.lower()
nome.split()
nome.title()
nome.upper()
Enter fullscreen mode Exit fullscreen mode

Replace

nome.replace('a','4')
Enter fullscreen mode Exit fullscreen mode

Slices

palavra = 'paralelepípedo'
len(palavra)
palavra[0]
palavra[0:3]
palavra[:3]
palavra[4:8]
palavra[8:]
palavra[1:10:2]
palavra[1::2]
palavra[-1]
palavra[:-1]
palavra[::-1]
Enter fullscreen mode Exit fullscreen mode

Listas

Toda lista é mutável

lista = [42, 'palavra', 3.14, 2 + 3j, [1, 2, 3]]
for i in lista: print(i)

lista[0]
lista[-1]
lista[-1][-1]
lista.append('mais')
lista.remove('palavra')

L = [100, 2, 80, 7, -5, 42]
L
L.sort()
L

N = [30, 10, 20]
sorted(N)
N

Enter fullscreen mode Exit fullscreen mode

Pilhas com lista


a = ['zero', 'um', 'dois', 'três']
a.append('quatro')
a
a.append('cinco')
a
a.pop()
a
a.pop(2)
a
Enter fullscreen mode Exit fullscreen mode

Tuplas

São objetos imutáveis.

t = (1, 2, 3)
type(t)
# uma tupla de tuplas


Enter fullscreen mode Exit fullscreen mode

posicoes = ((1, 2), (2, 2), (5, 2), (0, 3))


# um jeito de percorrer

Enter fullscreen mode Exit fullscreen mode

for pos in posicoes:
i, j = pos
print(i, j)

print('-' * 10)


# outra forma de percorrer
for i, j in posicoes:
    print(i, j)
Enter fullscreen mode Exit fullscreen mode

Split


palavras = 'joaquim josé da silva xavier'
palavras.split()
Enter fullscreen mode Exit fullscreen mode

While

n = 1
while(n < 11):
    print('n =', n)
n = 1
while(n < 11):
    print('n =', n)
    n = n + 1

print('Fim do loop')
Enter fullscreen mode Exit fullscreen mode

for

for n in range(1, 5):
    print('n =', n)

print('Fim do loop')
for n in range(5):
    for j in ['a', 'b', 'c']:
        print('n =', n, 'e j =', j, '--> ', str(n) + ',' + str(j))
letters = 'Python'
for letter in letters:
    print(letter)
lista = ['', 'Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab']
for idx, item in enumerate(lista):
    print(idx, item)
Enter fullscreen mode Exit fullscreen mode

if else (condições)

a > b
a < b
a >= b
a <= b
a != b
a == b
Enter fullscreen mode Exit fullscreen mode

Tabela verdade

True and True
True and False
False and True
False and False
True or True
True or False
False or True
False or False
not True
not False
if 2 + 2 == 4:
    print('Ok')
else:
    print('Errado')
if True:
    print('Verdadeiro')
else:
    print('Falso')
Enter fullscreen mode Exit fullscreen mode

Coloque o not no exemplo anterior e veja o resultado.

if 3 % 2:
    print('Três é impar')
notas = [7, 4, 3.9]
for nota in notas:
    if nota >= 7:
        print('Aprovado')
    elif nota >= 4:
        print('Recuperação')
    else:
        print('Reprovado')
Enter fullscreen mode Exit fullscreen mode

List Comprehensions

[x ** 2 for x in range(10)]

Enter fullscreen mode Exit fullscreen mode

Soma de vetores

a = [1, 2]
b = [9, 18]

c = []
for i in range(len(a)):
    c.append((a[i], b[i]))

for x, y in c: print(x + y)

for i in range(len(a)): print(a[i] + b[i])
[x + y for x, y in zip(a,b)]
list(map(sum, zip(a, b)))
Multiplicação por escalar

vec = [1, 2, 3]
[x * 2 for x in vec]
def vogal(c):
    return c.lower() in 'aeiou'

print(vogal('a'))
print(vogal('b'))

palavra = 'abacaxi'
vogais = [letra for letra in palavra if vogal(letra)]
print(vogais)
Enter fullscreen mode Exit fullscreen mode

type(), help(), dir()

lista = [3, 2, 1]
type(lista)
help(lista)
dir(lista)
type(3.14)
type('palavra')
dir('palavra')
Enter fullscreen mode Exit fullscreen mode

atribuições múltiplas

a, b = 0, 1
a
b
c, d, e = range(3)
c
d
e
vars = ('A', 2, 'C')
a, b, c = vars
Enter fullscreen mode Exit fullscreen mode

Dicionários

São coleções de valores identificados por chaves únicas.

{'chave': valor}

uf = {'SP': 'São Paulo', 'RJ': 'Rio de Janeiro', 'MG': 'Minas Gerais'}
uf['SP']
uf['RJ']
uf['PR']
uf['PR'] = 'Paraná'
for chave in uf:
    print(chave)
for chave, valor in uf.items():
    print(chave, valor)
for chave, valor in sorted(uf.items()):
    print(chave, valor)
Enter fullscreen mode Exit fullscreen mode

As chaves são sempre únicas
As chaves têm que ser objetos imutáveis
Qualquer objeto pode ser um valor
A ordem de armazenamento das chaves é indefinida
Dicionários são otimizados para acesso direto a um item pela chave, e não para acesso sequencial em determinada ordem.
Dicionários: operações básicas
Criar um dicionário vazio

d = {}
d = dict()
Enter fullscreen mode Exit fullscreen mode

Acessar um item do dicionário


print(d[chave])
Enter fullscreen mode Exit fullscreen mode

Adicionar ou sobrescrever um item

d[chave] = valor
Enter fullscreen mode Exit fullscreen mode

Remover um item


del d[chave]
Enter fullscreen mode Exit fullscreen mode

Verificar a existência de uma chave


d.has_key(c)
c in d
Enter fullscreen mode Exit fullscreen mode

Obter listas de chaves, valores e pares

d.keys()
d.values()
d.items()
Acessar um item que talvez não exista

d.get(chave, 'Python') # retorna None ou o valor default
for nome in uf.values():
    print(nome)
for nome in sorted(uf.values()):
    print(nome)
Enter fullscreen mode Exit fullscreen mode

Funções

def message():
    pass
def message():
    return 'Hello World'
def soma(a, b):
    return a + b
Argumentos Posicionais
def func(a, b, c):
    print(a, b, c)

if __name__ == '__main__':
    func(a=1, c=2, b=3)
Valores padrão
def func(a, b=4, c=42):
    print(a, b, c)

if __name__ == '__main__':
    func(1)
    func(b=5, a=7, c=9)
    func(40, c=9)
def func(*args):
    print('Positional:', args)

if __name__ == '__main__':
    lista = [-1, 100, 0, 2, 3, 4]
    func(lista)
    func(*lista)
def func(*args):
    print('Positional:', args)

if __name__ == '__main__':
    lista = [-1, 100, 0, 2, 3, 4]
    func(lista)
    func(*lista)
Enter fullscreen mode Exit fullscreen mode

Argumentos Posicionais Variáveis

'''

minimum(1, 3, -7, 9)
-7
'''


def minimum(*n):
    if n:
        mn = n[0]
        for value in n[1:]:
            if value < mn:
                mn = value
        return mn

if __name__ == '__main__':
    lista = [1, 3, -7, 9]
    print(minimum(*lista))
python -m doctest minimum.py
Argumentos Nomeados
def func(**kwargs):
    print('Keywords:', kwargs)

if __name__ == '__main__':
    func(a=1, b=42)
    dic = {'a': 1, 'b': 42}
    func(**dic)
Tudo misturado
def func(a, b, c=7, *args, **kwargs):
    print('a, b, c:', a, b, c)
    print('args:', args)
    for i in args:
        print(i)
    print('kwargs:', kwargs)
    for k in kwargs:
        print(k, kwargs[k])
Enter fullscreen mode Exit fullscreen mode
if __name__ == '__main__':
    func(1, 2, 3, *(5, 7, 9), **{'A': 'a', 'B': 'b'})
python function_all.py
Lambda
São funções anônimas.

l = lambda x: x * 2
print(l(3))

for i in range(11):
    l = lambda x: x * i
    print(l(3))
Enter fullscreen mode Exit fullscreen mode

Programação funcional e lambda

Números ímpares gerado com programação funcional e lambda.

nums = range(1,11)
print(list(filter(lambda x: x % 2, nums)))
Enter fullscreen mode Exit fullscreen mode

Módulos

gen_random_values.py

from datetime import date, datetime, timedelta
from random import randint, random
Enter fullscreen mode Exit fullscreen mode

def gen_number():
    return randint(1, 10)
Enter fullscreen mode Exit fullscreen mode
def gen_date(min_year=1900, max_year=datetime.now().year):
    # gera um date no formato yyyy-mm-dd
    start = date(min_year, 1, 1)
    years = max_year - min_year + 1
    end = start + timedelta(days=365 * years)
    return start + (end - start) * random()
Enter fullscreen mode Exit fullscreen mode
def convert_date(d):
    # converte data no formato mês, dia, ano.
    return d.strftime('%m/%d/%Y')
Enter fullscreen mode Exit fullscreen mode

Abra o interpretador Python


Enter fullscreen mode Exit fullscreen mode

from gen_random_values import gen_number, gen_date, convert_date
gen_number()
gen_date()
convert_date(gen_date())
Testes
Doctest
'''
square(2)
4
square(3)
9
square(4)
16


'''

Enter fullscreen mode Exit fullscreen mode

def square(n):
return n ** 2

print(square(2))
print(square(3))
print(square(4))
python -m doctest square.py
Teste simples
def test_par():
assert par(0) == True
assert par(1) == False

if name == 'main':
test_par()

Enter fullscreen mode Exit fullscreen mode

python par.py
Definição: Seja P o conjunto dos números inteiros pares, então:

P = {x \in \Z | x = 2y, y \in \Z}

Enter fullscreen mode Exit fullscreen mode

Número par é todo número que ao ser dividido por dois deixa resto zero.

P = {x \in \Z | x mod 2 = 0}

Arrumando o código temos:

Enter fullscreen mode Exit fullscreen mode

def par(n):
if n % 2 == 0:
return True
return False

def test_par():
assert par(0) == True
assert par(1) == False
assert par(2) == True
assert par(4) == True
assert par(42) == True

if name == 'main':
test_par()
Existe uma outra solução para este problema:

def par(n):
return n % 2 == 0
Unittest
unittest

import unittest

class EvenNumberTest(unittest.TestCase):

def test_par(self):
    self.assertTrue(par(0))
    self.assertFalse(par(1))
    # self.assertTrue(par(2))
    # self.assertTrue(par(4))
    # self.assertTrue(par(42))
Enter fullscreen mode Exit fullscreen mode

if name == 'main':
unittest.main()

Enter fullscreen mode Exit fullscreen mode

python par2.py
Agora separamos os testes colocando um assert por teste.

import unittest


def par(n):
    pass

Enter fullscreen mode Exit fullscreen mode
class EvenNumberTest(unittest.TestCase):

    def test_0(self):
        self.assertEqual(par(0), True)

    def test_1(self):
        self.assertEqual(par(1), False)

    def test_2(self):
        self.assertEqual(par(2), True)

    def test_4(self):
        self.assertEqual(par(4), True)

    def test_42(self):
        self.assertEqual(par(42), True)


if __name__ == '__main__':
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

Vendo o resultado de todos os asserts.

python par3.py -v
Try/except
def divide(n, d):
return n / d

if __name__ == '__main__':
    n = int(input('Digite um numerador:'))
    d = int(input('Digite um denominador:'))
    divide(n, d)
Enter fullscreen mode Exit fullscreen mode

Arrumando

def divide(n, d):
    try:
        result = n / d
    except ZeroDivisionError as zde:
        print(zde)
    else:
        print('O resultado é:', result)
        return result

if __name__ == '__main__':
    n = int(input('Digite um numerador:'))
    d = int(input('Digite um denominador:'))
    divide(n, d)
Random
from random import randint, random, randrange, choice
colors = ['azul', 'amarelo', 'rosa', 'verde', 'laranja', 'cinza', 'preto', 'branco', 'marrom']
for i in range(1,11): print(i, choice(colors))
Enter fullscreen mode Exit fullscreen mode

randint(10,20)
random()
randrange(0,100,10)
I/O
Ler/Escrever CSV

Escrever
import csv

with open('file.csv', 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow([1, 'Um', 'One'])
    extra_rows = [[2, 'Dois', 'Two'], [3, 'Três', 'Three']]
    csv_writer.writerows(extra_rows)
Enter fullscreen mode Exit fullscreen mode

Ler
Considere o CSV a seguir:

id,username,email
1,admin,admin@example.com
2,regis,regis@example.com
3,pedro,pedro@example.com
4,aline,aline@example.com
5,bianca,bianca@example.com
import csv

with open('users.csv') as f:
    users_reader = csv.reader(f)
    for row in users_reader:
        print(row)
Resultado dos print do bloco anterior:

['id', 'username', 'email']
['1', 'admin', 'admin@example.com']
['2', 'regis', 'regis@example.com']
['3', 'pedro', 'pedro@example.com']
['4', 'aline', 'aline@example.com']
['5', 'bianca', 'bianca@example.com']
Enter fullscreen mode Exit fullscreen mode

Note que cada row é uma lista de strings. Para retornar um dicionário podemos fazer:

import csv

with open('users.csv') as f:
    users_reader = csv.DictReader(f)
    for row in users_reader:
        print(row['id'], row['username'], row['email'])
Enter fullscreen mode Exit fullscreen mode

Resultado dos print do bloco anterior:

1 admin admin@example.com
2 regis regis@example.com
3 pedro pedro@example.com
4 aline aline@example.com
5 bianca bianca@example.com
JSON
todo

Orientação a Objetos
Abra o interpretador ipython e digite:

TV

class Televisao():
    def __init__(self):
        self.ligada = False
        self.canal = 2

tv_quarto = Televisao()
tv_sala = Televisao()
tv_quarto.ligada
tv_quarto.canal
tv_sala.ligada = True
tv_sala.canal = 5
tv_sala.ligada
tv_sala.canal
Enter fullscreen mode Exit fullscreen mode

Agora crie um programa chamado tv.py.

class Televisao():

    def __init__(self):
        self.ligada = False
        self.canal = 2

    def muda_canal_para_baixo(self):
        self.canal -= 1

    def muda_canal_para_cima(self):
        self.canal += 1


if __name__ == '__main__':
    tv = Televisao()
    print('Canal inicial:', tv.canal)

    print('Ligada:', tv.ligada)

    tv.ligada = True
    tv.canal = 5

    print('Ligada:', tv.ligada)
    print('Canal inicial:', tv.canal)
    tv.muda_canal_para_cima()
    print('Canal +', tv.canal)
    tv.muda_canal_para_cima()
    print('Canal +', tv.canal)
    tv.muda_canal_para_baixo()
    print('Canal -', tv.canal)
Veículos
class Veiculo(object):

    def __init__(self):
        self.porta = 0
        self.roda = 2
Enter fullscreen mode Exit fullscreen mode

class VeiculoMotorizado(Veiculo):

    def __init__(self):
        Veiculo.__init__(self)
        self.ligado = False

    def ligar_motor(self):
        self.ligado = True



Enter fullscreen mode Exit fullscreen mode
if __name__ == '__main__':
    bicicleta = Veiculo()
    print('Bicicleta:')
    print('Porta:' ,bicicleta.porta)
    print('Roda:' ,bicicleta.roda)

    triciclo = Veiculo()
    print('Triciclo:')
    triciclo.roda = 3
    print('Porta:' ,triciclo.porta)
    print('Roda:' ,triciclo.roda)

    moto = VeiculoMotorizado()
    print('Moto:')
    print('Porta:' ,moto.porta)
    print('Roda:' ,moto.roda)
    print('Motor:' ,moto.ligado)

    moto.ligar_motor()
    print('Motor:' ,moto.ligado)

    carro = VeiculoMotorizado()
    carro.porta = 4
    carro.roda = 4
    carro.ligar_motor()
    print('Carro:')
    print('Porta:' ,carro.porta)
    print('Roda:' ,carro.roda)
    print('Motor:' ,carro.ligado)
Veículos melhorado

class Veiculo(object):

    def __init__(self, porta=0, roda=2):
        super(Veiculo, self).__init__()
        self.porta = porta
        self.roda = roda
Enter fullscreen mode Exit fullscreen mode
class VeiculoMotorizado(Veiculo):

    def __init__(self, porta=0, roda=2, ligado=False):
        super(VeiculoMotorizado, self).__init__(porta, roda)
        Veiculo.__init__(self)
        self.ligado = ligado

    def ligar_motor(self):
        self.ligado = True
Enter fullscreen mode Exit fullscreen mode
if __name__ == '__main__':
    bicicleta = Veiculo()
    print('Bicicleta:')
    print('Porta:', bicicleta.porta)
    print('Roda:', bicicleta.roda)

    triciclo = Veiculo()
    print('Triciclo:')
    triciclo.roda = 3
    print('Porta:', triciclo.porta)
    print('Roda:', triciclo.roda)

    moto = VeiculoMotorizado()
    print('Moto:')
    print('Porta:', moto.porta)
    print('Roda:', moto.roda)
    print('Motor:', moto.ligado)

    moto.ligar_motor()
    print('Motor:', moto.ligado)

    carro = VeiculoMotorizado()
    carro.porta = 4
    carro.roda = 4
    carro.ligar_motor()
    print('Carro:')
    print('Porta:', carro.porta)
    print('Roda:', carro.roda)
    print('Motor:', carro.ligado)
Salas

Enter fullscreen mode Exit fullscreen mode

rooms.py

class Person(object):

    def __init__(self, username):
        self.username = username
Enter fullscreen mode Exit fullscreen mode
class Room(object):

    def __init__(self, room):
        self.room = room
        self.persons = []

    def add_person(self, person):
        '''
        Adiciona pessoas na lista 'persons'.
        Se for uma lista ou tupla usa 'extend'.
        Caso contrário, usa 'append'.
        '''
        if isinstance(person, (list, tuple)):
            self.persons.extend(person)
        else:
            self.persons.append(person)
Enter fullscreen mode Exit fullscreen mode
  def count_persons(self):
        # Conta os items da lista 'persons'.
        return len(self.persons)
Enter fullscreen mode Exit fullscreen mode
if __name__ == '__main__':
    sala1 = Room('Think Lab')
    print(sala1.room)
    print(sala1.persons)
    sala1.add_person('Regis')
    sala1.add_person('Fernando')
    print(sala1.room, sala1.count_persons(), sala1.persons)

    sala2 = Room('Watson')
    sala2.add_person('Marcia')
    print(sala2.room, sala2.count_persons(), sala2.persons)

    sala3 = Room('Auditório')
    persons = ['Ana', 'Beatriz', 'Carlos', 'Daniel', 'Eduardo', 'Frederico']
    sala3.add_person(persons)
    print(sala3.room, sala3.count_persons(), sala3.persons)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)