Python é uma linguagem de programação de tipagem dinâmica e forte. Ela usa tanto duck typing quanto tipagem gradual por meio de type hints.
Embora Python dê suporte a muitos estilos diferentes de programação, internamente tudo em Python é um objeto. Isso inclui números, strings, listas e até funções.
Vamos nos aprofundar no que tudo isso significa conforme avançamos pela trilha.
Este primeiro exercício apresenta 4 recursos principais da linguagem Python:
def e a palavra-chave return),Em geral, o conteúdo, os testes e as ferramentas de análise da trilha de Python seguem as convenções de estilo descritas na PEP 8 e na PEP 257 para estilo de código Python, com a sugestão adicional (forte) de que não haja nomes de variáveis de uma única letra nem variáveis chamadas "_".
Na trilha de Python, as variáveis são sempre escritas em snake_case, e as constantes em SCREAMING_SNAKE_CASE.
Quem programa pode vincular nomes (também chamados de variáveis) a qualquer tipo de objeto usando o operador de atribuição =: <name> = <value>.
Um nome pode receber uma nova atribuição (ou ser vinculado novamente) a valores diferentes (tipos de objeto diferentes) ao longo de sua existência.
>>> my_first_variable = 1 #<-- my_first_variable bound to an integer object of value one.
>>> my_first_variable = 2 #<-- my_first_variable re-assigned to integer value 2.
>>> print(type(my_first_variable))
<class 'int'>
>>> print(my_first_variable)
2
>>> my_first_variable = "Now, I'm a string." #<-- You may re-bind a name to a different object type and value.
>>> print(type(my_first_variable))
<class 'str'>
>>> my_first_variable = 'You can call me "str".' #<-- Strings can be declared using single or double quote marks.
>>> print(my_first_variable)
You can call me "str".
Constantes são nomes que devem ser atribuídos apenas uma vez em um programa.
Elas devem ser definidas no nível de módulo (arquivo), e normalmente ficam visíveis para todas as funções e classes do programa.
Usar SCREAMING_SNAKE_CASE sinaliza que o nome não deve receber nova atribuição, nem ter seu valor alterado.
A palavra-chave def inicia uma definição de função.
Cada função pode ter zero ou mais parâmetros formais entre parênteses (), seguidos de dois-pontos :.
As instruções do corpo da função começam na linha seguinte ao def e precisam estar indentadas em um bloco.
# The body of a function is indented by 2 spaces, & prints the sum of the numbers.
def add_two_numbers(number_one, number_two):
total = number_one + number_two
print(total)
>>> add_two_numbers(3, 4)
7
# Inconsistent indentation in your code blocks will raise an error.
>>> def add_three_numbers_misformatted(number_one, number_two, number_three):
... result = number_one + number_two + number_three # This was indented by 4 spaces.
... print(result) #this was only indented by 3 spaces
...
...
File "<stdin>", line 3
print(result)
^
IndentationError: unindent does not match any outer indentation level
As funções retornam explicitamente um valor ou objeto por meio da palavra-chave return:
# Function definition on first line, explicit return used on final line.
>>> def add_two_numbers(number_one, number_two):
return number_one + number_two
# Calling the function in the Python shell returns the sum of the numbers.
>>> add_two_numbers(3, 4)
7
# Assigning the function call to a variable and printing it
# will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11
As funções que não têm uma expressão explícita após um return vão retornar implicitamente o objeto None.
Os detalhes de None serão abordados em um exercício posterior.
Para os fins deste exercício e desta explicação, None é um marcador que representa nada, ou null:
# This function will return `None`
def square_a_number(number):
square = number * number
return # <-- note that this return is not followed by an expression
# Calling the function in the Python shell appears
# to not return anything at all.
>>> square_a_number(2)
>>>
# Using print() with the function call shows that
# the function is actually returning the **None** object.
>>> print(square_a_number(2))
None
As funções que omitem return também vão retornar implicitamente o objeto None.
Isso significa que, se você não usar return em uma função, o Python vai retornar o objeto None para você.
# This function omits a return keyword altogether.
def add_two_numbers(number_one, number_two):
result = number_one + number_two
>>> add_two_numbers(5, 7)
>>> print(add_two_numbers(5, 7))
None
# Assigning the function call to a variable and printing
# the variable will also show None.
>>> sum_without_return = add_two_numbers(5, 6)
>>> print(sum_without_return)
None
As funções são chamadas ou invocadas usando seu nome seguido de ().
A notação de ponto (.) é usada para chamar funções definidas dentro de uma classe ou módulo.
>>> def raise_to_power(number, power):
... return number ** power
...
>>> raise_to_power(3,3) # <--Invoking the function with the arguments 3 and 3.
27
# A mismatch between the number of parameters and the number of arguments will raise an error.
>>> raise_to_power(4,)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: raise_to_power() missing 1 required positional argument: 'power'
# Calling methods or functions in classes and modules.
>>> start_text = "my silly sentence for examples."
>>> str.upper(start_text) # <--Calling the upper() method from the built-in str class on start_text.
'MY SILLY SENTENCE FOR EXAMPLES.'
# Importing the math module
>>> import math
>>> math.pow(2,4) # <--Calling the pow() function from the math module.
16.0
Os comentários em Python começam com um # que não faz parte de uma string e terminam no fim da linha.
Diferente de muitas outras linguagens de programação, o Python não tem suporte a marcas de comentário de várias linhas.
Cada linha de um bloco de comentário precisa começar com o caractere #.
A primeira instrução do corpo de uma função pode, opcionalmente, ser uma docstring, que resume de forma concisa o propósito da função ou do objeto. As docstrings são declaradas usando três aspas duplas (""") indentadas no mesmo nível do bloco de código:
# An example from PEP257 of a multi-line docstring
# reformatted to use Google style non-type hinted docstrings.
# Some additional details can be found in the Sphinx documentation:
# https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword Arguments:
real (float): The real part of the number (default 0.0)
imag (float): The imaginary part of the number (default 0.0)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
As docstrings são lidas por ferramentas automatizadas de documentação, como o Sphinx, e são retornadas ao chamar o atributo especial .__doc__ na função, no método ou no nome da classe.
As convenções gerais de docstring estão descritas na PEP257, mas os formatos exatos variam de projeto para projeto e de equipe para equipe.
Os exercícios de conceito do Exercism tentam seguir o estilo Google para código sem type hints.
As docstrings também podem funcionar como testes de unidade leves, que serão abordados em um exercício posterior.
# An example on a user-defined function using a Google style docstring.
>>> def raise_to_power(number, power):
"""Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
"""
return number ** power
...
# Calling the .__doc__ attribute of the function and printing the result.
>>> print(raise_to_power.__doc__)
Raise a number to an arbitrary power.
Parameters:
number (int): The base number.
power (int): The power to raise the base number to.
Returns:
int: The number raised to the specified power.
Takes a number and raises it to the specified power, returning the result.
Você vai escrever um código para ajudar a preparar uma lasanha maravilhosa do seu livro de receitas favorito.
Você tem cinco tarefas, todas relacionadas ao preparo da sua receita.
Nós já começamos a primeira definição de função para você no arquivo stub, mas você vai precisar escrever as demais definições de função por conta própria. Você também vai precisar definir as constantes por conta própria. Leia com atenção as linhas de comentário #TODO no arquivo stub. Assim que terminar uma tarefa, remova o comentário TODO.
Defina a constante EXPECTED_BAKE_TIME, que representa quantos minutos a lasanha deve ficar no forno.
De acordo com o seu livro de receitas, a lasanha deve ficar no forno por 40 minutos:
>>> print(EXPECTED_BAKE_TIME)
40
Complete a função bake_time_remaining(), que recebe como argumento os minutos reais que a lasanha já passou no forno e retorna quantos minutos ela ainda precisa ficar no forno, com base na constante EXPECTED_BAKE_TIME.
>>> bake_time_remaining(30)
10
Defina a função preparation_time_in_minutes(), que recebe como argumento o number_of_layers que você quer adicionar à lasanha e retorna quantos minutos você levaria para prepará-las.
Considere que cada camada leva 2 minutos para preparar.
>>> def preparation_time_in_minutes(number_of_layers):
...
...
>>> preparation_time_in_minutes(2)
4
Defina a função elapsed_time_in_minutes(), que recebe dois parâmetros como argumentos:
number_of_layers (o número de camadas adicionadas à lasanha)elapsed_bake_time (o número de minutos que a lasanha já passou no forno).Essa função deve retornar o total de minutos que você passou na cozinha cozinhando: o seu tempo de preparo montando as camadas mais o tempo que a lasanha passou no forno.
>>> def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time):
...
...
>>> elapsed_time_in_minutes(3, 20)
26
Percorra a receita novamente, adicionando "notas" na forma de docstrings de função.
def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time):
"""Calculate the elapsed cooking time.
Parameters:
number_of_layers (int): The number of layers in the lasagna.
elapsed_bake_time (int): Time the lasagna has been baking in the oven.
Returns:
int: The total time elapsed (in minutes) preparing and baking.
This function takes two integers representing the number of lasagna
layers and the time already spent baking the lasagna. It calculates
the total elapsed minutes spent cooking (preparing + baking).
"""
Crie sua conta no Exercism para aprender e dominar Python com 17 conceitos146 exercícios e mentoria humana de verdade, tudo de graça.