External Packages / Paquetes Externos - Coding Basics #19

pip install newPost


realPython2.jpg

Shoutout to Real Python

HiveDivider.png

In this article you'll find:

  • Introduction
  • What is a package?
  • How to install a package?
  • Some of the most popular Python packages

HiveDivider.png

Before we fully retire from the modules, I must introduce you to something of the utmost importance for your programming career. Something you'll wear on each and every

the projects you find from now on: Installing external modules or libraries.

You see, Python is a very complete language, which can provide us with a large number of tools which are very useful when creating applications.

However, like any programming language, its base version is limited by the number of problems that a field as broad as programming can present.

This is why the Python community has created different libraries, which provide Python with multiple functionalities: From extracting content from web pages to being able to create our own Web Apps and using the power of artificial intelligence.

If you want to know how to make Python much more than a programming language. Keep reading.

Let's get started

HiveDivider.png

What is an external module or Package?


Analytics Vidhya.png

Shoutout to Analytics Vidhya

As explained in previous articles, a module is a group of functions, classes and variables that allow us to extend the capabilities of our programming language.

However, so far we have only worked with internal methods, which are pre-installed in the IDE by default. If we want to call them, we just have to take a look at the list of Python built-in modules. The problem comes when we want to carry out tasks that are beyond the possibilities of any of these methods.

This is where the external modules, better known as packages, are presented. The only difference they present with respect to the built-in modules is that they do not come with the IDE, which is why they must be installed, either from the command line or any other method.

One of the best known examples of the most popular packages for Python is the NumPy library, which allows us to have an advanced version of Math to handle multidimensional arrays and matrices, including much more advanced methods. This can be found on the Internet and easily installed if we follow the instructions below.

HiveDivider.png

How to install a package


ListenData.png

Shoutout to ListenData

The first step to install a package will be to open our Unix command line (If you use Mac/Linux) or our cmd (If you use Windows). Once here, you will have to make sure if you have Python installed. For this, we will write:

>>>py --version

And for Mac/Unix:

>>>python3 --version

Note: If you have a version of Python lower than 3.0.0 or if the command line doesn't recognize the command, try typing python --version.

If the following message appears:

Python (Number according to your version)

That means we have python installed. In case it does not appear under any circumstances, you must install Python.

Now we need to make sure we have pip installed. Pip is the Python package management system, through which we can install the packages we want to use. Thus, in order to verify, we write

  • On Windows:
>>>py -m pip --version
  • On Mac/Unix:
>>> python3 -m pip --version

By default, all versions of Python after 3.4 have pip installed. In case you have pip, the following message will appear on your command line:

pip (version) from (Your Python site-packages Directory)

In case it does not appear, you can try to run it with bootstrap using the following command:

*Windows:

py -m ensurepip --default-pip
  • Mac/Unix:
python3 -m ensurepip --default-pip

Alternatively, you can download the get-pip.py script, use cd + (Address of the folder where get-pip.py is downloaded) to go to the directory where get-pip.py is, and finally run:

>>> py get-pip.py

either

>>> python3 get-pip.py

Note: If you ever have problems with packages due to an outdated version of pip, use the following command to update it:

>>> py -m pip install --upgrade pip (Windows)

>>> python -m pip install --upgrade pip (MacOS/Unix)

Once we make sure that pip is installed, we just have to look for the package that we want to install. For this, we can go to PyPi (The Python Package Index), which is a repository with endless Python packages. A google search with 'pypi (Package name)', will be enough for us to have PyPi in the first result, we enter this and we will see the following image:

image.png

Here, we focus on the section that says pip install (Package Name). This will be the syntax that we will use whenever we want to install a package. To do this, we go back to our command line and type it:

pip install numpy

Thus, the files corresponding to the package will begin to be downloaded and once finished, you can use it just by writing import (Package name) in a corresponding file.

To test this, let's say we want to create an array with numpy. For this, we import the module and use the following statement:

from numpy import np

a = np.matrix('1 2; 3 4')
print(a)

>>> matrix([[1, 2],
            [3. 4]])

Thus, we know that it was possible to install a module with pip.

Note: If you work with a virtual environment that you will use in a github repository, you must install the packages that you will use again.

HiveDivider.png

Some of the most popular Python packages

Panda


GeeksForGeeks.png

Shoutout to GeeksforGeeks

Pandas is the preferred choice of data analysts who work with Python, because it allows us to work and analyze huge data sets and produce statistics without having to learn additional programming languages. To install this, you just have to use:

