0% found this document useful (0 votes)
40 views36 pages

Python Notes

This document provides an overview of the Python programming language. It covers fundamental Python concepts like data types, operators, control flow, functions, modules and libraries. Specific topics discussed include variables, strings, lists, dictionaries, conditionals, loops, functions, classes, errors and exceptions, files and modules. The document also includes code examples and exercises to demonstrate various features of the Python language.

Uploaded by

soribel santos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views36 pages

Python Notes

This document provides an overview of the Python programming language. It covers fundamental Python concepts like data types, operators, control flow, functions, modules and libraries. Specific topics discussed include variables, strings, lists, dictionaries, conditionals, loops, functions, classes, errors and exceptions, files and modules. The document also includes code examples and exercises to demonstrate various features of the Python language.

Uploaded by

soribel santos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

Python

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

Consejos buenas practicas


Aquí hay algunos consejos para una depuración exitosa que discutiremos con más
detalle a continuación:

Comprenda los mensajes de error comunes que puede recibir y qué hacer con
ellos.

Busque su mensaje de error utilizando la comunidad web.

Utilice declaraciones de impresión.

Python 2
A la hora de buscar soluciones a problemas es recomendable empezar con la
palabra python:

python valueError : local variables (parte del mensaje de error)

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 ^

no hace esta operación, como habrás visto en otros idiomas)

// Divide y redondea hacia abajo al entero más cercano

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

print(type(10)) #r <class "int">

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)

# Add 4 spaces (an extra level of indentation) to distingui


sh arguments from the rest.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)

# Hanging indents should add a level.


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

#Operador * con palabras


word = "Mine"
print(word*5) #r MineMineMineMineMine

#Longitud del texto


var_text = len("Udacity")
print(var_text) #r 7

with backslash escaping: ford_quote = 'Whether you think yo


u can, or you think you can\'t--you\'re right.'

with double quotes: ford_quote = "Whether you think you ca


n, or you think you can't--you're right."

salto = "texto con salto de\n lineaaaaa,\n a no me cai"


#"texto con salto de
# lineaaaaa,
# a no me cai"

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

One important string method: format()


#Example
print("Mohammed has {} balloons".format(27)) #return Mohamm
ed has 27 balloons
return (f"{self.usted} {self.es} {self.species}) #r hacev l
o mismo que format per corto

#Metodo .split acepta dos valores pero tambien se puede dej


ar vacio, el primero es que elemento sera el separador y el
segundo parametro decide en cuantas partes dividir un texto
new_str = "The cow jumped over the moon."
new_str.split() #return ['The', 'cow', 'jumped', 'over', 't
he', 'moon.']

#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']

q3 = months[6:9] #el primero se incluye pero el ultimo no


print(q3) #r [ 'July', 'August', 'September']
# 6 7 8
9

first_half = months[:6] # de este modo solo se especifica u

Python 7
n fin
print(first_half) # ['January', 'February', 'March', 'Apri
l', 'May', 'June']

second_half = months[6:] # de este modo solo se especifica


el comienzo
print(second_half) # ['July', 'August', 'September', 'Octob
er', 'November', 'December']

#El slicing tambien se aplica a textos,asi como funciones/m


etodos de texto en listas
greeting = "Hello there"
print(len(greeting)) # 11
print(len(months)) # 12

print(greeting[6:9], months[6:9]) #r ''the' [ 'July', 'Augu


st', 'September']

#Ejercicio metedo pajoncio


https://youtu.be/865KYhK4LaM

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

Funciones with list


#MAX AND MIN

#len es para el tamaño


# Max da el valor maximo entre una lsita con valores del mi
smo tipo
lst = ["Soy", "A", "El aventurero"] #no evalua longitud sin
o su posicion en el alfabeto

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

lsst = [1,34,78] #min hace lo contrario a max


print(min(lsst)) #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

new_str = "\n".join(["fore", "aft", "starboard", "port"])


print(new_str)

#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]))

# para declarar tuplas es opcional poner parentesis


tuplas = 10,20,30
le,wi,he = tuplas
print("The dimensions are {} x {} x {}".format(le,wi,he))

#POP AND ADD


fruit = {"avocado","banana","apple","orange","strawberry"}
print(fruit)
fruit.add("Watermelon")
print(fruit.pop())

#LGreat job, you understand the properties of a tuple! A tu


ple is an immutable, ordered data structure that can be ind
exed and sliced like a list. Tuples are defined by listing
a sequence of elements separated by commas, optionally cont
ained within parentheses: ().

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)

