Tracks
/
Python
Python
/
Temario
/
Fundamentos
Fu

Fundamentos en Python

113 ejercicios

Acerca de Fundamentos

Python es un lenguaje de programación de tipado dinámico y fuerte. Emplea tanto el tipado pato como el tipado gradual, mediante las anotaciones de tipo. Se admiten los estilos de programación imperativo, declarativo (por ejemplo, funcional) y orientado a objetos, pero, internamente, en Python todo es un objeto.

Python hace mucho hincapié en la legibilidad del código y (de forma similar a Haskell) usa la indentación significativa para denotar definiciones de funciones, métodos y clases.

Python fue creado por Guido van Rossum y se publicó por primera vez en 1991. La Python Software Foundation gestiona y dirige los recursos para el desarrollo de Python y CPython, y recibe propuestas de cambios en el lenguaje de los miembros de la comunidad a través de las propuestas de mejora de Python, o PEP.

La documentación completa de la versión actual está en docs.python.org.


Este primer concepto presenta 4 características principales del lenguaje Python:

  1. Asignación de nombres (variables y constantes),
  2. Funciones (la palabra clave def y la palabra clave return),
  3. Comentarios, y
  4. Docstrings.
Note

En general, el contenido, las pruebas y las herramientas de análisis de la pista de Python siguen las convenciones de estilo descritas en PEP 8 y PEP 257 para el estilo del código Python, con la sugerencia adicional (y firme) de que no haya nombres de variable de una sola letra.

El zen de Python (PEP 20) y ¿Qué es pythonico? exponen filosofías adicionales.

En la pista de Python, las variables se escriben siempre en snake_case, y las constantes en SCREAMING_SNAKE_CASE

Asignación de nombres (variables y constantes)

En Python no se usa ninguna palabra clave para crear variables o constantes. En su lugar, quienes programan pueden vincular nombres (también llamados variables) a cualquier tipo de objeto con el operador de asignación =: <name> = <value>. Un nombre puede reasignarse (o revincularse) a distintos valores (distintos tipos de objeto) a lo largo de su vida.

Por ejemplo, my_first_variable puede reasignarse muchas veces con =, y puede referirse a distintos tipos de objeto en cada reasignación:

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

Las constantes son nombres que están pensados para asignarse solo una vez en un programa. Deben definirse a nivel de módulo (fichero) y, normalmente, son visibles para todas las funciones y clases del programa. Usar SCREAMING_SNAKE_CASE indica que el nombre no debe reasignarse ni debe mutar su valor.

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

Funciones

En Python, las unidades de funcionalidad se encapsulan en funciones, que a su vez son objetos (es tortugas hasta el fondo).

Las funciones pueden ejecutarse por sí solas, pasarse como argumentos a otras funciones, anidarse o vincularse a una clase. Cuando las funciones se vinculan a un nombre de clase, se denominan métodos. Las funciones y clases relacionadas (con sus métodos) pueden agruparse en el mismo fichero o módulo, e importarse en parte o en su totalidad para usarlas en otros programas.

La palabra clave def inicia una definición de función. Cada función puede tener cero o más parámetros formales entre paréntesis (), seguidos de dos puntos :. Las instrucciones del cuerpo de la función empiezan en la línea siguiente a def y deben ir indentadas en un bloque:

# 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

Las funciones devuelven explícitamente un valor u objeto mediante la palabra clave 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

Las funciones que no tienen una expresión explícita después de un return devolverán implícitamente el objeto None. Los detalles de None se tratarán en un concepto posterior. A efectos de este ejercicio y esta explicación, None es un marcador de posición que no representa nada, o 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

Las funciones que omiten return también devolverán implícitamente el objeto None. Esto significa que si no usas return en una función, Python devolverá el objeto None por ti.


# 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

Llamar a funciones

Las funciones se llaman o se invocan con su nombre seguido de (). La notación de punto (.) se usa para llamar a funciones definidas dentro de una clase o un 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

Comentarios

Los comentarios en Python empiezan con un # que no forma parte de un string y terminan al final de la línea. A diferencia de muchos otros lenguajes de programación, Python no admite marcas de comentarios de varias líneas. Cada línea de un bloque de comentarios debe empezar con el carácter #.

El intérprete ignora los comentarios:

# 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

La primera instrucción del cuerpo de una función puede ser, de forma opcional, un docstring, que resume de forma concisa el propósito de la función o el objeto. Los docstrings se declaran con triples comillas dobles (""") indentadas al mismo nivel que el bloque 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

Los docstrings los leen las herramientas de documentación automática y se devuelven llamando al atributo especial .__doc__ de la función, el método o la clase. Se recomiendan para programas de cualquier tamaño que necesiten documentación, y sus convenciones se describen en PEP257.

Los docstrings también pueden funcionar como pruebas unitarias ligeras, que PyTest puede leer y ejecutar, o hacerlo importando el módulo doctest. Las pruebas y doctest se tratarán en un concepto 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 en GitHub El enlace se abre en una nueva ventana o pestaña

Aprende Fundamentos