O Python se tornou uma das linguagens de programação que mais cresce nos últimos anos.
Além de ser amplamente utilizado, também é uma linguagem incrível de se lidar, se você quiser entrar no mundo da programação.
Este Guia Python para Iniciantes permite que você aprenda o núcleo do idioma em questão de horas, em vez de semanas.
Informações rápidas: Você pode baixar uma versão em PDF deste Guia Python para Iniciantes.
Pronto para mergulhar?
- Introdução ao Python
- Instalando o Python 3
- Código em execução
- Sintaxe
- Comentários
- Variáveis
- Tipos
- Typecasting
- Entrada do Usuário
- Operadores
- Condicionais
- Listas
- Tuplas
- Conjuntos
- Dicionários
- enquanto Loops
- para loops
- Funções
- Escopo
- Compreensões da lista
- Funções Lambda
- Módulos
- E se nome == ‘a Principal“
- arquivos
- Classes e Objetos
- Herança
- Exceções
- Conclusão
Python foi criado em 1990 por Guido Van Rossum na Holanda.
Um dos objetivos da linguagem era ser acessível a não programadores.
O Python também foi projetado para ser uma segunda linguagem para os programadores aprenderem devido à sua baixa curva de aprendizado e facilidade de uso.
O Python é executado no Mac, Linux, Windows e muitas outras plataformas.
Python é:
Interpretado: ele pode ser executado em tempo de execução e as alterações em um programa são instantaneamente perceptíveis. Para ser muito técnico, o Python possui um compilador. A diferença em comparação com Java ou C ++ é a transparência e a automação. Com o Python, não precisamos nos preocupar com a etapa de compilação, como é feita em tempo real. A desvantagem é que as línguas interpretadas são geralmente mais lentas que as compiladas.
Dinamicamente Semanticamente: você não precisa especificar tipos para variáveis e não há nada que o faça fazê-lo.
Orientado a objetos: tudo em Python é um objeto. Mas você pode optar por escrever o código de maneira orientada a objetos, processual ou mesmo funcional.
Alto nível: você não precisa lidar com detalhes de máquinas de baixo nível.
O Python vem crescendo muito recentemente, em parte por causa de seus muitos usos nas seguintes áreas:
Script de sistema: é uma ótima ferramenta para automatizar tarefas repetitivas diárias.
Análise de dados: é uma ótima linguagem para experimentar e possui inúmeras bibliotecas e ferramentas para lidar com dados, criar modelos, visualizar resultados e até implantar soluções. Isso é usado em áreas como finanças, comércio eletrônico e pesquisa.
Desenvolvimento Web: estruturas como Django e Flask permitem o desenvolvimento de aplicativos web, APIs e sites.
Aprendizado de máquina: Tensorflow e Pytorch são algumas das bibliotecas que permitem aos cientistas e à indústria desenvolver e implantar soluções de Inteligência Artificial em reconhecimento de imagem, saúde, carros autônomos e muitos outros campos.
Você pode organizar facilmente seu código em módulos e reutilizá-los ou compartilhá-los com outras pessoas.
Por fim, devemos ter em mente que o Python teve alterações significativas entre as versões 2 e 3. E desde que o suporte ao Python 2 terminou em 2020, este artigo é baseado exclusivamente no Python 3.
Então vamos começar.
Se você usa um Mac ou Linux, já possui o Python instalado. Mas o Windows não vem com o Python instalado por padrão.
Você também pode ter o Python 2 e usaremos o Python 3. Portanto, verifique se o Python 3 é o primeiro.
Digite o seguinte no seu terminal.
python3 -V
Observe as letras maiúsculas V
.
Se o resultado for algo semelhante ao ‘Python 3.x.y’, por exemplo, Python 3.8.1
, então você está pronto para ir.
Caso contrário, siga as próximas instruções de acordo com o seu sistema operacional.
Instalando o Python 3 no Windows
Vamos para https://www.python.org/downloads/.
Baixe a versão mais recente.
Após o download, clique duas vezes no instalador.
Na primeira tela, marque a caixa indicando “Adicionar Python 3.x ao PATH” e clique em “Instalar agora”.
Aguarde o processo de instalação terminar até a próxima tela com a mensagem “A instalação foi bem-sucedida”.
Clique em “Fechar”.
Instalando o Python 3 no Mac
Instalar XCode da App Store.
Instale as ferramentas de linha de comando executando o seguinte em seu terminal.
xcode-select --install
Eu recomendo usar o Homebrew. Vamos para https://brew.sh/ e siga as instruções na primeira página para instalá-lo.
Depois de instalar o Homebrew, execute o seguinte brew
comandos para instalar o Python 3.
brew updatebrew install python3
O Homebrew já adiciona o Python 3 ao PATH, para que você não precise fazer mais nada.
Instalando o Python 3 no Linux
Para instalar usando apt
, disponível no Ubuntu e Debian, digite o seguinte:
sudo apt install python3
Para instalar usando yum
, disponível no RedHat e CentOS, digite o seguinte:
sudo yum install python3
Você pode executar o código Python diretamente no terminal como comandos ou salvar o código em um arquivo com o comando .py
extensão e execute o arquivo Python.
terminal
A execução de comandos diretamente no terminal é recomendada quando você deseja executar algo simples.
Abra a linha de comando e digite python3
renan@mypc:~$ python3
Você deve ver algo assim no seu terminal, indicando a versão (no meu caso, Python 3.6.9), o sistema operacional (estou usando Linux) e alguns comandos básicos para ajudá-lo.
o >>>
nos diz que estamos no console do Python.
Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>>
Vamos testá-lo executando nosso primeiro programa para executar matemática básica e adicionar dois números.
>>> 2 + 2
A saída é:
4
Para sair do console Python, basta digitar exit()
.
>>> exit()
Corrida .py
arquivos
Se você tem um programa complexo, com muitas linhas de código, o console Python não é a melhor opção.
A alternativa é simplesmente abrir um editor de texto, digitar o código e salvar o arquivo com um .py
extensão.
Vamos fazer isso, crie um arquivo chamado second_program.py
com o seguinte conteúdo.
print('Second Program')
o print()
A função imprime uma mensagem na tela.
A mensagem entra entre parênteses com aspas simples ou duplas, ambas funcionam da mesma maneira.
Para executar o programa, no seu terminal, faça o seguinte:
renan@mypc:~$ python3 second_program.py
A saída é:
Second Program
Python é conhecido por sua sintaxe limpa.
O idioma evita o uso de caracteres desnecessários para indicar alguma especificidade.
Ponto e vírgula
Python não usa ponto e vírgula para terminar as linhas. Uma nova linha é suficiente para informar ao intérprete que um novo comando está começando.
o print()
O método exibirá algo.
Neste exemplo, temos dois comandos que exibirão as mensagens entre aspas simples.
print('First command')print('Second command')
Resultado:
First commandSecond command
Mas o seguinte é errado devido ao ponto e vírgula no final:
print('First command');print('Second command');
Indentação
Muitos idiomas usam colchetes para definir o escopo.
O intérprete do Python usa apenas recuo para definir quando um escopo termina e outro inicia.
Isso significa que você deve estar ciente dos espaços em branco no início de cada linha – eles têm significado e podem quebrar seu código se forem extraviados.
Esta definição de uma função funciona:
def my_function(): print('First command')
este não funciona porque o recuo da segunda linha está ausente e gerará um erro:
def my_function():print('First command')
Sensibilidade e variáveis de caso
Python faz distinção entre maiúsculas e minúsculas. Então as variáveis name
e Name
não são a mesma coisa e armazenam valores diferentes.
name = 'Renan'Name = 'Moura'
Como você pode ver, as variáveis são criadas facilmente atribuindo valores a elas usando o comando =
símbolo.
Isso significa name
lojas ‘Renan’ e Name
lojas ‘Moura’.
Por fim, para comentar algo em seu código, use a marca de hash #
.
A parte comentada não influencia o fluxo do programa.
# this function prints somethingdef my_function(): print('First command')
Esta foi apenas uma visão geral. Os detalhes de cada uma delas ficarão mais claros nos próximos capítulos, com exemplos e explicações mais amplas.
O objetivo dos comentários é explicar o que está acontecendo no código.
Os comentários são escritos junto com o seu código, mas não influenciam o fluxo do programa.
Quando você trabalha sozinho, talvez os comentários não pareçam algo que você deva escrever. Afinal, no momento, você sabe os porquês de cada linha de código.
Mas e se novas pessoas entrarem no seu projeto depois de um ano e o projeto tiver 3 módulos, cada um com 10.000 linhas de código?
Pense em pessoas que não sabem nada sobre seu aplicativo e que, de repente, precisam mantê-lo, corrigi-lo ou adicionar novos recursos.
Lembre-se, não existe uma solução única para um determinado problema. Sua maneira de resolver as coisas é sua e somente sua. Se você pedir a 10 pessoas para resolver o mesmo problema, elas apresentarão 10 soluções diferentes.
Se você deseja que outras pessoas entendam completamente seu raciocínio, um bom design de código é obrigatório, mas os comentários são parte integrante de qualquer base de código.
A sintaxe dos comentários no Python é bastante fácil: basta usar a marca de hash #
símbolo na frente do texto que você deseja que seja um comentário.
#This is a comment and it won't influence my program flow
Você pode usar um comentário para explicar o que algum código faz.
#calculates the sum of any given two numbersa + b
Talvez você queira comentar algo muito complexo ou descrever como algum processo funciona no seu código.
Nesses casos, você pode usar comentários de várias linhas.
Para fazer isso, basta usar uma única marca de hash #
para cada linha.
#Everything after the hash mark # is a comment#This is a comment and it won't influence my program flow#Calculates the cost of the project given variables a and b#a is the time in months it will take until the project is finished#b is how much money it will cost per montha + b * 10
Em qualquer programa, você precisa armazenar e manipular dados para criar um fluxo ou alguma lógica específica.
É para isso que servem as variáveis.
Você pode ter uma variável para armazenar um nome, outra para armazenar a idade de uma pessoa ou até mesmo usar um tipo mais complexo para armazenar tudo isso de uma vez como um dicionário.
Criando, também conhecido como Declaração
Declarar uma variável é uma operação básica e direta em Python
Basta escolher um nome e atribuir um valor a ele usando o =
símbolo.
name='Bob'age=32
Você pode usar o print()
para mostrar o valor de uma variável.
print(name)print(age)
Bob32
Observe que no Python não há uma palavra especial para declarar uma variável.
No momento em que você atribui um valor, a variável é criada na memória.
O Python também possui digitação dinâmica, o que significa que você não precisa informar se sua variável é um texto ou um número, por exemplo.
O intérprete deduz a digitação com base no valor atribuído.
Se você precisar, também poderá declarar novamente uma variável apenas alterando seu valor.
#declaring name as a stringname='Bob'#re-declaring name as an intname = 32
Lembre-se, porém, que isso não é recomendado, pois as variáveis devem ter significado e contexto.
Se eu tiver uma variável chamada name
Não espero que ele tenha um número armazenado.
Convenções de nomenclatura
Vamos continuar da última seção quando falei sobre significado e contexto.
Não use nomes de variáveis aleatórios como x
ou y
.
Digamos que você queira armazenar a hora de uma festa, basta chamá-la party_time
.
Oh, você notou o sublinhado _
?
Por convenção, se você quiser usar um nome de variável composto por duas ou mais palavras, separe-as por sublinhados. Isso é chamado de Snake Case.
Outra opção seria usar o CamelCase como em partyTime
. Isso é muito comum em outros idiomas, mas não na convenção em Python, como afirmado anteriormente.
As variáveis diferenciam maiúsculas de minúsculas, portanto party_time
e Party_time
não são os mesmos. Além disso, lembre-se de que a convenção nos diz para sempre usar letras minúsculas.
Lembre-se, use nomes que você possa lembrar facilmente dentro do seu programa. A má nomeação pode custar muito tempo e causar bugs irritantes.
Em resumo, nomes de variáveis:
- São sensíveis a maiúsculas e minúsculas:
time
eTIME
não são os mesmos - Tem que começar com um sublinhado
_
ou uma letra (NÃO comece com um número) - É permitido ter apenas números, letras e sublinhados. Nenhum caractere especial como: #, $, &, @, etc.
Isso, por exemplo, é não permitido: party#time
, 10partytime
.
Para armazenar dados em Python, você precisa usar uma variável. E toda variável tem seu tipo, dependendo do valor dos dados armazenados.
O Python possui digitação dinâmica, o que significa que você não precisa declarar explicitamente o tipo de sua variável – mas, se quiser, pode.
Listas, Tuplas, Conjuntos e Dicionários são todos tipos de dados e, posteriormente, possuem seções dedicadas com mais detalhes, mas veremos brevemente aqui.
Dessa forma, posso mostrar os aspectos e operações mais importantes de cada um em sua própria seção, mantendo a seção mais concisa e focada em fornecer uma visão ampla dos principais tipos de dados no Python.
Determinando o tipo
Primeiro de tudo, vamos aprender como determinar o tipo de dados.
Basta usar o type()
e passe a variável de sua escolha como argumento, como no exemplo abaixo.
print(type(my_variable))
boleano
O tipo booleano é um dos tipos mais básicos de programação.
Uma variável do tipo booleano pode representar apenas Verdadeiro ou Falso.
my_bool = Trueprint(type(my_bool))my_bool = bool(1024)print(type(my_bool))
Números
Existem três tipos de tipos numéricos: int, float e complexo.
Inteiro
my_int = 32print(type(my_int))my_int = int(32)print(type(my_int))
Flutuador
my_float = 32.85print(type(my_float))my_float = float(32.85)print(type(my_float))
Complexo
my_complex_number = 32+4jprint(type(my_complex_number))my_complex_number = complex(32+4j)print(type(my_complex_number))
Corda
O tipo de texto é um dos tipos mais comuns existentes no mercado e é frequentemente chamado corda ou, em Python, apenas str
.
my_city = "New York"print(type(my_city))#Single quotes have exactly#the same use as double quotesmy_city = 'New York'print(type(my_city))#Setting the variable type explicitlymy_city = str("New York")print(type(my_city))
Você pode usar o +
operador para concatenar seqüências de caracteres.
Concatenação é quando você tem duas ou mais seqüências e deseja uni-las em uma.
word1 = 'New 'word2 = 'York'print(word1 + word2)
New York
O tipo de string possui muitos métodos internos que nos permitem manipulá-los. Vou demonstrar como alguns desses métodos funcionam.
o len()
A função retorna o comprimento de uma sequência.
print(len('New York'))
8
o replace()
O método substitui uma parte da string por outra. Como exemplo, vamos substituir ‘Novo’ por ‘Velho’.
print('New York'.replace('New', 'Old'))
Old York
o upper()
O método retornará todos os caracteres em maiúsculas.
print('New York'.upper())
NEW YORK
o lower()
O método faz o oposto e retorna todos os caracteres em minúsculas.
print('New York'.lower())
new york
Listas
Uma lista tem seus itens solicitados e você pode adicionar o mesmo item quantas vezes quiser. Um detalhe importante é que as listas são mutáveis.
Mutabilidade significa que você pode alterar uma lista após a sua criação adicionando itens, removendo-os ou mesmo alterando seus valores. Essas operações serão demonstradas posteriormente na seção dedicada às listas.
my_list = ["bmw", "ferrari", "maclaren"]print(type(my_list))my_list = list(("bmw", "ferrari", "maclaren"))print(type(my_list))
Tuplas
Uma tupla é como uma lista: ordenada e permite a repetição de itens.
Há apenas uma diferença: uma tupla é imutável.
Imutabilidade significa que você não pode alterar uma tupla após sua criação. Se você tentar adicionar um item ou atualizar um, por exemplo, o intérprete Python mostrará um erro. Mostrarei que esses erros ocorrem mais adiante na seção dedicada às Tuplas.
my_tuple = ("bmw", "ferrari", "maclaren")print(type(my_tuple))my_tuple = tuple(("bmw", "ferrari", "maclaren"))print(type(my_tuple))
Conjuntos
Os conjuntos não garantem a ordem dos itens e não são indexados.
Um ponto chave ao usar conjuntos: eles não permitem a repetição de um item.
my_set = {"bmw", "ferrari", "maclaren"}print(type(my_set))my_set = set(("bmw", "ferrari", "maclaren"))print(type(my_set))
Dicionários
Um dicionário não garante a ordem dos elementos e é mutável.
Uma característica importante nos dicionários é que você pode definir suas próprias teclas de acesso para cada elemento.
my_dict = {"country" : "France", "worldcups" : 2}print(type(my_dict))my_dict = dict(country="France", worldcups=2)print(type(my_dict))
A conversão de tipo permite converter entre tipos diferentes.
Dessa forma, você pode ter um int
se transformou em um str
ou um float
se transformou em um int
, por exemplo.
Conversão explícita
Para converter uma variável em uma string, use o str()
função.
# this is just a regular explicit intializationmy_str = str('32') print(my_str)# int to strmy_str = str(32) print(my_str)# float to strmy_str = str(32.0)print(my_str)
323232.0
Para converter uma variável em um número inteiro, basta usar o int()
função.
# this is just a regular explicit intializationmy_int = int(32) print(my_int)# float to int: rounds down to 3my_int = int(3.2) print(my_int)# str to intmy_int = int('32') print(my_int)
32332
Para converter uma variável em um float, use o float()
função.
# this is an explicit intializationmy_float = float(3.2) print(my_float)# int to floatmy_float = float(32) print(my_float)# str to floatmy_float = float('32') print(my_float)
3.232.032.0
O que eu fiz acima é chamado de explícito conversão de tipo.
Em alguns casos, você não precisa fazer a conversão explicitamente, pois o Python pode fazer isso por si só.
Conversão implícita
O exemplo abaixo mostra a conversão implícita ao adicionar um int
e um float
.
Notar que my_sum
é float
. Python usa float
para evitar a perda de dados desde o int
O tipo não pode representar os dígitos decimais.
my_int = 32my_float = 3.2my_sum = my_int + my_floatprint(my_sum)print(type(my_sum))
35.2
Por outro lado, neste exemplo, quando você adiciona um int
e um str
, Python não poderá fazer a conversão implícita, e a conversão explícita de tipo é necessária.
my_int = 32my_str = '32'# explicit conversion worksmy_sum = my_int + int(my_str)print(my_sum)#implicit conversion throws an errormy_sum = my_int + my_str
64Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
O mesmo erro é gerado ao tentar adicionar float
e str
tipos sem fazer uma conversão explícita.
my_float = 3.2my_str = '32'# explicit conversion worksmy_sum = my_float + float(my_str)print(my_sum)#implicit conversion throws an errormy_sum = my_float + my_str
35.2Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'float' and 'str'
Se você precisar interagir com um usuário ao executar seu programa na linha de comando (por exemplo, para solicitar uma informação), use o input()
função.
country = input("What is your country? ") #user enters 'Brazil'print(country)
Brazil
O valor capturado é sempre string
. Lembre-se de que pode ser necessário convertê-lo usando a conversão de texto.
age = input("How old are you? ") #user enters '29'print(age)print(type(age))age = int(age)print(type(age))
A saída para cada print()
é:
29
Observe que a idade de 29 anos é capturada como string
e depois convertido explicitamente em int
.
Em uma linguagem de programação, os operadores são símbolos especiais que você pode aplicar às suas variáveis e valores para executar operações como aritmética / matemática e comparação.
O Python possui muitos operadores que você pode aplicar às suas variáveis e eu demonstrarei os mais usados.
Operadores aritméticos
Operadores aritméticos são o tipo mais comum de operadores e também os mais reconhecíveis.
Eles permitem que você execute operações matemáticas simples.
Eles são:
+
: Adição-
: Subtração*
: Multiplicação/
: Divisão**
: Exponenciação//
: Floor Division, arredonda o resultado de uma divisão%
: Módulo, fornece o restante de uma divisão
Vamos ver um programa que mostra como cada um deles é usado.
print('Addition:', 5 + 2)print('Subtraction:', 5 - 2)print('Multiplication:', 5 * 2)print('Division:', 5 / 2)print('Floor Division:', 5 // 2)print('Exponentiation:', 5 ** 2)print('Modulus:', 5 % 2)
Addition: 7Subtraction: 3Multiplication: 10Division: 2.5Floor Division: 2Exponentiation: 25Modulus: 1
Concatenação
Concatenação é quando você tem duas ou mais seqüências e deseja uni-las em uma.
Isso é útil quando você tem informações em várias variáveis e deseja combiná-las.
Por exemplo, neste próximo exemplo, eu combino duas variáveis que contêm meu primeiro nome e meu sobrenome, respectivamente, para ter meu nome completo.
o +
O operador também é usado para concatenar.
first_name = 'Renan 'last_name = 'Moura'print(first_name + last_name)
Renan Moura
Como a concatenação é aplicada a cadeias de caracteres, para concatenar cadeias de caracteres com outros tipos, é necessário executar uma conversão de tipo explícita usando str()
.
Eu tenho que escrever o int
valor 30 para string com str()
concatená-lo com o restante da string.
age = 'I have ' + str(30) + ' years old'print(age)
I have 30 years old
Operadores de comparação
Use operadores de comparação para comparar dois valores.
Esses operadores retornam True
ou False
.
Eles são:
==
: Igual!=
: Não igual>
: Maior que<
: Menor que>=
: Melhor que ou igual a<=
: Menos que ou igual a
Vamos ver um programa que mostra como cada um deles é usado.
print('Equal:', 5 == 2)print('Not equal:', 5 != 2)print('Greater than:', 5 > 2)print('Less than:', 5 < 2)
print('Greater than or equal to:', 5 >= 2)print('Less than or equal to:', 5 <= 2)
Equal: FalseNot equal: TrueGreater than: TrueLess than: FalseGreater than or equal to: TrueLess than or equal to: False
Operadores de atribuição
Como o nome indica, esses operadores são usados para atribuir valores a variáveis.
x = 7
no primeiro exemplo é uma atribuição direta que armazena o número 7
na variável x
.
A operação de atribuição pega o valor à direita e o atribui à variável à esquerda.
Os outros operadores são simples atalhos para os operadores aritméticos.
No segundo exemplo x
começa com 7
e x += 2
é apenas outra maneira de escrever x = x + 2
. Isso significa que o valor anterior de x
é adicionado por 2
e reatribuído para x
agora é igual a 9
.
x = 7print(x)
7
+=
: adição e atribuição
x = 7x += 2print(x)
9
-=
: subtração e atribuição
x = 7x -= 2print(x)
5
*=
: multiplicação e atribuição
x = 7x *= 2print(x)
14
/=
: divisão e atribuição
x = 7x /= 2print(x)
3.5
%=
: módulo e atribuição
x = 7x %= 2print(x)
1
//=
: divisão e atribuição de piso
x = 7x //= 2print(x)
3
**=
: exponenciação e atribuição
x = 7x **= 2print(x)
49
Operadores lógicos
Operadores lógicos são usados para combinar instruções aplicando álgebra booleana.
Eles são:
and
:True
somente quando ambas as afirmações são verdadeirasor
:False
somente quando x e y são falsosnot
: Onot
O operador simplesmente inverte a entrada,True
torna-seFalse
e vice versa.
Vamos ver um programa que mostra como cada um é usado.
x = 5y = 2print(x == 5 and y > 3) print(x == 5 or y > 3) print(not (x == 5))
FalseTrueFalse
Operadores de associação
Esses operadores fornecem uma maneira fácil de verificar se um determinado objeto está presente em uma sequência: string
, list
, tuple
, set
e dictionary
.
Eles são:
in
: retornaTrue
se o objeto estiver presentenot in
: retornaTrue
se o objeto não estiver presente
Vamos ver um programa que mostra como cada um é usado.
number_list = [1, 2, 4, 5, 6]print( 1 in number_list)print( 5 not in number_list)print( 3 not in number_list)
TrueFalseTrue
Os condicionais são uma das pedras angulares de qualquer linguagem de programação.
Eles permitem controlar o fluxo do programa de acordo com condições específicas que você pode verificar.
o if
declaração
A maneira como você implementa uma condicional é através do if
declaração.
A forma geral de um if
declaração é:
if expression: statement
o expression
contém alguma lógica que retorna um booleano e o statement
é executado apenas se o retorno for True
.
Um exemplo simples:
bob_age = 32sarah_age = 29if bob_age > sarah_age: print('Bob is older than Sarah')
Bob is older than Sarah
Temos duas variáveis indicando as idades de Bob e Sarah. A condição em inglês simples diz "se a idade de Bob for maior que a de Sarah, imprima a frase 'Bob é mais velho que Sarah'".
Como a condição retorna True
, a frase será impressa no console.
o if else
e elif
afirmações
No nosso último exemplo, o programa só faz algo se a condição retornar True
.
Mas também queremos que faça algo se retornar False
ou até mesmo verificar uma segunda ou terceira condição se a primeira não foi atendida.
Neste exemplo, trocamos a idade de Bob e Sarah. A primeira condição retornará False
já que Sarah está mais velha agora, e o programa imprimirá a frase após o else
em vez de.
bob_age = 29sarah_age = 32if bob_age > sarah_age: print('Bob is older than Sarah')else: print('Bob is younger than Sarah')
Bob is younger than Sarah
Agora, considere o exemplo abaixo com o elif
.
bob_age = 32sarah_age = 32if bob_age > sarah_age: print('Bob is older than Sarah')elif bob_age == sarah_age: print('Bob and Sarah have the same age')else: print('Bob is younger than Sarah')
Bob and Sarah have the same age
O objetivo do elif
é fornecer uma nova condição a ser verificada antes da else
É executado.
Mais uma vez mudamos suas idades e agora ambos têm 32 anos.
Como tal, a condição no elif
é cumprida. Como ambos têm a mesma idade, o programa imprimirá "Bob e Sarah têm a mesma idade".
Observe que você pode ter elif
s como quiser, basta colocá-los em sequência.
bob_age = 32sarah_age = 32if bob_age > sarah_age: print('Bob is older than Sarah')elif bob_age < sarah_age: print('Bob is younger than Sarah')elif bob_age == sarah_age: print('Bob and Sarah have the same age')else: print('This one is never executed')
Bob and Sarah have the same age
Neste exemplo, o else
nunca é executado porque todas as possibilidades estão cobertas nas condições anteriores e, portanto, podem ser removidas.
Condicionais aninhados
Pode ser necessário verificar mais de uma condição para que algo aconteça.
Nesse caso, você pode aninhar seu if
afirmações.
Por exemplo, a segunda frase "Bob é o mais antigo" é impressa apenas se ambos if
s passa.
bob_age = 32sarah_age = 28mary_age = 25if bob_age > sarah_age: print('Bob is older than Sarah') if bob_age > mary_age: print('Bob is the oldest')
Bob is the oldest
Ou, dependendo da lógica, simplifique-a com Álgebra Booleana.
Dessa forma, seu código é menor, mais legível e mais fácil de manter.
bob_age = 32sarah_age = 28mary_age = 25if bob_age > sarah_age and bob_age > mary_age: print('Bob is the oldest')
Bob is the oldest
Ou até:
bob_age = 32sarah_age = 28mary_age = 25if bob_age > sarah_age > mary_age: print('Bob is the oldest')
Bob is the oldest
Operadores ternários
O operador ternário é uma linha if
declaração.
É muito útil para condições simples.
Isto é o que parece:
if else
Considere o seguinte código Python:
a = 25b = 50x = 0y = 1result = x if a > b else yprint(result)
1
Aqui usamos quatro variáveis, a
e b
são para a condição, enquanto x
e y
representa as expressões.
a
e b
são os valores que estamos verificando entre si para avaliar alguma condição. Nesse caso, estamos verificando se a
é melhor que b
.
Se a expressão for verdadeira, ou seja, a
é melhor que b
, então o valor de x
será atribuído a result
que será igual a 0.
No entanto, se a
é menos do que b
, então temos o valor de y
atribuído a result
e result
manterá o valor 1
.
Desde a a
é menos do que b
, 25 <50, result
terá 1
como valor final de y
.
A maneira mais fácil de lembrar como a condição é avaliada é lê-la em inglês simples.
Nosso exemplo seria: result
será x
E se a
é melhor que b
de outra forma y
.
Como prometido no Tipos , esta seção e as próximas três sobre Tuplas, Conjuntos e Dicionários terão explicações mais detalhadas de cada um deles, uma vez que são estruturas muito importantes e amplamente usadas no Python para organizar e lidar com dados.
Uma lista tem seus itens solicitados e você pode adicionar o mesmo item quantas vezes quiser.
Um detalhe importante é que as listas são mutáveis.
Mutabilidade significa que você pode alterar uma lista após a sua criação adicionando itens, removendo-os ou mesmo alterando seus valores.
Inicialização
Lista vazia
people = []
Lista com valores iniciais
people = ['Bob', 'Mary']
Adicionando em uma lista
Para adicionar um item no final de uma lista, use append()
.
people = ['Bob', 'Mary']people.append('Sarah')print(people)
['Bob', 'Mary', 'Sarah']
Para especificar a posição do novo item, use o insert()
método.
people = ['Bob', 'Mary']people.insert(0, 'Sarah')print(people)
['Sarah', 'Bob', 'Mary']
Atualizando em uma lista
Especifique a posição do item para atualizar e defina o novo valor
people = ['Bob', 'Mary']people[1] = 'Sarah'print(people)
['Bob', 'Sarah']
Exclusão em uma lista
Use o remove()
para excluir o item fornecido como argumento.
people = ['Bob', 'Mary']people.remove('Bob')print(people)
['Mary']
Para excluir todos, use o clear()
método:
people = ['Bob', 'Mary']people.clear()
Recuperando em uma lista
Use o índice para fazer referência ao item.
Lembre-se de que o índice começa em 0.
Portanto, para acessar o segundo item, use o índice 1.
people = ['Bob', 'Mary']print(people[1])
Mary
Verifique se um determinado item já existe em uma Lista
people = ['Bob', 'Mary']if 'Bob' in people: print('Bob exists!')else: print('There is no Bob!')
Uma tupla é semelhante a uma lista: é ordenada e permite a repetição de itens.
Há apenas uma diferença: uma tupla é imutável.
Imutabilidade, se você se lembra, significa que não pode alterar uma tupla após a sua criação. Se você tentar adicionar um item ou atualizar um, por exemplo, o interpretador Python mostrará um erro.
Inicialização
Tupla vazia
people = ()
Tupla com valores iniciais
people = ('Bob', 'Mary')
Adicionando em uma tupla
Tuplas são imutáveis. Isso significa que, se você tentar adicionar um item, verá um erro.
people = ('Bob', 'Mary')people[2] = 'Sarah'
Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment
Atualizando em uma tupla
A atualização de um item também retornará um erro.
Mas há um truque: você pode converter em uma lista, alterar o item e depois convertê-lo novamente em uma tupla.
people = ('Bob', 'Mary')people_list = list(people)people_list[1] = 'Sarah'people = tuple(people_list)print(people)
('Bob', 'Sarah')
Exclusão em uma tupla
Pelo mesmo motivo, você não pode adicionar um item, também não pode excluir um item, pois eles são imutáveis.
Recuperando em uma tupla
Use o índice para fazer referência ao item.
people = ('Bob', 'Mary')print(people[1])
Mary
Verifique se um determinado item já existe em uma Tupla
people = ('Bob', 'Mary')if 'Bob' in people: print('Bob exists!')else: print('There is no Bob!')
Os conjuntos não garantem a ordem dos itens e não são indexados.
Um ponto chave ao usar conjuntos: eles não permitem a repetição de um item.
Inicialização
Conjunto vazio
people = set()
Definido com valores iniciais
people = {'Bob', 'Mary'}
Adicionando em um conjunto
Use o add()
método para adicionar um item.
people.add('Sarah')
Use o update()
método para adicionar vários itens de uma só vez.
people.update(['Carol', 'Susan'])
Lembre-se de que os conjuntos não permitem repetição; portanto, se você adicionar 'Mary' novamente, nada muda.
people = {'Bob', 'Mary'}people.add('Mary')print(people)
{'Bob', 'Mary'}
Atualizando em um conjunto
Os itens de um conjunto não são mutáveis. Você precisa adicionar ou excluir um item.
Exclusão em um conjunto
Para remover Bob do dicionário:
people = {'Bob', 'Mary'}people.remove('Bob')print(people)
{'Mary'}
Para excluir todos:
people.clear()
Verifique se um determinado item já existe em um conjunto
people = {'Bob', 'Mary'}if 'Bob' in people: print('Bob exists!')else: print('There is no Bob!')
O dicionário não garante a ordem dos elementos e é mutável.
Uma característica importante dos dicionários é que você pode definir suas chaves de acesso personalizadas para cada elemento.
Inicialização de um dicionário
Dicionário vazio
people = {}
Dicionário com valores iniciais
people = {'Bob':30, 'Mary':25}
Adicionando em um dicionário
Se a chave ainda não existir, ela será anexada ao dicionário.
people['Sarah']=32
Atualizando um dicionário
Se a chave já existir, o valor será atualizado.
#Bob's age is 28 nowpeople['Bob']=28
Observe que o código é praticamente o mesmo.
Excluindo em um dicionário
Para remover Bob do dicionário:
people.pop('Bob')
Para excluir todos:
people.clear()
Recuperando em um dicionário
bob_age = people['Bob']print(bob_age)
30
Verifique se uma chave já existe em um dicionário
if 'Bob' in people: print('Bob exists!')else: print('There is no Bob!')
Os loops são usados quando você precisa repetir um bloco de código um certo número de vezes ou aplicar a mesma lógica sobre cada item de uma coleção.
Existem dois tipos de loops: for
e while
.
Você aprenderá sobre for
loops na próxima seção.
Sintaxe básica
A sintaxe básica de um while
loop é como abaixo.
while condition: statement
O loop continuará até a condição é True
.
O quadrado de um número é
O exemplo abaixo pega cada valor de number
e calcula seu valor ao quadrado.
number = 1while number <= 5: print(number, 'squared is', number**2) number = number + 1
1 squared is 12 squared is 43 squared is 94 squared is 165 squared is 25
Você pode usar qualquer nome de variável, mas eu escolhi number
porque faz sentido no contexto. Uma escolha genérica comum seria simplesmente i
.
O loop continuará até number
(inicializado com 1) é menor ou igual a 5.
Observe que após o print()
comando, a variável number
é incrementado em 1 para obter o próximo valor.
Se você não fizer o incremento, terá um loop infinito, pois number
nunca atingirá um valor maior que 5. Esse é um detalhe muito importante!
else
quadra
Quando a condição retornar False
, a else
bloco será chamado.
number = 1while number <= 5: print(number, 'squared is', number**2) number = number + 1else: print('No numbers left!')
1 squared is 12 squared is 43 squared is 94 squared is 165 squared is 25No numbers left!
Observe a frase 'Nenhum número restante!' é impresso após o término do loop, ou seja, após a condição number <= 5
avalia como False
.
Como sair de um while
loop em Python
Basta usar o break
palavra-chave e o loop interromperá sua execução.
number = 1while number <= 5: print(number, 'squared is', number**2) number = number + 1 if number == 4: break
1 squared is 12 squared is 43 squared is 9
O loop é executado normalmente e quando number
atinge 4 a if
declaração é avaliada como True
e a break
comando é chamado. Isso termina o loop antes que o valor quadrado dos números 4 e 5 seja calculado.
Como pular um item em um while
ciclo
o continue
fará isso por você.
Eu tive que inverter a ordem do if
declaração e o print()
para mostrar como funciona corretamente.
number = 0while number < 5: number = number + 1 if number == 4: continue print(number, 'squared is', number**2)
1 squared is 12 squared is 43 squared is 95 squared is 25
O programa sempre verifica se 4 é o valor atual de number
. Se for, o quadrado de 4 não será calculado e o continue
pulará para a próxima iteração quando o valor de number
é 5.
for
loops são semelhantes a while
loops no sentido em que são usados para repetir blocos de código.
A diferença mais importante é que você pode iterar facilmente sobre tipos sequenciais.
Sintaxe básica
A sintaxe básica de um for
loop é como abaixo.
for item in collection: statement
Passar por cima de uma lista
Para fazer um loop sobre uma lista ou qualquer outra coleção, continue como mostrado no exemplo abaixo.
cars = ['BMW', 'Ferrari', 'McLaren']for car in cars: print(car)
BMWFerrariMcLaren
A lista de cars
contém três itens. o for
loop irá percorrer a lista e armazenar cada item no car
variável e, em seguida, execute uma instrução, neste caso print(car)
, para imprimir cada carro no console.
range()
função
A função range é amplamente usada em loops, porque fornece uma maneira simples de listar números.
Este código percorrerá os números de 0 a 5 e imprimirá cada um deles.
for number in range(5): print(number)
01234
Por outro lado, sem o range()
função, faríamos algo assim.
numbers = [0, 1, 2, 3, 4]for number in numbers: print(number)
01234
Você também pode definir um start
e stop
usando range()
.
Aqui, começamos em 5 e paramos em 10. O número que você definiu para parar não está incluído.
for number in range(5, 10): print(number)
56789
Por fim, também é possível definir um passo.
Aqui começamos em 10 e aumentamos de 2 até 20, já que 20 é o stop
, não está incluído.
for number in range(10, 20, 2): print(number)
1012141618
else
quadra
Quando os itens da lista terminam, o else
bloco será chamado.
cars = ['BMW', 'Ferrari', 'McLaren']for car in cars: print(car)else: print('No cars left!')
BMWFerrariMcLarenNo cars left!
Como sair de um loop for em Python
Basta usar o break
palavra-chave e o loop interromperá sua execução.
cars = ['BMW', 'Ferrari', 'McLaren']for car in cars: print(car) if car == 'Ferrari': break
BMWFerrari
O loop irá percorrer a lista e imprimir cada carro.
Nesse caso, depois que o loop atingir 'Ferrari', o break
é chamado e 'McLaren' não será impresso.
Como pular um item em um loop for
Nesta seção, aprenderemos como continue
pode fazer isso por você.
Eu tive que inverter a ordem do if
declaração e o continue
para mostrar como funciona corretamente.
Observe que eu sempre verifico se 'Ferrari' é o item atual. Se for, 'Ferrari' não será impresso e o continue
pulará para o próximo item 'McLaren'.
cars = ['BMW', 'Ferrari', 'McLaren']for car in cars: if car == 'Ferrari': continue print(car)
BMWMcLaren
Loop em loop: loops aninhados
Às vezes, você tem coleções mais complexas, como uma lista de listas.
Para iterar essas listas, é necessário aninhar for
rotações.
Nesse caso, eu tenho três listas: um dos modelos da BMW, outro nos modelos da Ferrari e, finalmente, uma com os modelos da McLaren.
O primeiro loop percorre a lista de cada marca e o segundo percorre os modelos de cada marca.
car_models = [ ['BMW I8', 'BMW X3', 'BMW X1'], ['Ferrari 812', 'Ferrari F8', 'Ferrari GTC4'], ['McLaren 570S', 'McLaren 570GT', 'McLaren 720S']]for brand in car_models: for model in brand: print(model)
BMW I8BMW X3BMW X1Ferrari 812Ferrari F8Ferrari GTC4McLaren 570SMcLaren 570GTMcLaren 720S
Loop sobre outras estruturas de dados
A mesma lógica que se aplica for
laços sobre um list
pode ser estendido para outras estruturas de dados: tuple
, set
e dictionary
.
Vou demonstrar brevemente como fazer um loop básico sobre cada um deles.
Loop sobre uma tupla
people = ('Bob', 'Mary')for person in people: print(person)
BobMary
Loop sobre um conjunto
people = {'Bob', 'Mary'}for person in people: print(person)
BobMary
Loop sobre um dicionário
Para imprimir as teclas:
people = {'Bob':30, 'Mary':25}for person in people: print(person)
BobMary
Para imprimir os valores:
people = {'Bob':30, 'Mary':25}for person in people: print(people[person])
3025
À medida que o código cresce, a complexidade também aumenta. E as funções ajudam a organizar o código.
As funções são uma maneira útil de criar blocos de código que você pode reutilizar.
Definição e Chamada
No Python, use o def
palavra-chave para definir uma função.
Dê um nome a ele e use parênteses para informar 0 ou mais argumentos.
In the line after the declaration starts, remember to indent the block of code.
Here is an example of a function called print_first_function()
that only prints a phrase 'My first function!'.
To call the function just use its name as defined.
def print_first_function(): print('My first function!')print_first_function()
My first function!
return
a value
Use the return
keyword to return a value from the function.
In this example the function second_function()
returns the string 'My second function!'.
Notice that print()
is a built-in function and our function is called from inside it.
The string returned by second_function()
is passed as an argument to the print()
função.
def second_function(): return 'My second function!'print(second_function())
My second function!
return
multiple values
Functions can also return multiple values at once.
return_numbers()
returns two values simultaneously.
def return_numbers(): return 10, 2print(return_numbers())
(10, 2)
Arguments
You can define parameters between the parentheses.
When calling a function with parameters you have to pass arguments according to the parameters defined.
The past examples had no parameters, so there was no need for arguments. The parentheses remained empty when the functions were called.
One Argument
To specify one parameter, just define it inside the parentheses.
In this example, the function my_number
expects one number as argument defined by the parameter num
.
The value of the argument is then accessible inside the function to be used.
def my_number(num): return 'My number is: ' + str(num)print(my_number(10))
My number is: 10
Two or more Arguments
To define more parameters, just use a comma to separate them.
Here we have a function that adds two numbers called add
. It expects two arguments defined by first_num
e second_num
.
The arguments are added by the +
operator and the result is then returned by the return
.
def add(first_num, second_num): return first_num + second_numprint(add(10,2))
12
This example is very similar to the last one. The only difference is that we have 3 parameters instead of 2.
def add(first_num, second_num, third_num): return first_num + second_num + third_numprint(add(10,2,3))
15
This logic of defining parameters and passing arguments is the same for any number of parameters.
It is important to point out that the arguments have to be passed in the same order that the parameters are defined.
Default value.
You can set a default value for a parameter if no argument is given using the =
operator and a value of choice.
In this function, if no argument is given, the number 30 is assumed as the expected value by default.
def my_number(my_number = 30): return 'My number is: ' + str(my_number)print(my_number(10))print(my_number())
My number is: 10My number is: 30
Keyword or Named Arguments
When calling a function, the order of the arguments have to match the order of the parameters.
The alternative is if you use keyword or named arguments.
Set the arguments to their respective parameters directly using the name of the parameters and the =
operators.
This example flips the arguments, but the function works as expected because I tell it which value goes to which parameter by name.
def my_numbers(first_number, second_number): return 'The numbers are: ' + str(first_number) + ' and ' + str(second_number)print(my_numbers(second_number=30, first_number=10))
The numbers are: 10 and 30
Any number of arguments: *args
If you don't want to specify the number of parameters, just use the *
before the parameter name. Then the function will take as many arguments as necessary.
The parameter name could be anything like *numbers
, but there is a convention in Python to use *args
for this definition of a variable number of arguments.
def my_numbers(*args): for arg in args: print(number)my_numbers(10,2,3)
1023
Any number of Keyword/Named arguments: **kwargs
Similar to *args
, we can use **kwargs
to pass as many keyword arguments as we want, as long as we use **
.
Again, the name could be anything like **numbers
, mas **kwargs
is a convention.
def my_numbers(**kwargs): for key, value in kwargs.items(): print(key) print(value)my_numbers(first_number=30, second_number=10)
first_number30second_number10
Other types as arguments
The past examples used mainly numbers, but you can pass any type as argument and they will be treated as such inside the function.
This example takes strings as arguments.
def my_sport(sport): print('I like ' + sport)my_sport('football')my_sport('swimming')
I like footballI like swimming
This function takes a list as argument.
def my_numbers(numbers): for number in numbers: print(number)my_numbers([30, 10, 64, 92, 105])
30106492105
The place where a variable is created defines its availability to be accessed and manipulated by the rest of the code. This is known as scope.
There are two types of scope: local and global.
Global Scope
A global scope allows you to use the variable anywhere in your program.
If your variable is outside a function, it has global scope by default.
name = 'Bob'def print_name(): print('My name is ' + name)print_name()
My name is Bob
Notice that the function could use the variable name
and print My name is Bob
.
Local Scope
When you declare a variable inside a function, it only exists inside that function and can't be accessed from the outside.
def print_name(): name = "Bob" print('My name is ' + name)print_name()
My name is Bob
The variable name
was declared inside the function, so the output is the same as before.
But this will throw an error:
def print_name(): name = 'Bob' print('My name is ' + name)print(name)
The output of the code above is:
Traceback (most recent call last): File "", line 1, in NameError: name 'name' is not defined
I tried to print the variable name
from outside the function, but the scope of the variable was local and could not be found in a global scope.
Mixing Scopes
If you use the same name for variables inside and outside a function, the function will use the one inside its scope.
So when you call print_name()
, a name='Bob'
is used to print the phrase.
On the other hand, when calling print()
outside the function scope, name="Sarah"
is used because of its global scope.
name = "Sarah"def print_name(): name = 'Bob' print('My name is ' + name)print_name()print(name)
The output of the code above is:
My name is BobSarah
Sometimes we want to perform some very simple operations over the items of a list.
List comprehensions give us a succinct way to work on lists as an alternative to other methods of iteration, such as for
loops.
Basic syntax
To use a list comprehension to replace a regular for loop, we can make:
[expression for item in list]
Which is the same as doing:
for item in list: expression
If we want some conditional to apply the expression, we have:
[expression for item in list if conditional ]
Which is the same as doing:
for item in list: if conditional: expression
Example 1: calculating the cube of a number
Regular way
numbers = [1, 2, 3, 4, 5]new_list = []for n in numbers: new_list.append(n**3)print(new_list)
[1, 8, 27, 64, 125]
Using list comprehensions
numbers = [1, 2, 3, 4, 5]new_list = []new_list = [n**3 for n in numbers]print(new_list)
[1, 8, 27, 64, 125]
Example 2: calculating the cube of a number only if it is greater than 3
Using the conditional, we can filter only the values we want the expression to be applied to.
Regular way
numbers = [1, 2, 3, 4, 5]new_list = []for n in numbers: if(n > 3): new_list.append(n**3)print(new_list)
[64, 125]
Using list comprehensions
numbers = [1, 2, 3, 4, 5]new_list = []new_list = [n**3 for n in numbers if n > 3]print(new_list)
[64, 125]
Example 3: calling functions with list comprehensions
We can also call functions using the list comprehension syntax:
numbers = [1, 2, 3, 4, 5]new_list = []def cube(number): return number**3new_list = [cube(n) for n in numbers if n > 3]print(new_list)
[64, 125]
A Python lambda function can only have one expression and can't have multiple lines.
It is supposed to make it easier to create some small logic in one line instead of a whole function as is usually done.
Lambda functions are also anonymous, which means there is no need to name them.
Basic Syntax
The basic syntax is very simple: just use the lambda
keyword, define the parameters needed, and use ":" to separate the parameters from the expression.
The general forms is:
lambda arguments : expression
One parameter example
Look at this example using only one parameter
cubic = lambda number : number**3print(cubic(2))
8
Multiple parameter example
If you want, you can also have multiple parameters.
exponential = lambda multiplier, number, exponent : multiplier * number**exponentprint(exponential(2, 2, 3))
16
Calling the Lambda Function directly
You don't need to use a variable as we did before. Instead you can make use of parenthesis around the lambda function and another pair of parenthesis around the arguments.
The declaration of the function and the execution will happen in the same line.
(lambda multiplier, number, exponent : multiplier * number**exponent)(2, 2, 3)
16
Examples using lambda functions with other built-in functions
Map
The Map function applies the expression to each item in a list.
Let's calculate the cubic of each number in the list.
numbers = [2, 5, 10]cubics = list(map(lambda number : number**3, numbers))print(cubics)
[8, 125, 1000]
Filter
The Filter function will filter the list based on the expression.
Let's filter to have only the numbers greater than 5.
numbers = [2, 5, 10]filtered_list = list(filter(lambda number : number > 5, numbers))print(filtered_list)
[10]
After some time your code starts to get more complex with lots of functions and variables.
To make it easier to organize the code we use Modules.
A well-designed Module also has the advantage of being reusable, so you write code once and reuse it everywhere.
You can write a module with all the mathematical operations and other people can use it.
And, if you need, you can use someone else's modules to simplify your code, speeding up your project.
In other programming languages, these are also referred to as libraries.
Using a Module
To use a module we use the import
keyword.
As the name implies we have to tell our program what module to import.
After that, we can use any function available in that module.
Let's see an example using the math
módulo.
First, let's see how to have access to a constant, Euler's number.
import mathmath.e
2.718281828459045
In this second example, we are going to use a function that calculates the square root of a number.
It is also possible to use the as
keyword to create an alias.
import math as mm.sqrt(121)m.sqrt(729)
1127
Finally, using the from
keyword, we can specify exactly what to import instead of the whole module and use the function directly without the module's name.
This example uses the floor()
function that returns the largest integer less than or equal to a given number.
from math import floorfloor(9.8923)
9
Creating a Module
Now that we know how to use modules, let's see how to create one.
It is going to be a module with the basic math operations add
, subtract
, multiply
, divide
and it is gonna be called basic_operations
.
Create the basic_operations.py
file with the four functions.
def add(first_num, second_num): return first_num + second_numdef subtract(first_num, second_num): return first_num - second_numdef multiply(first_num, second_num): return first_num * second_numdef divide(first_num, second_num): return first_num / second_num
Then, just import the basic_operations
module and use the functions.
import basic_operationsbasic_operations.add(10,2)basic_operations.subtract(10,2)basic_operations.multiply(10,2)basic_operations.divide(10,2)
128205.0
You are in the process of building a module with the basic math operations add
, subtract
, multiply
e divide
called basic_operations
saved in the basic_operations.py
Arquivo.
To guarantee everything is fine, you can run some tests.
def add(first_num, second_num): return first_num + second_numdef subtract(first_num, second_num): return first_num - second_numdef multiply(first_num, second_num): return first_num * second_numdef divide(first_num, second_num): return first_num / second_numprint(add(10, 2)) print(subtract(10,2))print(multiply(10,2))print(divide(10,2))
After running the code:
renan@pro-home:~$ python3 basic_operations.py
The output is:
128205.0
The output for those tests are what we expected.
Our code is right and ready to share.
Let's import the new module run it in the Python console.
Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import basic_operations128205.0>>>
When the module is imported our tests are displayed on the screen even though we didn't do anything besides importing basic_operations
.
To fix that we use if __name__ == '__main__'
no basic_operations.py
file like this:
def add(first_num, second_num): return first_num + second_numdef subtract(first_num, second_num): return first_num - second_numdef multiply(first_num, second_num): return first_num * second_numdef divide(first_num, second_num): return first_num / second_numif __name__ == '__main__': print(add(10, 2)) print(subtract(10,2)) print(multiply(10,2)) print(divide(10,2))
Running the code directly on the terminal will continue to display the tests. But when you import it like a module, the tests won't show and you can use the functions the way you intended.
Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import basic_operations>>> basic_operations.multiply(10,2)20>>>
Now that you know how to use the if __name__ == '__main__'
, let's understand how it works.
The condition tells when the interpreter is treating the code as a module or as a program itself being executed directly.
Python has this native variable called __name__
.
This variable represents the name of the module which is the name of the .py
Arquivo.
Create a file my_program.py
with the following and execute it.
print(__name__)
The output will be:
__main__
This tells us that when a program is executed directly, the variable __name__
is defined as __main__
.
But when it is imported as a module, the value of __name__
is the name of the module.
Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import my_programmy_program>>>
This is how the Python interpreter differentiates the behavior of an imported module and a program executed directly on the terminal.
Creating, deleting, reading, and many other functions applied to files are an integral part of many programs.
As such, it is very important to know how to organize and deal with files directly from your code.
Let's see how to handle files in Python.
File create
First things first, create!
We are going to use the open()
função.
This function opens a file and returns its corresponding object.
The first argument is the name of the file we are handling, the second refers to the operation we are using.
The code below creates the file "people.txt", the x
argument is used when we just want to create the file. If a file with the same name already exists, it will throw an exception.
people_file = open("people.txt", "x")
You can also use the w
mode to create a file. Unlike the x
mode, it will not throw an exception since this mode indicates the writing modo. We are opening a file to write data into it and, if the file doesn't exist, it is created.
people_file = open("people.txt", "w")
The last one is the a
mode which stands for append. As the name implies, you can append more data to the file, while the w
mode simply overwrites any existing data.
When appending, if the file doesn't exist, it also creates it.
people_file = open("people.txt", "a")
File write
To write data into a file, you simply open a file with the w
modo.
Then, to add data, you use the object return by the open()
função. In this case, the object is called people_file
. Then you call the write() function passing the data as argument.
people_file = open("people.txt", "w")people_file.write("Bobn")people_file.write("Maryn")people_file.write("Sarahn")people_file.close()
We use n
at the end to break the line, otherwise the content in the file will stay in the same line as "BobMarySarah".
One more detail is to close() the file. This is not only a good practice, but also ensures that your changes were applied to the file.
Remember that when using w
mode, the data that already existed in the file will be overwritten by the new data. To add new data without losing what was already there, we have to use the append mode.
File append
o a
mode appends new data to the file, keeping the existing one.
In this example, after the first writing with w
mode, we are using the a
mode to append. The result is that each name will appear twice in the file "people.txt".
#first writepeople_file = open("people.txt", "w")people_file.write("Bobn")people_file.write("Maryn")people_file.write("Sarahn")people_file.close()#appending more data#keeping the existing datapeople_file = open("people.txt", "a")people_file.write("Bobn")people_file.write("Maryn")people_file.write("Sarahn")people_file.close()
File read
Reading the file is also very straightforward: just use the r
mode like so.
If you read the "people.txt" file created in the last example, you should see 6 names in your output.
people_file = open("people.txt", "r")print(people_file.read())
BobMarySarahBobMarySarah
o read()
function reads the whole file at once. If you use the readline()
function, you can read the file line by line.
people_file = open("people.txt", "r")print(people_file.readline())print(people_file.readline())print(people_file.readline())
BobMarySarah
You can also loop to read the lines like the example below.
people_file = open("people.txt", "r")for person in people_file: print(person)
BobMarySarahBobMarySarah
Delete a File
To delete a file, you also need the os
módulo.
Use the remove()
método.
import osos.remove('my_file.txt')
Check if a File Exists
Use the os.path.exists()
method to check the existence of a file.
import osif os.path.exists('my_file.txt'): os.remove('my_file.txt')else: print('There is no such file!')
Copy a File
For this one, I like to use the copyfile()
method from the shutil
módulo.
from shutil import copyfilecopyfile('my_file.txt','another_file.txt')
There are a few options to copy a file, but copyfile()
is the fastest one.
Rename and Move a File
If you need to move or rename a file you can use the move()
method from the shutil
módulo.
from shutil import movemove('my_file.txt','another_file.txt')
Classes and Objects are the fundamental concepts of Object-Oriented Programming.
In Python, everything is an object!
A variable (object) is just an instance of its type (class).
That's why when you check the type of a variable you can see the class
keyword right next to its type (class).
This code snippet shows that my_city
is an object and it is an instance of the class str
.
my_city = "New York"print(type(my_city))
Differentiate Class x Object
The class gives you a standard way to create objects. A class is like a base project.
Say you are an engineer working for Boeing.
Your new mission is to build the new product for the company, a new model called 747-Space. This aircraft flies higher altitudes than other commercial models.
Boeing needs to build dozens of those to sell to airlines all over the world, and the aircrafts have to be all the same.
To guarantee that the aircrafts (objects) follow the same standards, you need to have a project (class) that can be replicable.
The class is a project, a blueprint for an object.
This way you make the project once, and reuse it many times.
In our code example before, consider that every string has the same behavior and the same attributes. So it only makes sense for strings to have a class str
to define them.
Attributes and Methods
Objects have some behavior which is is given by attributes and methods.
In simple terms, in the context of an object, attributes are variables and methods are functions attached to an object.
For example, a string has many built-in methods that we can use.
They work like functions, you just need to separate them from the objects using a .
.
In this code snippet, I'm calling the replace()
method from the string variable my_city
which is an object, and an instance of the class str
.
o replace()
method replaces a part of the string for another and returns a new string with the change. The original string remains the same.
Let's replace 'New' for 'Old' in 'New York'.
my_city = 'New York'print(my_city.replace('New', 'Old'))print(my_city)
Old YorkNew York
Creating a Class
We have used many objects (instances of classes) like strings, integers, lists, and dictionaries. All of them are instances of predefined classes in Python.
To create our own classes we use the class
keyword.
By convention, the name of the class matches the name of the .py
file and the module by consequence. It is also a good practice to organize the code.
Create a file vehicle.py
with the following class Vehicle
.
class Vehicle: def __init__(self, year, model, plate_number, current_speed = 0): self.year = year self.model = model self.plate_number = plate_number self.current_speed = current_speed def move(self): self.current_speed += 1 def accelerate(self, value): self.current_speed += value def stop(self): self.current_speed = 0 def vehicle_details(self): return self.model + ', ' + str(self.year) + ', ' + self.plate_number
Let's break down the class to explain it in parts.
o class
keyword is used to specify the name of the class Vehicle
.
o __init__
function is a built-in function that all classes have. It is called when an object is created and is often used to initialize the attributes, assigning values to them, similar to what is done to variables.
The first parameter self
no __init__
function is a reference to the object (instance) itself. Nós chamamos isso self
by convention and it has to be the first parameter in every instance method, as you can see in the other method definitions def move(self)
, def accelerate(self, value)
, def stop(self)
e def vehicle_details(self)
.
Vehicle
has 5 attributes (including self): year
, model
, plate_number
e current_speed
.
Inside the __init__
, each one of them is initialized with the parameters given when the object is instantiated.
Notice that current_speed
is initialized with 0
by default, meaning that if no value is given, current_speed
will be equal to 0 when the object is first instantiated.
Finally, we have three methods to manipulate our vehicle regarding its speed: def move(self)
, def accelerate(self, value)
e def stop(self)
.
And one method to give back information about the vehicle: def vehicle_details(self)
.
The implementation inside the methods work the same way as in functions. You can also have a return
to give you back some value at the end of the method as demonstrated by def vehicle_details(self)
.
Using the Class
To use the class in your terminal, import the Vehicle
class from the vehicle
módulo.
Create an instance called my_car
, initializing year
with 2009, model
with 'F8', plate_number
with 'ABC1234', and current_speed
with 100.
o self
parameter is not taken into consideration when calling methods. The Python interpreter infers its value as being the current object/instance automatically, so we just have to pass the other arguments when instantiating and calling methods.
Now use the methods to move()
the car which increases its current_speed
by 1, accelerate(10)
which increases its current_speed
by the value given in the argument, and stop()
which sets the current_speed
to 0.
Remember to print the value of current_speed
at every command to see the changes.
To finish the test, call vehicle_details()
to print the information about our vehicle.
>>> from vehicle import Vehicle>>>>>> my_car = Vehicle(2009, 'F8', 'ABC1234', 100)>>> print(my_car.current_speed)100>>> my_car.move()>>> print(my_car.current_speed)101>>> my_car.accelerate(10)>>> print(my_car.current_speed)111>>> my_car.stop()>>> print(my_car.current_speed)0>>> print(my_car.vehicle_details())F8, 2009, ABC1234
If we don't set the initial value for current_speed
, it will be zero by default as stated before and demonstrated in the next example.
>>> from vehicle import Vehicle>>>>>> my_car = Vehicle(2009, 'F8', 'ABC1234')>>> print(my_car.current_speed)0>>> my_car.move()>>> print(my_car.current_speed)1>>> my_car.accelerate(10)>>> print(my_car.current_speed)11>>> my_car.stop()>>> print(my_car.current_speed)0>>> print(my_car.vehicle_details())F8, 2009, ABC1234
Let's define a generic Vehicle
class and save it inside the vehicle.py
Arquivo.
class Vehicle: def __init__(self, year, model, plate_number, current_speed): self.year = year self.model = model self.plate_number = plate_number self.current_speed = current_speed def move(self): self.current_speed += 1 def accelerate(self, value): self.current_speed += value def stop(self): self.current_speed = 0 def vehicle_details(self): return self.model + ', ' + str(self.year) + ', ' + self.plate_number
A vehicle has attributes year
, model
, plate_number
e current_speed
.
The definition of vehicle in the Vehicle
is very generic and might not be suitable for trucks, for instance, because it should include a cargo
attribute.
On the other hand, a cargo attribute does not make much sense for small vehicles like motorcycles.
To solve this we can use inheritance.
When a class (child) inherits another class (parent), all the attributes and methods from the parent class are inherited by the child class.
Parent and Child
In our case, we want a new Truck
class to inherit everything from the Vehicle
class. Then we want it to add its own specific attribute current_cargo
to control the addition and removal of cargo from the truck.
o Truck
class is called a child class that inherits from its parent class Vehicle
.
UMA parent class is also called a superclass while a child class is also known as a subclass.
Create the class Truck
and save it inside the truck.py
Arquivo.
from vehicle import Vehicleclass Truck(Vehicle): def __init__(self, year, model, plate_number, current_speed, current_cargo): super().__init__(year, model, plate_number, current_speed) self.current_cargo = current_cargo def add_cargo(self, cargo): self.current_cargo += cargo def remove_cargo(self, cargo): self.current_cargo -= cargo
Let's break down the class to explain it in parts.
The class Vehicle
inside the parentheses when defining the class Truck
indicates that the parent Vehicle
is being inherited by its child Truck
.
o __init__
method has self
as its first parameter, as usual.
The parameters year
, model
, plate_number
e current_speed
are there to match the ones in the Vehicle
class.
We added a new parameter current_cargo
suited for the Truck
class.
In the first line of the __init__
method of the Truck
class we have to call the __init__
method of the Vehicle
class.
To do that we use super()
to make a reference to the supperclass Vehicle
, so when super().__init__(year, model, plate_number, current_speed)
is called we avoid repetition of our code.
After that, we can assign the value of current_cargo
normally.
Finally, we have two methods to deal with the current_cargo
: def add_cargo(self, cargo):
e def remove_cargo(self, cargo):
.
Lembre-se disso Truck
inherits attributes and methods from Vehicle
, so we also have an implicit access to the methods that manipulate the speed: def move(self)
, def accelerate(self, value)
e def stop(self)
.
Usando o Truck
class
To use the class in your terminal, import the Truck
class from the truck
módulo.
Create an instance called my_truck
, initializing year
with 2015, model
with 'V8', plate_number
with 'XYZ1234', current_speed
with 0, and current_cargo
with 0.
Usar add_cargo(10)
to increase current_cargo
by 10, remove_cargo(4)
, to decrease current_cargo
by 4.
Remember to print the value of current_cargo
at every command to see the changes.
By inheritance, we can use the methods from the Vehicle
class to move()
the truck which increases its current_speed
by 1, accelerate(10)
which increases its current_speed
by the value given in the argument, and stop()
which sets the current_speed
to 0.
Remember to print the value of current_speed
at every interaction to see the changes.
To finish the test, call vehicle_details()
inherited from the Vehicle
class to print the information about our truck.
>>> from truck import Truck>>> >>> my_truck = Truck(2015, 'V8', 'XYZ1234', 0, 0)>>> print(my_truck.current_cargo)0>>> my_truck.add_cargo(10)>>> print(my_truck.current_cargo)10>>> my_truck.remove_cargo(4)>>> print(my_truck.current_cargo)6>>> print(my_truck.current_speed)0>>> my_truck.accelerate(10)>>> print(my_truck.current_speed)10>>> my_truck.stop()>>> print(my_truck.current_speed)0>>> print(my_truck.vehicle_details())V8, 2015, XYZ1234
Errors are a part of every programmer's life, and knowing how to deal with them is a skill on its own.
The way Python deals with errors is called 'Exception Handling'.
If some piece of code runs into an error, the Python interpreter will raise an exception.
Types of Exceptions
Let's try to raise some exceptions on purpose and see the errors they produce.
First, try to add a string and an integer
'I am a string' + 32
Traceback (most recent call last): File "", line 1, in TypeError: must be str, not int
Now, try to access an index that doesn't exist in a list.
A common mistake is to forget that sequences are 0-indexed, meaning the first item has index 0, not 1.
In this example, the list car_brands
ends at index 2.
car_brands = ['ford', 'ferrari', 'bmw']print(car_brands[3])
Traceback (most recent call last): File "", line 1, in IndexError: list index out of range
If we try to print a variable that doesn't exist:
print(my_variable)
Traceback (most recent call last): File "", line 1, in NameError: name 'my_variable' is not defined
Math doesn't allow division by zero, so trying to do so will raise an error, as expected.
32/0
Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
This was just a sample of the kinds of exceptions you might see during your daily routine and what can cause each of them.
Exception Handling
Now we know how to cause errors that will crash our code and show us some message saying something is wrong.
To handle these exceptions just make use of the try/except
declaração.
try: 32/0except: print('Dividing by zero!')
Dividing by zero!
The example above shows the use of the try
declaração.
Put the block of code that may cause an exception inside the try
scope. If everything runs alright, the except
block is not invoked. But if an exception is raised, the block of code inside the except
is executed.
This way the program doesn't crash and if you have some code after the exception, it will keep running if you want it to.
Specific Exception Handling
In the last example the except
block was generic, meaning it was catching anything.
Good practice it to specify the type of exception we are trying to catch, which helps a lot when debugging the code later.
If you know a block of code can throw an IndexError
, specify it in the except
:
try: car_brands = ['ford', 'ferrari', 'bmw'] print(car_brands[3])except IndexError: print('There is no such index!')
There is no such index!
You can use a tuple to specify as many exception types as you want in a single except
:
try: print('My code!')except(IndexError, ZeroDivisionError, TypeError): print('My Excepetion!')
else
It is possible to add an else
command at the end of the try/except
. It runs only if there are no exceptions.
my_variable = 'My variable'try: print(my_variable)except NameError: print('NameError caught!')else: print('No NameError')
My variableNo NameError
Raising Exceptions
o raise
command allows you to manually raise an exception.
This is particularly useful if you want to catch an exception and do something with it -- like logging the error in some personalized way like redirecting it to a log aggregator, or ending the execution of the code since the error should not allow the progress of the program.
try: raise IndexError('This index is not allowed')except: print('Doing something with the exception!') raise
Doing something with the exception!Traceback (most recent call last): File "", line 2, in IndexError: This index is not allowed
finally
o finally
block is executed independently of exceptions being raised or not.
They are usually there to allow the program to clean up resources like files, memory, network connections, etc.
try: print(my_variable)except NameError: print('Except block')finally: print('Finally block')
Except blockFinally block
É isso aí!
Congratulations on reaching the end.
I want to thank you for reading this article.
If you want to learn more, checkout my blog renanmf.com.
Remember to download a PDF version of this Python Guide for Beginners.
You can also find me on Twitter: @renanmouraf.