set_example = {element1, element2, element3} #este es un se

Python 10
t

#cuando agregamos elementos en una lista o borramos estas


se borran de forma aleatoria y se agregan de forma desorden
ada.

#A set is a mutable data structure - you can modify the ele


ments in a set with methods like add and pop. A set is an u
nordered data structure, so you can't index and slice eleme
nts like a list; there is no sequence of positions to index
with!

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)

diccionario["lithium"] = 3 #de esta forma es posible agrema


r mas contenido al diccionario

#get se utiliza para obtener los valores de las key words e


n los diccionarios

#si llamamos un valor que no esta devolvera None pero podem


os especificar su valor por default
diccionario.get("carbonato","No hay de esa wea!")

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'

oxygen = {"number":8,"weight":15.999,"symbol":"O"} # creat


e a new oxygen dictionary
elements["oxygen"] = oxygen # assign 'oxygen' as a key to
the elements dictionary
print('elements = ', elements)

#asi es posible agregar indirectamente valores


elements['hydrogen']['is_noble_gas'] = False
elements['helium']['is_noble_gas'] = True

#A dictionary is a mutable, unordered data structure that c


ontains mappings of keys to values. Because these keys are
used to index values, they must be unique and immutable. Fo
r example, a string or tuple can be used as the key of a di
ctionary, but if you try to use a list as a key of a dictio
nary, you will get an error.

Python 12
Identity operators
is #evaluates if both sides have the same identity
is not #evaluates if both sides have different identities

print(n is None) #r True


print(n is not None) #r False

print("carbon" in diccionario) #r True


