Diferències
Ací es mostren les diferències entre la revisió seleccionada i la versió actual de la pàgina.
Següent revisió | Revisió prèvia | ||
info:cursos:python:codigofacilito [30/08/2021 03:57] – creat mate | info:cursos:python:codigofacilito [10/06/2022 02:28] (actual) – [curso python (código facilito)] mate | ||
---|---|---|---|
Línia 1: | Línia 1: | ||
= curso python (código facilito) | = curso python (código facilito) | ||
+ | {{tag> | ||
+ | [[https:// | ||
== que es python | == que es python | ||
* reminiscencias perl, pero más natual (pseudocódigo) | * reminiscencias perl, pero más natual (pseudocódigo) | ||
Línia 75: | Línia 77: | ||
bNot = not True | bNot = not True | ||
</ | </ | ||
+ | == listas, tuplas, diccionarios | ||
+ | === listas | ||
+ | * ordenada | ||
+ | * ≡ array, vectores | ||
+ | * <code python>l = [ 2, " | ||
+ | print l | ||
+ | print l[1] | ||
+ | print l[3][0] | ||
+ | l[1] = False | ||
+ | print l | ||
+ | l2 = l[0:3] # desde elemento 0, 3 elementos | ||
+ | print l2 | ||
+ | l2 = l[1::2] # desde elemento 1, todos los elementos, uno si, uno no | ||
+ | print l2 | ||
+ | l[0:2] = [4,3] # sustituye | ||
+ | print l | ||
+ | l[0:2] = [5] # sustituye y elimina un elemento | ||
+ | print l | ||
+ | |||
+ | print l[-1] # ultimo elemento | ||
+ | </ | ||
+ | === tuplas | ||
+ | * sin corchetes (como las listas) | ||
+ | * elementos separados por coma (y opcionalmente paréntesis) | ||
+ | * acceso a los elementos como en las listas | ||
+ | * las tuplas no se pueden modificar o añadir nuevos elementos | ||
+ | * <code python>t = 1, | ||
+ | print t | ||
+ | |||
+ | t2 = (2, | ||
+ | print type(t2) | ||
+ | |||
+ | print t2[2] | ||
+ | |||
+ | t2[0] = 4 # error | ||
+ | </ | ||
+ | === diccionarios | ||
+ | * clave, valor' | ||
+ | * matrices asociativas | ||
+ | * no permite tener como valores listas o diccionarios | ||
+ | * se pueden cambiar los valores pero no las claves | ||
+ | * no permite slice (nomenclatura selección elementos [::]) | ||
+ | * <code python>d = {' | ||
+ | print d | ||
+ | |||
+ | print d[' | ||
+ | print d[3] | ||
+ | |||
+ | d[3] = False | ||
+ | print d | ||
+ | |||
+ | d[' | ||
+ | print d | ||
+ | |||
+ | del d[' | ||
+ | print d | ||
+ | </ | ||
+ | |||
+ | == operadores relacionales | ||
+ | * números, cadenas, listas, tuplas | ||
+ | * en cadenas los operadores del estilo **>** no son exactos | ||
+ | <code python> | ||
+ | a = 1 | ||
+ | b = 1 | ||
+ | c = 2 | ||
+ | |||
+ | r = a == c # False | ||
+ | r = a == b # True | ||
+ | r = a != c # False | ||
+ | r = a < c # True | ||
+ | r = a > c # False | ||
+ | r = a >= c # False | ||
+ | r = a <= c # True | ||
+ | </ | ||
+ | == sentencias condicionales | ||
+ | <code python> | ||
+ | #encoding: utf-8 | ||
+ | edad = 8 | ||
+ | m_edad = 18 | ||
+ | |||
+ | if edad >= m_edad: | ||
+ | print " | ||
+ | if True: | ||
+ | print "mayor de edad" | ||
+ | else: | ||
+ | print "no se ejecuta nunca" | ||
+ | else: | ||
+ | print " | ||
+ | |||
+ | print "fuera del if" | ||
+ | |||
+ | if edad >= 0 and edad < 18: | ||
+ | print "menor de edad ñ" | ||
+ | elif edad >= 18 and edad < 28: | ||
+ | print " | ||
+ | elif edad >=27 and edad < 65: | ||
+ | print " | ||
+ | else: | ||
+ | print " | ||
+ | </ | ||
+ | == bucles | ||
+ | * while< | ||
+ | while contador < 10: | ||
+ | contador = contador + 1 | ||
+ | if contador == 4: | ||
+ | continue # se salta el print en el 4 | ||
+ | elif contador == 8: | ||
+ | break # rompe el while en el 8 | ||
+ | print "hola " + str(contador) | ||
+ | </ | ||
+ | * for<code python> | ||
+ | |||
+ | for mi_item in lista: | ||
+ | print mi_item | ||
+ | | ||
+ | for letra in " | ||
+ | print letra | ||
+ | </ | ||
+ | == funciones | ||
+ | <code python> | ||
+ | def miFuncion(num1, | ||
+ | print num1+num2 | ||
+ | |||
+ | miFuncion(1, | ||
+ | miFuncion(1) # 1 | ||
+ | |||
+ | |||
+ | def miFuncion2(cad, | ||
+ | # *algomas es una tupla | ||
+ | print cad + algomas[0] + algomas[1] | ||
+ | for palabra in algomas: | ||
+ | print palabra | ||
+ | |||
+ | miFuncion2(' | ||
+ | |||
+ | def miFuncion3(cad, | ||
+ | # **algomas es un diccionario | ||
+ | print cad, | ||
+ | |||
+ | miFuncion3(' | ||
+ | |||
+ | def miFuncion4(num1, | ||
+ | return num1+num2 | ||
+ | |||
+ | resultado = miFuncion4(3, | ||
+ | print resultado | ||
+ | </ | ||
+ | == cadenas y métodos | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * <code python> | ||
+ | #encoding: utf-8 | ||
+ | |||
+ | s = "Hola Mundo" | ||
+ | |||
+ | print len(s) | ||
+ | |||
+ | print s.count(' | ||
+ | print s.count(' | ||
+ | print s.count(' | ||
+ | |||
+ | print s.upper() | ||
+ | print s.lower() | ||
+ | |||
+ | print s.replace(' | ||
+ | print s.replace(' | ||
+ | |||
+ | print s.split(' | ||
+ | print s.split() | ||
+ | print s.split(' | ||
+ | print s.split(' | ||
+ | |||
+ | print s.find(' | ||
+ | print s.rfind(' | ||
+ | |||
+ | t = (" | ||
+ | t2 = ";" | ||
+ | t3 = "" | ||
+ | print t2.join(t) | ||
+ | print t3.join(t) | ||
+ | </ | ||
+ | |||
+ | == listas y métodos | ||
+ | * ''< | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * <code python> | ||
+ | lista = [1," | ||
+ | |||
+ | buscar = 1 | ||
+ | print buscar in lista # True | ||
+ | |||
+ | print lista.index(buscar) # 0 | ||
+ | if buscar in lista: | ||
+ | print lista.index(buscar) | ||
+ | else: | ||
+ | print "No existe el elemento" | ||
+ | |||
+ | lista.append(' | ||
+ | |||
+ | print lista.count(" | ||
+ | |||
+ | lista.insert(3," | ||
+ | print lista | ||
+ | print lista.count(" | ||
+ | |||
+ | tupla = (1,2,3,4) | ||
+ | lista.extend(tupla) | ||
+ | print lista | ||
+ | |||
+ | lista.pop(1) | ||
+ | print lista | ||
+ | |||
+ | lista.remove(" | ||
+ | print lista | ||
+ | |||
+ | lista.reverse() | ||
+ | print lista | ||
+ | </ | ||
+ | == diccionarios y métodos | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | * '' | ||
+ | |||
+ | == funciones de orden superior | ||
+ | * enviar funciones como variables y ejecutarla al usar **()** | ||
+ | * <code python> | ||
+ | def prueba(f): | ||
+ | return f() | ||
+ | |||
+ | def porEnviar(): | ||
+ | return (2+2) | ||
+ | |||
+ | print prueba(porEnviar) # sin parentesis en porEnviar | ||
+ | |||
+ | |||
+ | def seleccion(operacion): | ||
+ | def suma(n,m): | ||
+ | return n+m | ||
+ | def multi(n,m): | ||
+ | return n*m | ||
+ | |||
+ | if operacion == " | ||
+ | return suma | ||
+ | elif operacion == " | ||
+ | return multi | ||
+ | |||
+ | fGuardada = seleccion(" | ||
+ | print fGuardada(3, | ||
+ | fGuardada = seleccion(" | ||
+ | print fGuardada(3, | ||
+ | </ | ||
+ | |||
+ | == función MAP | ||
+ | * iteraciones de orden superior | ||
+ | * <code python> | ||
+ | def operador(n, | ||
+ | if n==None or m==None: | ||
+ | return None | ||
+ | |||
+ | return n+m | ||
+ | |||
+ | l1 = [1,2,3,4] | ||
+ | t1 = (9,8,7,6) | ||
+ | t2 = (5,4,3) | ||
+ | s1 = " | ||
+ | s2 = " | ||
+ | |||
+ | lr = map(operador, | ||
+ | |||
+ | print lr | ||
+ | |||
+ | print map(operador, | ||
+ | |||
+ | print map(operador, | ||
+ | </ | ||
+ | |||
+ | == función FILTER | ||
+ | * evalua a través de una función todos los elementos de una lista y retorna aquellos que son True | ||
+ | * <code python> | ||
+ | def filtro(elem): | ||
+ | return (elem > 0) | ||
+ | |||
+ | l = [1, | ||
+ | |||
+ | print filter(filtro, | ||
+ | </ | ||
+ | |||
+ | == función REDUCE | ||
+ | * reducir una secuencia a un elemento | ||
+ | * coge pares de elementos, el resultado de la anterior iteracción y el siguiente elemento. | ||
+ | * Para **(' | ||
+ | * <code python> | ||
+ | s = (' | ||
+ | |||
+ | def concatenar(a, | ||
+ | return a+b | ||
+ | |||
+ | print reduce(concatenar, | ||
+ | </ | ||
+ | |||
+ | == funciones Lambda | ||
+ | * función anónima | ||
+ | * siempre retorna algo | ||
+ | * sólo 1 línea | ||
+ | * uso en map, filter, reduce | ||
+ | * reduce el número de ciclos de computación usados. | ||
+ | * <code python> | ||
+ | li = [1,-2,1,-4] | ||
+ | lo = [5,3,6,7] | ||
+ | s = "Hola Mundo" | ||
+ | lf = lambda n,m: n+m | ||
+ | |||
+ | print map(lambda n,m: n+m, li,lo) | ||
+ | print filter(lambda n: n==' | ||
+ | print reduce (lambda n,m: n+m, lo) | ||
+ | |||
+ | print reduce (lf,lo) | ||
+ | print lf(3,4) | ||
+ | </ | ||
+ | |||
+ | == comprensión de listas | ||
+ | * reemplaza en python 3 a map, filter | ||
+ | * la operación a realizar se pone primero, las condiciones o recorridos detrás ¿?¿?¿? | ||
+ | * <code python> | ||
+ | l = [1,2,-3,4] | ||
+ | l2 = [" | ||
+ | |||
+ | print [num for num in l if num>0] | ||
+ | print [c * num for c in s | ||
+ | for num in l2] | ||
+ | print [c * num for c in s | ||
+ | for num in l2 | ||
+ | if num > 0] | ||
+ | </ | ||
+ | |||
+ | == Generadores | ||
+ | * equivalente a comprensión de listas | ||
+ | * recorre la lista, no devuelve una lista, si no los elementos | ||
+ | * <code python> | ||
+ | l = [1,2,-3,4] | ||
+ | l2 = [" | ||
+ | |||
+ | print [num for num in l if num>0] | ||
+ | print [c * num for c in s | ||
+ | for num in l2] | ||
+ | r1 = (c * num for c in s | ||
+ | for num in l2 | ||
+ | if num > 0) | ||
+ | print r1.next() | ||
+ | print r1.next() | ||
+ | |||
+ | for letra in r1: | ||
+ | print letra | ||
+ | | ||
+ | def factorial(n): | ||
+ | i = 1 | ||
+ | while n > 1: | ||
+ | i = n*i | ||
+ | yield i # ? objeto generador | ||
+ | n -= 1 | ||
+ | |||
+ | for e in factorial(5): | ||
+ | print e | ||
+ | </ | ||
+ | | ||
+ | == Decoradores | ||
+ | * función que recibe una función y devuelve una función decorada | ||
+ | * es decir, podemos añadir cosas antes (y supongo que después) de la ejecución de la función pasada por parámetro | ||
+ | * <code python> | ||
+ | def decorador(funcion): | ||
+ | def funcionDecorada(*args, | ||
+ | print " | ||
+ | funcion(*args, | ||
+ | | ||
+ | return funcionDecorada | ||
+ | |||
+ | def resta(n,m): | ||
+ | print n-m | ||
+ | | ||
+ | #decorando | ||
+ | print decorador(resta)(5, | ||
+ | decorada = decorador(resta) | ||
+ | decorada(6, | ||
+ | |||
+ | @decorador | ||
+ | def multi(n,m): | ||
+ | print n*m | ||
+ | |||
+ | multi(2,4) | ||
+ | </ | ||
+ | * se podrían anidar varios decoradores, | ||
+ | <code python> | ||
+ | loggeado = False | ||
+ | usuario = " | ||
+ | |||
+ | def admin(f): | ||
+ | def comprobar(*args, | ||
+ | if loggeado: | ||
+ | f(*args, | ||
+ | else: | ||
+ | print "no tiene permisos para ejecutar", | ||
+ | return comprobar | ||
+ | | ||
+ | @admin | ||
+ | def resta(n,m): | ||
+ | print n-m | ||
+ | </ |