Automating Everything With Python Notes
Automating Everything With Python
Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate (that is, reduce) down to a single value.” Ex (2+2).
Data Types
“ A value that is passed to a function call is an argument.”
“If you use your finger to trace through a program with flow control statements, you’ll likely find yourself jumping around the source code based on conditions.
“Once one of the statements’ conditions is found to be True, the rest of the elif clauses are automatically skipped.”
Global Scope: Es una variable afuera de una función. NO puedes usar las local en otra función. (Puedes crear una variable global dentro de una función poniendo global)
Local Scope: Es una variable dentro de una función. puedes usar las global en la función. (Puedes crear variables dentro de tu mini programa pero solo las puedes usar ahi)
Lists can also contain other list values. The values in these lists of lists can be accessed using multiple indexes, like so.
You can use tuples to convey to anyone reading your code that you don’t intend for that sequence of values to change. If you need an ordered sequence of values that never changes, use a tuple.
You can use copy() or deepcopy() if you want to make changes to a list in one variable without modifying the original list.
'name' in spam.keys() Funciona para ver si una key o value está en el diccionario.
The escape characters \' and \" let you put single quotes and double quotes inside your strings, respectively.
Functions
str() #converts something to a string.
int() #converts something to a whole number.
float() #converts something to a number with decimals.
len() # Cuenta cuántos caracteres tiene el string. Cuantos ítems tiene una lista.
randint() # Te da números random entre un parámetro establecido (1,10)
sys.exit() #es para terminar el programa pero primero tienes que traer el sys (Import sys)
def() #es para crear una funcion que puedes llamar cuando sea puedes.
import # Puedes importar cualquier módulo o librería.
None #regresa nada
tuple() #Convierte una lista a un tuple
list() #Convierte un tuple a una lista
Modules
copy.copy() #Para duplicar una lista (crear una nueva referencia)
copy.deecopy() #Para quitar una lista (Para eliminar la nueva referencia)
pprint.pprint() #Para imprimir listas y diccionarios de forma vertical y limpio. pformat
random #seleccionar cosas random
pyperclip #para poder copiar y pegar cosas de tu paperclip
Flow control statements: can decide which Python instructions to execute under which conditions.
Boolean Values: 0 - 1, True or False.
Boolean Operators: The and and or operators always take two Boolean values (or expressions), so they’re considered binary operators. not operator evaluate the opposite boolean value.
Comparison Operators
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to”
Statements:
if # decide entre dos caminos true y false.
else # el paso siguiente si la condición es falsa.
elif # Si la primera condición es falsa agrega otra condición y la evalua. (El orden importa porque te puedes saltar condiciones)
while # Loop “The code in a while clause will be executed as long as the while statement’s condition is True”
Break # statement para romper el loop.
Continue #regresa a ser evaluado dentro del loop.
For i in range(n): #Loop que se repite n veces. (i es una variable que va aumentando)
➊ total = 0
➋ for num in range(101):
➌ total = total + num”
➍ print(total)
Range (start, stop, step) step es la cantidad que la variable aumenta después de cada iteración.
Return #te da una respuesta específica.
try: #sirve para continuar tu programa cuando hay errores
except nombre del error: #continúa tu programa cuando hay errores
del # will delete values at an index in a list del spam[2]
append.() #agrega lo que sea a una lista, tienes que poner adentro del paréntesis lo que quieres agregar.
Keyword Arguments
end= # Sirve para quitar la línea/espacio entre dos funciones.
reverse=True #Para hacer lo contrario que true. spam.sort(reverse=True)
lower #Pasa las mayus a minus. spam.sort(key=str.lower)
Lists
A list is a value that contains multiple values in an ordered sequence.
[ ] #Las listas empiezan y terminan con estos paréntesis.
Items # the values inside the lists are called items
, # Items are separated by commas.
Index #El orden dentro de la lista, para llamar un ítem único necesitas poner la variable más el inter spam[2] spam[3] spam[1].
Negative Index: While indexes start at 0 and go up, you can also use negative integers for the index. The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in a list.
Slices: In a slice, the first integer is the index where the slice starts. The second integer is the index where the slice ends. spam[0:1]
Spam[1] = 'aardvark' # De esta forma cambias el ítem dentro de la lista.
+ o * # con estos puedes sumar listas o replicarlas.
*List variables don’t actually contain lists—they contain references to lists.
Operator
in # conecta un valor específico y el lugar donde lo va a buscar. vlookup.
not # busca si un valor no está en una lista.
Multiple assignment
“>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat”
Methods
Lists:
A method is the same thing as a function, except it is “called on” a value.
The method part comes after the value, separated by a period
When there are duplicates of the value in the list, the index of its first appearance is returned.
index() #Busca en la lista lo que está dentro del paréntesis y regresa el número/posición del index.
append() #Agrega al final cualquier variable a la lista. spam.append('moose')
insert() #Agregar donde en cualquier parte del index cualquier variable. spam.insert(1, 'chicken')
remove() #Elimina cualquier variable de la lista.
sort() #Ordena las variables alfabéticamente y por orden de mayus y minus.
upper() #Converts a string in upper case
lower() #Converts a string in lower case
isupper() #Boolean true value is a string contains at least one upper value
islower() #Boolean rue value is a string contains at least one lower value
isalpha()# returns True if the string consists only of letters and is not blank.
isalnum()#returns True if the string consists only of letters and numbers and is not blank.
isdecimal()# returns True if the string consists only of numeric characters and is not blank.
isspace()# True if the string consists only of spaces, tabs, and new-lines and is not blank.
istitle()# returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters.
startswith() #returns True if the string starts with something specific.
endswith() #returns True if the string ends with something specific.
join() #Joins a list of strings into one.
split() #splits a list of string by spaces or by specific value inside(“”)
rjust() # justifica right el texto con en el número de espacios necesarios entre el inicio y el string.
ljust() # justifica left...
center() #centra el string en left y right
rstrip() #elimina los espacios de la derecha.
lstrip() #elimina los espacios de la izquierda.
strip() #elimina los espacios de izquierda y derecha.
copy() #copia a tu clipboard lo que selecciones. import pyperclip module
paste() #pega lo que esté en tu clipboard import pyperclip module
Tuple: They are immutable data type you cannot change and you write it with (). (("puta",)) * solo para poner 1 valor.
Dictionary: Like lists dictionaries contains many different values. His index is called keys and you can use different data types strings integers etc. {} ham = {'species': 'cat', 'age': '8'} . Unlike lists, items in dictionaries are unordered. spam['color'] Tiene un valor dentro de la key.
keys() #Es el llava que contiene un valor. solo con esta llave traes el valor. dict_key
values() #Lo que está adentro del baúl y que necesitas la llave para entrar. dict_values
items() #
get() # Para buscar si esta un key en el diccionario si esta que te de el value y sino que te de un valor específico. “I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.”
setdefault() # Para ver si a key existe y para agregarle un valor si no.