\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{chembembere} \pdfinfo{ /Title (starting-with-python.pdf) /Creator (Cheatography) /Author (chembembere) /Subject (Starting with Python Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{A3A3A3} \definecolor{LightBackground}{HTML}{F3F3F3} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Starting with Python Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{chembembere} via \textcolor{DarkBackground}{\uline{cheatography.com/76595/cs/18871/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}chembembere \\ \uline{cheatography.com/chembembere} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 12th May, 2019.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{x{2.28942 cm} x{2.68758 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Comentarios}} \tn % Row 0 \SetRowColor{LightBackground} Comentar código & \# \textless{}texto comentado\textgreater{} \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.58804 cm} x{2.38896 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Listas básico}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Acción}} & {\bf{Código}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} Crear una lista vacia & miLista = {[}{]} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} Crear una lista con valores & miLista={[}\textless{}valor1\textgreater{}, \textless{}valor2\textgreater{},...{]} \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} Añadir un valor a una lista & miLista.append(\textless{}valor\textgreater{}) \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} Crear una lista de listas en base a 2 listas & list(zip(lista1, lista2)) \tn % Row Count 10 (+ 3) % Row 5 \SetRowColor{white} Añadir una lista a otra con + & lista1+{[}'valor1',...,'valorN'{]} \tn % Row Count 12 (+ 2) % Row 6 \SetRowColor{LightBackground} Crear una lista consecutiva de números & range (\textless{}número\textgreater{}) (de 0 a número -1) \tn % Row Count 14 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Operaciones con listas}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Operación}} & {\bf{Código}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} Tamaño de una lista & len(miLista) \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} Seleccionar un elemento & miLista{[}index{]} \tn % Row Count 4 (+ 2) % Row 3 \SetRowColor{white} Seleccionar el último elemento & miLista{[}-1{]} \tn % Row Count 6 (+ 2) % Row 4 \SetRowColor{LightBackground} Obtener sublista & miLista {[}comienzo:final{]} (ojo, final no se incluye) \tn % Row Count 9 (+ 3) % Row 5 \SetRowColor{white} Obtener los N primeros elementos de una lista & miLista{[}0:N{]} o miLista{[}:3{]} \tn % Row Count 12 (+ 3) % Row 6 \SetRowColor{LightBackground} Obtener los los elementos desde la posición N hasta el final & miLista{[}N:{]} \tn % Row Count 16 (+ 4) % Row 7 \SetRowColor{white} Obtener los N últimos elementos de una lista & miLista{[}-3:{]} \tn % Row Count 19 (+ 3) % Row 8 \SetRowColor{LightBackground} Contar la aparición de un elemento en una lista & miLista.count('\textless{}elemento\textgreater{}') \tn % Row Count 22 (+ 3) % Row 9 \SetRowColor{white} Ordenar los elementos de una lista & miLista.sort() (no genera lista, actua sobre la lista original) \tn % Row Count 26 (+ 4) % Row 10 \SetRowColor{LightBackground} & \seqsplit{miLista2=sorted(miLista)} \tn % Row Count 28 (+ 2) % Row 11 \SetRowColor{white} Obtener el índice de un elemento en una lista & miLista.index(\textless{}elemento\textgreater{}) (Devuelve el índice de la primera aparición del elemento) \tn % Row Count 33 (+ 5) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Operaciones con listas (cont)}} \tn % Row 12 \SetRowColor{LightBackground} Ver si un elemento está en una lista & If element in miLista (True si está) \tn % Row Count 2 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Loops para recorrer listas}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Bucle for}} \newline for \textless{}variable\textgreater{} in \textless{}lista\textgreater{}: \newline \textless{}código\textgreater{} \newline \newline {\bf{Bucle for usando índice en vez de valor}} \newline for i in range (len(\textless{}lista\textgreater{})): \newline código} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.14471 cm} x{3.83229 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Funciones para trabajar con listas}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Función}} & {\bf{Explicación}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} range() & range(10): Crea una lista de 0 a 9 \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} & range (2,9): Crea una lista de 2 a 8 \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} & range (2,9,2): Crea una lista de 2 a 9, pero saltando 2 posiciones \tn % Row Count 9 (+ 3) % Row 4 \SetRowColor{LightBackground} index() & milista.index(\textless{}elemento\textgreater{}) Devuelve el primer índice en el que se encuentra el elemento indicado, si no encuentra nada devuelve un ValueError \tn % Row Count 14 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{List Comprehensions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Para crear una list comprehension se usa:}} \newline usernames = {[}word for word in words if word{[}0{]} == '@'{]} \newline \newline Explicación: \newline Toma el elemento de la lista words en word. \newline Si el primer elemento de la variable es @ entonces lo añade a la lista \newline Si no, no hace nada. \newline \newline {\bf{Duplicar una lista}} \newline usernames = {[}word for word in words{]} \newline \newline Explicación: \newline Al no haber condición, duplica toda la lista} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Funciones}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Para definir una función: \newline def \textless{}nombre\textgreater{}(\textless{}parámetro1\textgreater{}, \textless{}parámetro 2\textgreater{}...\textless{}parámentro n\textgreater{}): \newline \textless{}código\textgreater{} \newline return \textless{}salida\textgreater{} \newline \newline {\bf{Argumentos}} \newline {\emph{Positional arguments}}: their assignments depend on their positions in the function call. \newline {\emph{keyword arguments}}: where we explicitly refer to what each argument is assigned to in the function call. \newline \newline def \seqsplit{create\_spreadsheet(title}, row\_count=1000): \newline \newline Una vez que se usan argumentos con keyword, detras de este argumento tienen que ser keyword. \newline \newline El caso de que tenga argumentos con keyword, puedo llamar la función sin especificar esos parámetros que usan el valor por defecto. \newline \newline {\bf{Devolver valores}} \newline return (\textless{}valor\textgreater{}) \newline \newline Si quiero devolver un texto más un valor, debo convertir primero el valor en string \newline return ("EL valor es"+ str(\textless{}valor\textgreater{})) \newline \newline Multiples valores: \newline def square\_point(x\_value, y\_value): \newline x\_2 = x\_value {\emph{ x\_value \newline y\_2 = y\_value }} y\_value \newline return x\_2, y\_2 \newline \newline x\_squared, y\_squared = square\_point(1, 3) \newline print(x\_squared) \newline print(y\_squared)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.19448 cm} x{3.78252 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Impresión de resultados}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Función}} & {\bf{Efecto}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} print() & Imprime el contenido entre paréntesis \tn % Row Count 4 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.14471 cm} x{3.83229 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Funciones de transformación}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Función}} & {\bf{Efecto}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} str() & Convierte un tipo numérico en string. Muy útil cuando se quieren imprimir números junto con strings mediante el print() \tn % Row Count 7 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.09494 cm} x{3.88206 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Comandos de linea de comandos}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Comando}} & {\bf{Efecto}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} ls & Listar un directorio \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} pwd & Indica el nombre del directorio actual \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} cd & Cambiar directorio \tn % Row Count 6 (+ 1) % Row 4 \SetRowColor{LightBackground} mkdir & Crear directorio \tn % Row Count 7 (+ 1) % Row 5 \SetRowColor{white} touch & Crear fichero \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{try...except}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Try ...except nos permiten capturar un posible error y hacer algo al respecto en vez de bloquear el programa. \newline \newline La sintaxis es: \newline try: \newline some\_thing = \seqsplit{can\_trigger\_a\_syntax\_errror()} \#o cualquier error \newline except SyntaxError: \newline print("Error caught!")} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.18988 cm} x{2.78712 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Operadores Numéricos}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Operador}} & {\bf{Efecto}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} + & Suma \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} - & Resta \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} * & Multiplicación \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} / & División \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} a**b & Exponente \tn % Row Count 6 (+ 1) % Row 6 \SetRowColor{LightBackground} a\%b & Módulo \tn % Row Count 7 (+ 1) % Row 7 \SetRowColor{white} a+=b & a= a+b \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.94103 cm} x{3.03597 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Operaciones con Strings}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Operador}} & {\bf{Efecto}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} "a"+"b" & Concatenar \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} '''\textless{}string\textgreater{}''' & Multi line string (3') \tn % Row Count 3 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.04057 cm} x{2.93643 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Operadores para el control de la ejecución}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{Operador}} & {\bf{Efecto}} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} == & Igual a \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} != & No igual \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \textgreater{} & Mayor que \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \textgreater{}= & Mayor o igual \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} \textless{} & Menor que \tn % Row Count 6 (+ 1) % Row 6 \SetRowColor{LightBackground} \textless{}= & Menor o igual que \tn % Row Count 7 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Bloque IF}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{If (condicion): \newline \textless{}codigo\textgreater{} \newline elif (condicion): \newline \textless{}codigo\textgreater{} \newline else: \newline \textless{}codigo\textgreater{}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Métodos de ristras}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Método}}} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}{\bf{Resultado}}} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{"Hello world".upper()} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"HELLO WORLD"} \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{"Hello world".lower()} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"hello world"} \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{"Hello world".title()} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"Hello World"} \tn % Row Count 8 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{"Hello world".split()} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}{[}'Hello', 'world'{]}, podemos indicar el caracter por el que separar e incluso usar \textbackslash{}n para indicar salto de linea o \textbackslash{}t para indicar tabulador} \tn % Row Count 12 (+ 4) % Row 5 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{" ".join({[}'Hello', 'world'{]})} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"Hello world"} \tn % Row Count 14 (+ 2) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{"Hello world".replace("H", "J")} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"Jello world"} \tn % Row Count 16 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{" Hello world ".strip()} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"Hello world"} \tn % Row Count 18 (+ 2) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{"\{\} \{\}".format("Hello", "world")} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}"Hello world"} \tn % Row Count 20 (+ 2) % Row 9 \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{"Hello world".find("w")} \tn \mymulticolumn{1}{x{5.377cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}6 (indice donde la primer "w" se encuentra, si no encuentra nada devuelve -1)} \tn % Row Count 23 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Modulos}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Importar un módulo: \newline \newline from \textless{}nombre módulo\textgreater{} import \textless{}object\textgreater{} \newline \newline Si quiero importar toda una librería: \newline \newline import \textless{}nombre\textgreater{} \newline \newline Para llamar a una función de un módulo: \newline \newline \textless{}modulo\textgreater{}.function() \newline \newline Para dar un alias a un módulo: \newline import \textless{}modulo\textgreater{} as \textless{}alias\textgreater{} \newline \newline Ver los métodos de un módulo: \newline import math \newline print(dir(math))w \newline \newline \newline Importar una función de otro fichero: \newline \newline from \textless{}fichero\textgreater{} import \textless{}método\textgreater{}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Métodos de Random}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# shuffle() will shuffle a sequence in place \newline arr = {[}1, 2, 3, 4{]} \newline random.shuffle(arr) \newline print(arr) \# {[}3, 1, 4, 2{]} \newline \newline \# random() will return a random float value between \newline \# 0.0 (inclusive) and 1.0 (exclusive) \newline print(random.random()) \# 0.237... \newline print(random.random()) \# 0.441... \newline \newline \# choices() is similar to choice(), but can return a list of k elements \newline \# from a list, with possibly repeating values. \newline arr = {[}1, 2, 3, 4, 5{]} \newline print(random.choices(arr, k=3)) \# {[}1, 1, 4{]}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Diccionarios}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{{\emph{Definición:}}}} \newline Conjuntos de pares {\emph{clave}} : {\emph{valor}} \newline \newline menu = \{"oatmeal": 3, "avocado toast": 6, "carrot juice": 5, "blueberry muffin": 2\} \newline \newline Un diccionario no puede tener 2 claves con el mismo valor. \newline \newline Una Tupla puede ser una clave para un diccionario ya que son valóres únicos inamovibles. \newline \newline {\bf{{\emph{Declarando un diccionario}}}} \newline empty\_dict = \{\} \newline \newline {\bf{{\emph{Ver si un diccionario está vacio}}}} \newline {\emph{Opción 1:}} \newline dict1 = \{\} \newline \newline if dict1: \newline print("dict1 Not Empty") \newline else: \newline print("dict1 is Empty") \newline \newline if bool(dict1): \newline print("dict1 Not Empty") \newline else: \newline print("dict1 is Empty") \newline \newline {\emph{Opción 2}} \newline dict1 = \{\} \newline \newline if len(dict1) == 0: \newline print("dict1 is Empty") \newline \newline \newline {\bf{{\emph{Añadir valores a un diccionario}}}} \newline {\emph{Opción 1}} \newline my\_dict{[}"new\_key"{]} = "new\_value" \newline \newline {\emph{Opción 2}} \newline sensors.update(\{"pantry": 22, "guest room": 25, "patio": 34\}) \newline \newline {\bf{{\emph{List comprehension}}}} \newline drinks = {[}"espresso", "chai", "decaf", "drip"{]} \newline caffeine = {[}64, 40, 0, 120{]} \newline zipped\_drinks=zip(drinks, caffeine) \newline drinks\_to\_caffeine=\{key:value for key, value in zipped\_drinks\}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Operaciones con diccionarios}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{{\bf{Leer un valor de un diccionario}} \newline % Row Count 1 (+ 1) `diccionario{[}"key"{]}` \newline % Row Count 2 (+ 1) Si 2 keys tienen diferente tipo, incluso si su valor es igual, se tratan como keys diferentes: \newline % Row Count 4 (+ 2) mydict = \{ \} \newline % Row Count 5 (+ 1) mydict{[}5{]} = "value1" \newline % Row Count 6 (+ 1) mydict{[}'5'{]} = "value2" \newline % Row Count 7 (+ 1) print(mydict) \newline % Row Count 8 (+ 1) \# \{5: 'value1', '5': 'value2'\} \newline % Row Count 9 (+ 1) Si intentamos acceder a una key qie no está en el diccionario, nos devolverá un error. \newline % Row Count 11 (+ 2) {\bf{Try/Except para leer una key}} \newline % Row Count 12 (+ 1) `try:` \newline % Row Count 13 (+ 1) `print(caffeine\_level{[}"matcha"{]})` \newline % Row Count 14 (+ 1) `except KeyError:` \newline % Row Count 15 (+ 1) `print("Unknown Caffeine Level")` \newline % Row Count 16 (+ 1) Si quieres saber qué {\emph{key}} es la que provoca el error, puedes usar este código \newline % Row Count 18 (+ 2) try: \newline % Row Count 19 (+ 1) utah\_list = population{[}'Utah'{]} \newline % Row Count 20 (+ 1) except KeyError as k: \newline % Row Count 21 (+ 1) print("Key " + str(k) + " does not exist") \newline % Row Count 22 (+ 1) {\bf{Comprobar si existe una {\emph{key}} en el diccionario}} \newline % Row Count 24 (+ 2) `key\_to\_check = "Landmark 81"` \newline % Row Count 25 (+ 1) `if key\_to\_check in building\_heights:` \newline % Row Count 26 (+ 1) ` print(building\_heights{[}"Landmark 81"{]})` \newline % Row Count 27 (+ 1) {\bf{Obtener una {\emph{key}} con get}} \newline % Row Count 28 (+ 1) building\_heights = \{"Burj Khalifa": 828, "Shanghai Tower": 632, "Abraj Al Bait": 601, "Ping An": 599, "Lotte World Tower": 554.5, "One World Trade": 541.3\} \newline % Row Count 32 (+ 4) } \tn \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Operaciones con diccionarios (cont)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{\#this line will return 632: \newline % Row Count 1 (+ 1) \seqsplit{building\_heights.get("Shanghai} Tower") \newline % Row Count 2 (+ 1) \#this line will return None: \newline % Row Count 3 (+ 1) \seqsplit{building\_heights.get("My} House") \newline % Row Count 4 (+ 1) Se puede usar el get sin asignar a una variable, por ejemplo para condiciones. \newline % Row Count 6 (+ 2) Además se puede indicar un valor por defecto (número o string) \newline % Row Count 8 (+ 2) \seqsplit{`stack\_id=user\_ids.get("superStackSmash"}, 100000)` \newline % Row Count 10 (+ 2) {\bf{Extraer un valor de un diccionario con pop()}} \newline % Row Count 11 (+ 1) \seqsplit{`midiccionario.pop(320291}, "No Prize")` \newline % Row Count 12 (+ 1) Si no se pone valor por defecto y no se encuentra la clave se devuelve un KeyError exception% Row Count 14 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}