pip install pandas

Requests


Edureka.jpg

Shoutout to Edureka

Requests is an HTTP library for Python that allows us to obtain relevant information from websites, which is why it is used quite frequently in Web Scraping. If you want to work with projects on the web, this package is essential. To install it:

pip install requests

scikit-learn


Scikit-Learn.png

Shoutout to Scikit-Learn

Another of the most popular packages is scikit-learn, which provides us with a free tool to create regression and classification algorithms that we will use to create artificial intelligence projects. To install it:

pip install scikit-learn

HiveDivider.png

The learning of a programmer never ends. This is due to the number of modules that you must use for each project, each one requiring an understanding of its documentation and its potential. Once you know how to install modules, you'll be one step closer to creating complex and beautiful applications.

That is why, with the following information, you will be able to install modules with great ease and use them in your subsequent programs.

That being said, we conclude with the modules, and can now start with another topic that is quite confusing for many: Regular expressions. See you in the next chapter of Coding Basics.

HiveDivider.png

Thank you for your support and good luck!

HiveDivider.png

@jesalmofficial.png

HiveDivider.png

pip install nuevoPost


realPython2.jpg

Shoutout to Real Python

HiveDivider.png

In this article you'll find:

  • Introducción
  • ¿Qué es un paquete?
  • Como instalar un paquete
  • Algunos de los paquetes más populares de Python

HiveDivider.png

Antes de retirarnos totalmente de los módulos, debo de presentarte algo de suma importancia para tu carrera en la programación. Algo que usarás en todos y cada uno de los proyectos que encuentres de ahora en adelante: El instalar módulos externos o librerías.

Verás, Python es un lenguaje muy completo, que nos puede proporcionar gran cantidad de herramientas las cuales son de gran utilidad a la hora de crear aplicaciones.

Sin embargo, como cualquier lenguaje de programación, su versión base se ve limitada frente a la cantidad de problemas que un campo tan amplio como el de la programación puede presentar.

Es por esto, que la comunidad de Python han creado distintas librerías, las cuales proveen a Python de múltiples funcionalidades: Desde Extraer contenido de páginas web hasta poder crear nuestras propias Web App y usar el poder de la inteligencia artificial.

Si quieres saber como convertir a Python en mucho más que un lenguaje de programación. Sigue leyendo.

¡Comencemos!

HiveDivider.png

¿Qué es un módulo o paquete externo?


Analytics Vidhya.png

Shoutout to Analytics Vidhya

Según lo explicado en artículos previos, un módulo es una agrupación de funciones, clases y variables que permiten extender las capacidades de nuestro lenguaje de programación.

Sin embargo, hasta ahora solo hemos trabajados con métodos internos, los cuales se encuentran preinstalados en el IDE por defecto. Si queremos llamarlos, solo tenemos que echar un vistazo a la lista de módulos built-in de Python. El problema viene cuando queremos llevar a cabo tareas que escapan de las posibilidades de alguno de estos métodos.

Es aquí donde se presentan los módulos externos, más conocido como paquete. La única diferencia que presentan respecto a los módulos built-in es que estos no vienen con el IDE, razón por la cual deben de ser instalados, ya sea desde la línea de comandos o cualquier otro método.

Uno de los ejemplos más conocidos de los paquetes más populares para Python es la librería NumPy, que nos permite tener una versión avanzada de Math para manejar arreglos multidimensionales y matrices, incluyendo métodos mucho más avanzados. Esta puede encontrarse en Internet e instalarse con facilidad si seguimos las siguientes instrucciones.

HiveDivider.png

Como instalar un paquete


ListenData.png

Shoutout to ListenData

El primer paso para instalar un paquete será abrir nuestra línea de comandos Unix (Si usas Mac/Linux) o nuestro cmd (Si usas Windows). Una vez aquí, deberás cerciorarte de si tienes Python instalado. Para esto, escribiremos:

>>>py --version

Y para Mac/Unix:

>>>python3 --version

Nota: Si posees una versión de Python inferior a la 3.0.0 o si la línea de comandos no reconoce la instrucción, intenta escribir python --version.

Si nos aparece el siguiente mensaje:

Python (Number according to your version)

Eso significa que tenemos Python instalado. En caso de que no aparezca bajo ninguna circunstancia, deberás de instalar Python.