print(diccionario.get("Yodo") #r en caso de no exister el r
esultado seria none

Equality vs. Identity: == vs. is

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

#That's correct! List a and list b are equal and identical.


List c is equal to a (and b for that matter) since they hav
e the same contents. But a and c (and b for that matter, ag
ain) point to two different objects, i.e., they aren't iden
tical objects. That is the difference between checking for
equality vs. identity.

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

check_prime = [26, 39, 51, 53, 57, 79, 85]

# iterate through the check_prime list


for num in check_prime:

# search for factors, iterating through numbers ranging fro


m 2 to the number itself
for i in range(2, num):

# number is not prime if modulo is 0


if (num % i) == 0:
print("{} is NOT a prime number, because {} is
a factor of {}".format(num, i, num))
break

# otherwise keep checking until we've searched all possible

Python 15
factors, and then declare it prime
if i == num -1:
print("{} IS a prime number".format(num))

#for city in cities:


# var condition elemento que se recorre

#An iterable is an object that can return one of its elemen


ts at a time. This can include sequence types, such as stri
ngs, lists, and tuples, as well as non-sequence types, such
as dictionaries and files.

range
print(list(range(4))) # crea una lista con 4 elementos

print(list(range(2,6))) #crea una lista que empieza en 2 y


termina en 5 porque no incluye el ultimo

print(list(range(1,10,2))) #crea una lista que empieza en 1


y va de dos en dos hasta 10 (no lo incluye)

range(start=0, stop, step=1)

print(list(range(0,-90))) #cuando das un valor negativo dev


uelve una lista vacia

#range() is a built-in function used to create an iterable


sequence of numbers. You will frequently use range() with a
for loop to repeat an action a certain number of times.

Building Dictionaries
#Method 1: using a for loop to create a set of counter

book_title = ['great', 'expectations','the', 'adventures',


'of', 'sherlock','holmes','the','great','gasby','hamlet','a

Python 16
dventures','of','huckleberry','fin']

word_counter = {}

for word in book_title:


if word not in word_counter:
word_counter[word] = 1
else:
word_counter[word] += 1

#Method 2: using the get method

book_title = ['great', 'expectations','the', 'adventures',


'of', 'sherlock','holmes','the','great','gasby','hamlet','a
dventures','of','huckleberry','fin']

word_counter = {}
for word in book_title:
word_counter[word] = word_counter.get(word, 0)
+ 1

#Recorrer diccionarios con un loop for devuelve solo las ke


ys (palabras clave) para obtener las keys y sus valores deb
emos:

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)

#los bulces deben incluir


# 1-Condicion para salir del bucle
# 2- Comprobar si se cumple la condicion
# 3- El cuerpo del ciclo debe cambiar el valor de las varia
bles de condicion

Break and Continue


break #terminates a loop
continue #skips one iteration of a loop

ZIP
#ZIP
items = ["maceta","collar","lampara","calabaza"]
weights = [10,4,23,9]
print(list(zip(items,weights)))

#ZIP with FOR LOOP


for item, weight in zip(items,weights):
print(item[0]), weight[1]

#Unzip
manifest = [('maceta', 10), ('collar', 4), ('lampara', 23),
('calabaza', 9)]

items, weights = zip(*manifest)


print(items)
print(weights)

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

for i, letter in enumerate(letters)


print(i, letter)

List Comprehensions
#METODO NORMAL
cities = ["Chicago","Buenos Aires","Lodres","Tokyo"]

new_list_cities = []

for city in cities:


new_list_cities.append(city.title())
print(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 = []

for key, value in win_count_dict.items():


if value > highest_count:
highest_count = value
most_win_director.clear()
most_win_director.append(key)
elif value == highest_count:
most_win_director.append(key)
else:
continue

#LIST COMPREHENSIONS
highest_count = max(win_count_dict.values())

most_win_director = [key for key, value in win_count_dict.i


tems() if value == highest_count]

Functions
Funciones
def cylinder_volume(height, radius): #con argumentos
pi = 3.14159
return height * pi * radius ** 2
cylinder_volume(10, 3)

def print_greeting(): #sin argumentos


print("Holaa a todos :)")

Python 20
print_greeting()
#Los argumentos son esos valores que requerira la funcion p
ara ejecutarse

def cylinder_volume(height, radius = 5): #con default argum


ent
pi = 3.14159
return height * pi * radius ** 2
cylinder_volume(10)

# Es posibel pasar argumentos by name and by position


cylinder_volume(10, 7) # pass in arguments by position
cylinder_volume(height=10, radius=7) # pass in arguments b
y name

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

def population_density(population, land_area):

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)

double = lambda x, y: x*y #varios argumentos

#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

x = eval(input("Enter an expression: "))


print(x)
#eval es una funcion que permite al usuario ingresar expres
iones

#La función eval() evalúa un código JavaScript representado


como una cadena de caracteres (string), sin referenciar a u
n objeto en particular.

#Para salir de la consola de python se puede usar exit()

Errors and Exceptions

#try intenta realizar lo que le piden, si genera una excepc


ion pasa al except

try:
x = int(input("Enter a number"))

except: #los except puede atrapar un tipo de error en espec


ifico (except ValueError:)
print("\n That's not a valid number\n")

finally: #este se ejecuta al final del try cuando se cimpl

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

#si no hay una excepcion especifica podemos hacer esto


try:
#some code
except Exception as e:
#some code
print("Exception ocurred: {}".format(e))

#Los errores en python no permitan que el programa sea comp


ilado, un ejemplo de estos errores son los de sintaxis.
# Las excepciones son errores "logicos" por que a pesar te
ner la sintaxis correcta puede prodrucir un error cuando al
go no concuerda
# ejemplo(ValueError, TypeError... etc)

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

#Open files just for reading


f = open("/my_path/my_file.txt", "r") #el segundo parametro
es opcional, ya que le especifamos a python como queremos q
ue habra el archivo
file_data = f.read()
f.close() #importante siempre cerrar lo que abrimos

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

archivo = open("prueba.txt", "a") #con "a" agregamos sin bo


rrar contenido
archivo.write('Hey, no lo borre')
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

#PALABRAS CLAVE PARA ACORTAR CODIGO Y CERRAR AUTOMATICAMENT


E
with open("prueba.txt","r") as f:
lectura = prueba.read()

#la read palabra clave, acepta enteros para especificar cua


ntos caracteres leer
with open("caramelo.txt","r") as song:
print(song.read(2)) #r We
print(song.read(8)) #r 're the
print(song.read()) #r knights of the round tabl
e We dance whenever we're able

#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


print("\n *** Una linea a la vez ***\n")
with open("HoHey.txt","r") as cancion:
print(cancion.readline())
print(cancion.readline())
print(cancion.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

Escriba una función llamada create_cast_listque tome un nom


bre de archivo como entrada y devuelva una lista de nombres
de actores.

#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])

#La Del Curso


# def create_cast_list(filename):
# cast_list = []
# with open(filename) as f:
# for line in f:
# name = line.split(",")[0]
# cast_list.append(name)

# 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

#Asi se llama para ejecutar


num = other_file.<variable>
#Si es una funcion
num = other_file.<variable>(argumento,arg,...)

#Importar archivos externos con apodos


import useful_function as uf
num = uf.<variable>
#Si es una funcion
num = uf.<variable>(argumento,arg,...)

#Podemos llamar una parte en especifico del codigo para no


tener que llamar o ejecutar codigo innecesario

#Las lineas de codigo que no deseemos ejecutar deberan ir e


ncerradas aqui:
if __name__ == "__main__"

#Usando un bloque principal Para evitar ejecutar declaracio


nes ejecutables en una secuencia de comandos cuando se impo
rta como un módulo en otra secuencia de comandos, incluya e
stas líneas en un if __name__ == "__main__"bloque. O altern
ativamente, inclúyalos en una función llamada main() y llam
e a esto en el if mainbloque.

#Importar modulos externas

Python 28
import <name>

#ejemplo
import math

factorial = math.factorial(8)

print(factorial) #factorial de 8! = 1*2*3*4*5*6*7*8

print(math.exp(3)) #potencia de 3

from funciones_matematicas import suma

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.

# TODO: First import the `random` module


import random

# We begin with an empty `word_list`


word_file = "modulo_random_texto.txt"
word_list = []

# We fill up the word_list from the `words.txt` file


with open(word_file,'r') as words:
for line in words:
# remove white space and make everything lowercase
word = line.strip().lower()
# don't include words that are too long or too shor
t

Python 29
if 3 < len(word) < 8:
word_list.append(word)

# TODO: Add your function generate_password below


# It should return a string consisting of three random word
s
# concatenated together without spaces

def generate_password(): # *** Mi solucion ****


cadena = ""
for i in range(0,3):
indice = random.randint(0,len(word_list))
cadena += word_list[indice]

return cadena

# Now we test the function


print(generate_password())

# *** La del curso ***


def generate_password():
return random.choice(word_list) + random.choice(word_li
st) + random.choice(word_list)
# *** Otra solucion del curso ***
def generate_password():
return ''.join(random.sample(word_list,3))

#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

# 2- Para importar múltiples objetos individuales desde un


módulo:
from module_name import first_object, second_object

# 3- Para cambiar el nombre de un módulo:


import module_name as new_name

#4- Para importar un objeto de un módulo y cambiarle el nom


bre:
from module_name import object_name as new_name

# 5- Para importar cada objeto individualmente desde un mód


ulo (NO HAGAS ESTO):
from module_name import*

# 6- Si realmente desea utilizar todos los objetos de un mó


dulo, utilice la instrucción import module_name estándar en
su lugar y acceda a cada uno de los objetos con la notación
de puntos.
import module_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.

#Los modulos que son sub-modulos se llaman con la notacion


de punto

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

Ipython (consola interactiva de python)


#finalización de pestañas
#?para detalles sobre un objeto
#!para ejecutar comandos de shell del sistema
#resaltado de sintaxis!

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.

#Aquí hay un ejemplo de una función generadora llamada my_r


ange, que produce un iterador que es una secuencia de númer
os de 0 a (x - 1).
def my_range(x):
i = 0
while i < x:
yield i
i += 1
# Tenga en cuenta que en lugar de usar la palabra clave ret
urn, usa yield. Esto permite que la función devuelva valore
s uno a la vez y comience donde los dejó cada vez que se ll
ama. Esta yieldpalabra clave es lo que diferencia a un gene
rador de una función típica.

#Expresiones generadoras ¡Aquí hay un concepto genial que c


ombina generadores y listas de comprensión! De hecho, puede
crear un generador de la misma manera que normalmente escri
biría una lista de comprensión, excepto con paréntesis en l
ugar de corchetes. Por ejemplo:

sq_list =[x**2 for x in range(10)] # this produces a list o


f squares
sq_list= (x**2 for x in range(10)) # this produces an itera
tor of squares

#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 Orientado A Objectos


Flask notes

📱 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

You might also like