Trilhas
/
Python
Python
/
Programa
/
Noções básicas
No

Noções básicas em Python

113 exercícios

Sobre Noções básicas

Python é uma linguagem de programação dinâmica e fortemente tipada. Ela usa tanto duck typing quanto tipagem gradual, por meio de type hints. Os estilos de programação imperativa, declarativa (por exemplo, funcional) e orientada a objetos são todos suportados, mas internamente tudo em Python é um objeto.

O Python dá muita ênfase à legibilidade do código e (de forma semelhante ao Haskell) usa indentação significativa para denotar definições de funções, métodos e classes.

O Python foi criado por Guido van Rossum e lançado pela primeira vez em 1991. A Python Software Foundation gerencia e direciona recursos para o desenvolvimento de Python e do CPython e recebe propostas de mudanças na linguagem de membros da comunidade por meio das Python Enhancement Proposals ou PEPs.

A documentação completa da versão atual está em docs.python.org.


Este primeiro conceito apresenta 4 recursos principais da linguagem Python:

  1. Atribuição de nomes (variáveis e constantes),
  2. Funções (a palavra-chave def e a palavra-chave return),
  3. Comentários, e
  4. Docstrings.
Note

Em geral, o conteúdo, os testes e as ferramentas de análise da trilha 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 com uma única letra.

O zen do Python (PEP 20) e What is Pythonic? apresentam filosofias adicionais.

Na trilha Python, as variáveis são sempre escritas em snake_case, e as constantes em SCREAMING_SNAKE_CASE

Atribuição de nomes (variáveis e constantes)

Em Python, não há palavras-chave usadas para criar variáveis ou constantes. Em vez disso, 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 ser reatribuído (ou revinculado) a valores diferentes (tipos de objeto diferentes) ao longo de sua existência.

Por exemplo, my_first_variable pode ser reatribuída muitas vezes usando =, e pode se referir a tipos de objeto diferentes a cada reatribuição:

>>> 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".

>>> import collections
>>> my_first_variable = collections.Counter([1,1,2,3,3,3,4,5,6,7]) # <--Now my_first_variable has been re-bound to a Counter object.
>>> print(type(my_first_variable))
<class 'collections.Counter'>

>>> print(my_first_variable)
Counter({3: 3, 1: 2, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1})

Constantes

Constantes são nomes que devem ser atribuídos apenas uma vez em um programa. Elas devem ser definidas no nível de um módulo (arquivo), e normalmente são visíveis para todas as funções e classes do programa. Usar SCREAMING_SNAKE_CASE sinaliza que o nome não deve ser reatribuído, nem seu valor alterado.

# All caps signal that this is intended as a constant.
MY_FIRST_CONSTANT = 16

# Re-assignment will be allowed by the compiler & interpreter,
# but this is VERY strongly discouraged.
# Please don't do this, it could create problems in your program!
MY_FIRST_CONSTANT = "Some other value"

Funções

Em Python, unidades de funcionalidade são encapsuladas em funções, que são elas mesmas objetos (é tartarugas até o fim).

As funções podem ser executadas por si mesmas, passadas como argumentos para outras funções, aninhadas ou vinculadas a uma classe. Quando funções são vinculadas a um nome de classe, elas são chamadas de métodos. Funções e classes relacionadas (com seus métodos) podem ser agrupadas no mesmo arquivo ou módulo, e importadas em parte ou no todo para uso em outros programas.

A palavra-chave def inicia uma definição de função. Cada função pode ter zero ou mais parâmetros formais nos parênteses (), seguidos de dois-pontos :. As instruções do corpo da função começam na linha seguinte ao def e devem 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 
# the variable will also return the value.
>>> sum_with_return = add_two_numbers(5, 6)
>>> print(sum_with_return)
11

Funções que não têm uma expressão explícita após um return retornam implicitamente o objeto None. Os detalhes de None serão abordados em um conceito 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

Funções que omitem return também retornam implicitamente o objeto None. Isso significa que, se você não usar return em uma função, o Python 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

Chamando funções

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 mis-match 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.'

# Because a string is an instance of the str class, methods can also be called on them "directly".
>>> start_text = "my silly sentence for examples."
>>> start_text.upper()  # <--Calling the upper() method on start_text directly.
'MY SILLY SENTENCE FOR EXAMPLES.'

# Alternatively, we can skip the variable assignment (although this gets messy quick).
>>> "my silly sentence for examples.".upper()
'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

Comentários

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 suporta marcas de comentário multilinha. Cada linha de um bloco de comentário deve começar com o caractere #.

Os comentários são ignorados pelo interpretador:

# This is a single line comment.

x = "foo"  # This is an in-line comment.

# This is a multi-line
# comment block over multiple lines --
# these should be used sparingly.

Docstrings

A primeira instrução do corpo de uma função pode ser, opcionalmente, 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 e são retornadas ao chamar o atributo especial .__doc__ na função, no método ou no nome da classe. Elas são recomendadas para programas de qualquer tamanho que precisem de documentação, e suas convenções estão descritas na PEP257.

As docstrings também podem funcionar como testes de unidade leves, que podem ser lidos e executados pelo PyTest, ou importando o módulo doctest. Testes e doctest serão abordados em um conceito 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.

...

# Printing the __doc__ attribute of the built-in type: str.
>>> print(str.__doc__)
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to 'utf-8'.
errors defaults to 'strict'.
Editar via GitHub O link abre em uma nova janela ou aba

Aprenda Noções básicas