DEV Community

Albert Coronado
Albert Coronado

Posted on • Edited on

5

Python Crash Course, de 0 a 100 con Python

Hoy os dejo todo el código del videotutorial de Python en esta comunidad. Así que si me queréis seguir, comentar, darle a like, etc. me haréis un favor(Tanto aquí como en Youtube, Linkedin, etc.)(Sí, soy mu pesao).

Estructuras de datos

Lo primero que hemos hecho ha sido trabajar con variables y estructuras de datos. Python tiene los típicos tipos básicos Integer, Float, Boolean y Strings pero donde realmente destaca es por su soporte nativo a listas, tuplas y diccionarios:

mylist = [ "java", "go", "php", "python", "nodejs" ]

print( "" )
print( "Listas" )
print( "===============================================================" )
print( "mylist: %s" % mylist )
print( "Intervalo 1 a 4: %s" % mylist[1:4] )
print( "Intervalo 1 al final: %s" % mylist[1:] )
print( "Intervalo posición 2 empezando por atrás al final: %s" % mylist[-2:] )

mylist.append( "rust" )
mylist.remove( "php" )
mylist.append( 4 )

print( "Añado 'rust', quito 'php', añado 4: %s" %mylist )

# Las tuplas son como las listas pero inmutables. Su principal ventaja es el poco espacio que ocupan en memória

mytupla = ( "java", "go", "php", "python", "nodejs" )

print( "" )
print( "Tuplas" )
print( "===============================================================" )
print( "mytupla: {0}".format(mytupla) )

# Diccionarios

print( "" )
print( "Diccionarios" )
print( "===============================================================" )
mydict = { "hello": "world", "mylist": mylist, "mytupla": mytupla }

print( "mydict: {0}".format(mydict) )
print( "Valor de 'hello': {0}({1})".format(mydict['hello'], type(mydict['hello'])) )
Enter fullscreen mode Exit fullscreen mode

Estructuras de control: condicionales y bucles

Después de ver las estructuras de datos hemos visto como crear condicionales y bucles:

# bucles
print( "" )
print( "Bucles" )
print( "===============================================================" )

for x in mydict:
    print( "keys: {0}".format(x) )

for x, y in mydict.items():
    print( "{0} = {1}".format(x, y) )    

for x in mydict.values():
    print( "values: {0}".format(x) )    

for x in range(1,5):
    print( "Rango: {0}".format(x) )    

count = 0
while count < 5:
    print( "Condición: {0}".format(count) )
    count += 1

# condicionales
print( "" )
print( "Condicionales" )
print( "===============================================================" )

for x in mytupla:
    print( "Procesando: {0}".format(x) )

    if x == "go":
        print( " Es Go!!!!!!!!!!!!!!!!!!!!!!!!!" )
    else:
        print( " No es go" )
Enter fullscreen mode Exit fullscreen mode

Estructuración del código: Funciones, lambdas y classes

# Funciones y lambdas
def my_function( myparam ):
    print( "El parámetro de mi función es: {0}".format( myparam ) )

    return "ok"

print( "" )
print( "funciones" )
print( "===============================================================" )
my_function( mylist )

print( "" )
print( "lambdas" )
print( "===============================================================" )
mylamda = lambda x,y:x+y
print( "El resultado de 2+5={0}".format( mylamda(2,5) ) )

# Classes
print( "" )
print( "Condicionales" )
print( "===============================================================" )

class Vehiculo:
    def __init__(self, ruedas):
        self.ruedas = ruedas

coche = Vehiculo( 4 )
print( coche )
print( vars(coche) )
Enter fullscreen mode Exit fullscreen mode

Módulos

Los módulos nos permiten organizar el código y para ilustrar su funcionamiento hemos creado un fichero llamado 'mymodule.py' con una variable y una función:

mymodulevar = { "customer_id":12, "total": 15000 }

def mymodulefunc():
    print( "Module func" )
Enter fullscreen mode Exit fullscreen mode

Después hemos creado un segundo fichero en python y hemos hecho uso de sus recursos:

import mymodule

mymodule.mymodulefunc()

x = dir(mymodule)

print(x)
Enter fullscreen mode Exit fullscreen mode

Bonus Track: Script Ejecutable

Finalmente, hemos visto como podíamos crear un script ejecutable con python simplemente creando un archivo y añadiendo en su cabecera #!/usr/bin/env python3 y dándole permisos de ejecución con chmod +x myfichero.

También hemos usado el módulo 'argparse' que nos ofrece el API de Python para parsear argumentos. El código del script es el siguiente:

#!/usr/bin/env python3
import argparse

parser = argparse.ArgumentParser(description="PaaS deployment tool.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--repository', required=True, help="Gitlab repository URL.") 
parser.add_argument('-e', '--environment', choices=["dev","pre", "pro"], default="dev", required=False, help="Environment.") 
parser.add_argument('action', nargs="?", choices=["deploy"], default="deploy", help="Openshift project name.") 

args = vars( parser.parse_args() )

print( "" )
print( "Argumentos:" )
print( "  %s" % args )
print( "" )
Enter fullscreen mode Exit fullscreen mode

¡Esto es todo amigos! Espero que lo disfrutéis.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more