Python Notes
Python Notes
Menu
Glosario
Consejos buenas practicas
Operadores aritméticos
Operadores lógicos
Variable
De uno a otro
Type of Data
Sangria
Texts
String Methods
Ejercicios / practicas
Data Structures
List
Membership Operator
Funciones with list
Tuplas
Sets
Dictionaries y Sets
Dictionaries
Identity operators
Equality vs. Identity: == vs. is
Control Flow
If (conditional)
For (loops)
Range
Building Dictionaries
While (loop)
Break and Continue
Zip
Enumarate
Python 1
List Comprehensions
Functions
Funciones
Variable Scope
Documentation or DocString
Lambda Expressions
Scripting
Errors and Exceptions
Using Files
Exercise
Import
Exercise
Techniques for importing Modules
Sub-Modulos
Bibliotecas de terceros
Ipython (consola interactiva de python)
Exercise
Advanced Topics
Iteradores y funciones generador
Paginas de interés
Glosario
#r —> El resultado es
los elementos que posean el mismo color es porque estan vinculados
Comprenda los mensajes de error comunes que puede recibir y qué hacer con
ellos.
Python 2
A la hora de buscar soluciones a problemas es recomendable empezar con la
palabra python:
No utilizar bucles for ya que son lentos, mejor usar funciones incorporadas o
funciones vectoraiales
Operadores aritméticos
hay mas (+,-,/,%) pero ya se que hacen 😅
** Exponenciación (nota que ^
Operadores lógicos
and
or
not
#Prioridades
not #1
and #2
or #3
Variable
#de esta manera asignamos valores por orden de manera simplifi
x, y, z = 1, 2, 3
De uno a otro
print(int(55.3)) #r 55
print(float(20 + 38)) #r 58.0
variable = 12
Python 3
print(str(12)) #r '12'
#bool (booleano)
Type of Data
print(type("hey")) #r <class "str">
Sangría
Utilizar 4 espacios por nivel del sangría
# Correct:
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Wrong:
# Arguments on first line forbidden when not using vertical
alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
Python 4
# Further indentation required as indentation is not distin
guishable.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
Texts
#Varias comillas dentro de un texto
varible_text = "This is a exception (it\'s)" #con el \ se a
cepta de cierta forma las ''
String Methods
Python 5
#Metodos ejemplos con texto
print("soy un ejemplo".title()) #return texto en capitalize
'Soy Un Ejemplo'
print("soy otro ejemplo".islower()) #return True because al
l is lower
print("alv soy diferente, porque soy yo, si soy yo todo est
a bien".count('soy'))
# return 3 porque hay 3 soy
#con parametros
new_str.split(' ', 3)
['The', 'cow', 'jumped', 'over the moon.']
# 0 1 2 3
#por default el valor de el separador es el espacio
Ejercicios / practicas
Python 6
weekly_sales = int(mon_sales) + int(tues_sales) + int(wed_s
ales) + int(thurs_sales) +
int(fri_sales)
weekly_sales = str(weekly_sales) #convert the type back!!
print("This week's total sales: " + weekly_sales)
Data Structures
List
my_list = ["soy","una", "lista"]
print(my_list[0])
print(my_list[1])
print(my_list[2])
print(my_list)
my_list[3] = "Cambio" #r en la posicion 3 cambia se colocar
a este nuevo valor
#Para acceder al ultimo elemento usamos numero en negativo
print(my_list[-1]) #r lista
list_of_random_things[len(list_of_random_things) - 1]
True #otra manera para llamar el ultimo elemento de una lsi
ta
#Slicing list
months = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October', 'Novembe
r', 'December']
Python 7
n fin
print(first_half) # ['January', 'February', 'March', 'Apri
l', 'May', 'June']
Membership Operator
"this" in "this is a string" #r True
"isa" in "this is a string" #r False
5 not in [1, 2, 3, 4, 6] #r True
5 in [1, 2, 3, 4, 6] #r False
Python 8
print(max(lst)) #r S porque en orden alfabetico la S esta m
as lejos
lsta = [1,34,78,20,14]
print(max(lsta)) #r 78
#SORTED
print(sorted(lsta)) #sorted ordena las lista de forma ascen
dente
#r [1,14,20,34,78]
print(sorted(lsta, reverse = True)) # sorted acepta un segu
ndo parametro que es para invertir el orden (por default es
ta en ascendente)
#r [78,34,20,14,1]
#JOIN
names_countrys = "-.-".join(["RD","US","P","PR","C","CM"])
#join toma como parametro la lista y la devuelve colocandol
e los separadores que elegimos
#r RD-.-US-.-P-.-PR-.-C-.-CM
#Da error si se trabaja con numeros
#APPEND
#se utiliza para agregar contenido al final de una lista
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
#POP
#se utiliza para eliminar contenido al final de una lista
letters.pop('z')
Python 9
#JOIN AND SORTED
names = ["Carol", "Albert", "Ben", "Donna"]
print(" & ".join(sorted(names)))
#r Albert & Ben & Carol & Donna
Tuplas
tupla = ("nueva", "data", "estructure") # las tuplas no son
mutables pero si ordenadas
print(type(tupla)) #r tupla
print("palabra {}".format(tupla[1]))
Sets
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_numbers = set(numbers) # set is a data type for muta
ble unordered collections of unique elements
print(unique_numbers)
Python 10
t
Dictionaries y Sets
Note: if you define a variable with an empty set of curly b
races like this: a = {}, Python will assign an empty dictio
nary to that variable. You can always use set() and dict()
to define empty sets and dictionaries as well.
Dictionaries
diccionario = {'hidrogeno' : 1, 'helium': 2, 'carbon': 6}
print(diccionario.get("helium")) # es recomendable usar get
para obtener valores ya que el programa no se detiene si ha
y una error (e.g. que no aparece un valor)
Python 11
#Compound Data Structures(Estructuras de datos compuestos)
elements = {
"hydrogen": { "number":1,
"weight":1.00794,
"symbol":"H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}
}
print(elements["hydrogen"])#r { "number":1, "weight":1.0079
4, "symbol":"H"}
print(elements["hydrogen"]["symbol"]) #r 'H'
Python 12
Identity operators
is #evaluates if both sides have the same identity
is not #evaluates if both sides have different identities
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == b)
print(a is b)
print(a == c)
Python 13
print(a is c)
#a == b True
#a is b True
#a == c True
#a is c False
Control Flow
If (conditional)
phone_balance = 3
bank_balance = 100
print(phone_balance,bank_balance) #r 3, 100
if phone_balance < 5 :
phone_balance += 10
bank_balance -= 10
print(phone_balance,bank_balance) #r 13,90
#with else
if phone_balance < 5 :
phone_balance += 10
bank_balance -= 10
else:
print("gasta para gastar")
#with elif
Python 14
if phone_balance < 5 :
phone_balance += 10
bank_balance -= 10
elif phone_balance == 5:
print("estas cerca de tu limite")
else:
print("gasta para gastar")
#Indentation
#Some other languages use braces to show where blocks of co
de begin and end. In Python we use indentation to enclose b
locks of code. For example, if statements use indentation t
o tell Python what code is inside and outside of different
clauses.
For (loops)
cities = ["New York City","Chicago","Cienfuego","Otras"]
for city in cities:
print(city.title())
Python 15
factors, and then declare it prime
if i == num -1:
print("{} IS a prime number".format(num))
range
print(list(range(4))) # crea una lista con 4 elementos
Building Dictionaries
#Method 1: using a for loop to create a set of counter
Python 16
dventures','of','huckleberry','fin']
word_counter = {}
word_counter = {}
for word in book_title:
word_counter[word] = word_counter.get(word, 0)
+ 1
cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
"Jason Alexander": "George Costanza",
"Michael Richards": "Cosmo Kramer"
}
for key, value in cast.items():
print("Actor: {} Role: {}".format(key,valu
e))
While (loop)
Python 17
card_dark= [1,2,45,29,11,22,5,66,34,90]
had = []
while sum(had) <= 100:
had.append(card_dark.pop())
print(had)
ZIP
#ZIP
items = ["maceta","collar","lampara","calabaza"]
weights = [10,4,23,9]
print(list(zip(items,weights)))
#Unzip
manifest = [('maceta', 10), ('collar', 4), ('lampara', 23),
('calabaza', 9)]
Python 18
#ZIP in a list count
items = ["maceta","collar","lampara","calabaza"]
for i,item in zip(range(len(items)), items):
print(i,items)
Enumarate
letters = ['a', 'b', 'c', 'd', 'e']
List Comprehensions
#METODO NORMAL
cities = ["Chicago","Buenos Aires","Lodres","Tokyo"]
new_list_cities = []
#LIST COMPREHENSIONS
new_list_cities = [city.title() for city in cities]
#METODO NORMAL
squares = []
for x in range(9):
squares.append(x**2)
print(squares)
#LIST COMPREHENSIONS
#las listas de comprension solo existen en python
squares = [x**2 for x in range(9)]
Python 19
# tambien podemos agregar condicionales
squares = [x**2 for x in range(9) if x % 2 == 0]
#si se desea poner un else el condicional va delante
squares = [x**2 if x % 2 == 0 else x + 3 for x in range
(9)]
#NORMAL
highest_count = 0
most_win_director = []
#LIST COMPREHENSIONS
highest_count = max(win_count_dict.values())
Functions
Funciones
def cylinder_volume(height, radius): #con argumentos
pi = 3.14159
return height * pi * radius ** 2
cylinder_volume(10, 3)
Python 20
print_greeting()
#Los argumentos son esos valores que requerira la funcion p
ara ejecutarse
Variable Scope
#Buena práctica: es mejor definir las variables en el ámbit
o más pequeño en el que se necesitarán. Si bien las funcion
es pueden hacer referencia a variables definidas en un ámbi
to más amplio, rara vez es una buena idea, ya que es posibl
e que no sepa qué variables ha definido si su El programa t
iene muchas variables.
Documentation or DocString
#Documentation is used to make your code easier to understa
nd and use. Functions are especially readable because they
often use documentation strings, or docstrings. Docstrings
are a type of comment used to explain the purpose of a func
tion, and how it should be used. Here's a function for popu
lation density with a docstring.
"""
Ahora mismo no hay nada que explicar
"""
Python 21
"""Calculate the population density of an area.
INPUT:
population: int. The population of that area
land_area: int or float. This function is unit-agnosti
c, if you pass in values in terms
of square km or square miles the function will return a
density in those units.
OUTPUT:
population_density: population / land_area. The populat
ion density of a particular area.
"""
return population / land_area
# Tomar en cuenta:
#1- La documentacion va dentro de la funcion en la primera
linea
# 2- Se puede ver la documentacion con .__doc__
documentacion = population_density.__doc__
Lambda Expressions
#NORMAL
def double(x):
x*2
#LAMBDA
double = lambda x: x*2
double(3)
#Lambda Expressions
#You can use lambda expressions to create anonymous functio
ns. That is, functions that don’t have a name. They are hel
Python 22
pful for creating quick functions that aren’t needed later
in your code. This can be especially useful for higher orde
r functions, or functions that take in other functions as a
rguments.
Scripting
python <nombre_archivo.py>
#Funcion eval
try:
x = int(input("Enter a number"))
Python 23
e
print("\n Attempted Input\n")
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code
try:
print("i'm try")
except ZeroDivisionError as e:
print("ZeroDivisionError ocurred: {}".format(e)) #Podem
os acceder al mensaje de error
Using Files
Python 24
open("archivos.txt","opcion")
#opciones :
# r read solo lectura
#w write solo escritura
# a add(o append no se) agrega contenido al final
# r+ lectura con escritura
# b abre el archivo en modo binario
# end = "" obtien los saltos de linea en los textos
# .strip() elimina el caracter de nueva linea
print(file_data)
files = []
for i in range(1000):
files.append(open("some_file.txt","r"))
print(i) #REMEMBER CLOSE YOUR FILES
#ESCRIBIR DOCUMENTOS
archivo = open("prueba.txt", "w")#si el archivo ya existe y
lo llamamos con write el contenido se borra
archivo.write('Hey, i get it')
archivo.close()
#Es importante cerrar los archivos por eso para evitar olvi
Python 25
darlo con la palabra clave with y as podemos indicar a una
varible que se cierre cuando termine
#READLINE
#solo imprime una linea del texto(para llegar al final
se debe ejecutar varias veces) readline divine las lineas c
on \n
f.readline()
#UNA LINEA A LA VEZ part 2 CON BUCLE FOR PARA REDUCIR ESPA
CIO EN MEMORIA
print("\n *** Una linea a la vez CON bucle FOR ***\n")
with open("HoHey.txt","r") as clumines:
for line in clumines:
print(line,end='')
Python 26
Exercise
Escribe una funcion llamada create_cast_list que tome como
parametro un input que retorne una lista de nombres de acto
res
al archivo flying_circus_cast.txt
#Mi Solucion
def create_cast_list(filename):
cast_list = []
with open(filename,"r") as actores:
for line in actores:
line.strip()
#line.split("")
cast_list.append(line.split(","))
#use with to open the file filename
#use the for loop syntax to process each line
#and add the actor name to cast_list
return cast_list
cast_list = create_cast_list("Flying_circus_cast.txt")
for actor in cast_list:
print(actor[0])
# return cast_list
Python 27
# cast_list = create_cast_list('flying_circus_cast.txt')
# for actor in cast_list:
# print(actor)
Import
#Llama un archivo externo
import other_file
Python 28
import <name>
#ejemplo
import math
factorial = math.factorial(8)
print(math.exp(3)) #potencia de 3
suma(2,4)
Exercise
# Escriba una función llamada generate_passwordque seleccio
ne tres palabras al azar de la lista de palabras word_listy
las concatene en una sola cadena. Su función no debe acepta
r ningún argumento y debe hacer referencia a la variable gl
obal word_listpara generar la contraseña.
Python 29
if 3 < len(word) < 8:
word_list.append(word)
return cadena
#Which Module?
#1- datetime
import datetime as dt
t = dt.time(1,2,3) #los valores que le pasamos
print("tiempo: ")
print("Hora: ", t.hour) #r 1 porque ese fue el valor que le
pasamos
print("Minutos: ", t.minute)#r ...
print("Segundos: ", t.second) #r ...
Python 30
Techniques for importing Modules
# 1- Para importar una función o clase individual desde un
módulo:
from module_name import object_name
Sub-Modulos
# Para gestionar mejor el código, los módulos de la bibliot
eca estándar de Python se dividen en submódulos que se encu
entran dentro de un paquete. Un paquete es simplemente un m
ódulo que contiene submódulos. Un submódulo se especifica c
on la notación habitual de puntos.
Python 31
from module import module_name as mn
val = mn.algo()
Bibliotecas de terceros
https://learn.udacity.com/courses/ud1110/lessons/a0dff550-b87f-4a48-ba5e-c74c92625a11/concepts/79
d07b2a-d5ea-498d-8e84-91de2f5c1ff3
Exercise
# Pregunta: Cree una función que abra el archivo flowers.tx
t, lea cada línea y lo guarde como un diccionario. La funci
ón principal (separada) debe tomar la entrada del usuario
(nombre y apellido del usuario) y analizar la entrada del u
suario para identificar la primera letra del nombre. Luego
debería usarlo para imprimir el nombre de la flor con la mi
sma primera letra (del diccionario creado en la primera fun
ción).
Advanced Topics
Iteradores y funciones generadoras
Python 32
#Un iterador es un objeto que representa un flujo de datos.
Esto es diferente de una lista , que también es iterable, p
ero no es un iterador porque no es un flujo de datos.
#ITERABLES
#listas,tuplas,sets,diccionarios,cadenas.
#ITERADORES
#zip, enumerate,range,filter,map,iter,reversed >> todos con
() al final
#EJEMPLO
a = iter(range(10)) # >> se llaman con next(a) y los pasa
Python 33
uno por uno
b = list(range(10)) # >> se reccores en un bucle
# for i in b:
#print(i)
Python 34
Paginas de interés
https://docs.python.org/3/reference/lexical_analysis.html#keywords
https://peps.python.org/pep-0008/
https://docs.python.org/3/tutorial/errors.html
https://docs.python.org/3/reference/lexical_analysis.html#keywords
https://docs.python.org/3/library/functions.html#open
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
https://pymotw.com/3/
📱 Python CRUD
Python 35
https://youtu.be/O1C9GvlcpNI
https://docs.python.org/3/library/turtle.html
https://docs.python.org/3/library/turtle.html#turtle.position
Python 36