Ahora debemos de asegurar de que tengamos instalado pip. Pip es el sistema de gestión de paquetes de Python, por el cual podremos instalar los paquetes que queramos usar. Así, en orden de verificar, escribimos.

  • En Windows:
>>>py -m pip --version
  • En Mac/Unix:
>>> python3 -m pip --version 

Por defecto, todas las versiones de Python después de la 3.4 traen a pip instalado. En caso de que tengas pip, aparecerá el siguiente mensaje en tu línea de comandos:

pip (version) from (Your Python site-packages Directory)

En caso de que no aparezca, puedes tratar de correrlo con bootstrap por medio del siguiente comando:

  • Windows:
py -m ensurepip --default-pip
  • Mac/Unix:
python3 -m ensurepip --default-pip

Como otra alternativa, puedes descargar el script get-pip.py, usar cd + (Dirección de la carpeta donde está descargado get-pip.py) para dirigirte al directorio donde está get-pip.py y finalmente, ejecutar:

>>> py get-pip.py

o

>>> python3 get-pip.py

Nota: Si alguna vez tienes problemas con paquetes por una versión de pip desactualizada, usa el siguiente comando para actualizarlo:

>>> py -m pip install --upgrade pip (Windows)

>>> python -m pip install --upgrade pip (MacOS/Unix)

Una vez nos aseguramos de que pip está instalado, solo debemos de buscar el paquete que queramos instalar. Para esto, podemos dirigirnos a PyPi (The Python Package Index), el cual es un repositorio con un sin fin de paquetes de Python. Una busqueda de google con 'pypi (Nombre del paquete)', nos bastará para que en el primer resultado tengamos a PyPi, entramos en este y veremos la siguiente imagen:

image.png

Aquí, nos enfocamos en la sección que dice pip install (Nombre del paquete). Esta será la sintaxis que usaremos siempre que queramos instalar un paquete. Para hacer esto, volvemos a nuestra línea de comandos y lo escribimos:

pip install numpy

Así, comenzarán a descargarse los archivos correspondientes al paquete y una vez finalizado, podrás utilizarlo con tan solo escribir import (Nombre del paquete) en un archivo correspondiente.

Para probar esto, digamos que queremos crear una matriz con numpy. Para esto, importamos el módulo y usamos la siguiente instrucción:

from numpy import np

a = np.matrix('1 2; 3 4')
print(a)

>>> matrix([[1, 2],
           [3, 4]])

Así, sabemos que fue posible instalar un módulo con pip.

Nota: Si trabajas con un entorno virtual que usarás en un repositorio de github, debes de instalar las paquetes que vayas a usar de nuevo.

HiveDivider.png

Algunos de los paquetes más populares de Python

Pandas


GeeksForGeeks.png

Shoutout to GeeksforGeeks

Pandas es la elección predilecta de los analistas de datos que trabajan con Python, esto debido a que nos permite trabajar y analizar sets de datos inmensos y elaborar estadísticas sin tener que aprender lenguajes de programación adicionales. Para instalar este, solo tienes que usar:

pip install pandas

Requests


Edureka.jpg

Shoutout to Edureka

Requests es una librería HTTP para Python que nos permite obtener información relevante de sitios web Razón por la que es usada con bastante frecuencia en el Web

Scraping. Si deseas trabajar con proyectos en la web, este paquete es esencial. Para instalarlo:

pip install requests

scikit-learn


Scikit-Learn.png

Shoutout to Scikit-Learn

Otro de los paquetes más populares es scikit-learn, el cual nos proporciona una herramienta gratuita para crear algoritmos de regresión y clasificación que usaremos para crear proyectos de inteligencia artificial. Para instalarlo:

pip install scikit-learn

HiveDivider.png

El aprendizaje de un programador nunca termina. Esto debido a la cantidad de módulos que debe usar para cada proyecto, cada uno requiriendo del entendimiento de su

documentación y su potencial. Una vez que conoces como instalar módulos, estarás un paso más cerca de crear aplicaciones complejas y de gran belleza.

Es por esto, que con la siguiente información podrás instalar módulos con gran facilidad y usarlos en tus programas posteriores.

Dicho esto, concluimos con los módulos, pudiendo ahora empezar con otro tema que es bastante confuso para muchos: Las expresiones regulares. Nos vemos en el siguiente capitulo de Coding Basics.

HiveDivider.png

¡Gracias por tu apoyo y buena suerte!

HiveDivider.png

@jesalmofficial.png



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000