\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{luckytime} \pdfinfo{ /Title (python-121.pdf) /Creator (Cheatography) /Author (luckytime) /Subject (python 121 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{python 121 Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{luckytime} via \textcolor{DarkBackground}{\uline{cheatography.com/214087/cs/46599/}}} \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}luckytime \\ \uline{cheatography.com/luckytime} \\ \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 29th June, 2025.\\ 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*}{4} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{Files}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{file = open("data.txt") \# open file \newline % Row Count 1 (+ 1) contents = file.read() \# whole file as string \newline % Row Count 2 (+ 1) lines = file.readlines() \# all lines as list \newline % Row Count 3 (+ 1) line = file.readline() \# one line \newline % Row Count 4 (+ 1) for line in file: \# loop lines \newline % Row Count 5 (+ 1) line = line.strip() \# remove \textbackslash{}n and spaces \newline % Row Count 6 (+ 1) parts = line.split(",") \# split by comma \newline % Row Count 7 (+ 1) file.close() \# close file% Row Count 8 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{Class}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{"""A program that defines a Student class and then tests it""" \newline % Row Count 2 (+ 2) class Student: \# Hint: How do you declare a class? \newline % Row Count 4 (+ 2) """Defines a Student class. \newline % Row Count 5 (+ 1) Data attributes: \newline % Row Count 6 (+ 1) student\_id : integer \newline % Row Count 7 (+ 1) usercode : string \newline % Row Count 8 (+ 1) first\_name, family\_name : strings \newline % Row Count 9 (+ 1) courses : set of course names(strings) \newline % Row Count 11 (+ 2) Methods: \newline % Row Count 12 (+ 1) get\_email\_address() \newline % Row Count 13 (+ 1) enrol\_course() \newline % Row Count 14 (+ 1) is\_enrolled\_in() \newline % Row Count 15 (+ 1) """ \newline % Row Count 16 (+ 1) def \_\_init\_\_(self, student\_id, usercode, first\_name, family\_name ): \newline % Row Count 18 (+ 2) """Creates a new Student object.""" \newline % Row Count 19 (+ 1) self.student\_id = student\_id \newline % Row Count 20 (+ 1) self.usercode = usercode \newline % Row Count 21 (+ 1) self.first\_name = first\_name \newline % Row Count 22 (+ 1) self.family\_name = family\_name \newline % Row Count 23 (+ 1) self.courses = set() \newline % Row Count 24 (+ 1) def \_\_str\_\_(self): \newline % Row Count 25 (+ 1) """Returns a printable version of a student.""" \newline % Row Count 27 (+ 2) return f"\{self.student\_id\} \{self.family\_name.upper()\}, \{self.first\_name.capitalize()\}" \newline % Row Count 29 (+ 2) def \seqsplit{get\_email\_address(self):} \newline % Row Count 30 (+ 1) } \tn \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{Class (cont)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{ """Returns the student's email address.""" \newline % Row Count 2 (+ 2) return f"\{self.usercode\}@uclive.ac.nz" \newline % Row Count 3 (+ 1) def enrol\_course(self, course): \newline % Row Count 4 (+ 1) """Update the set of courses a student is enrolled in.""" \newline % Row Count 6 (+ 2) self.courses.add(course) \newline % Row Count 7 (+ 1) def is\_enrolled\_in(self, course): \newline % Row Count 8 (+ 1) """Test to see if the course exists in the set of courses taken by the student.""" \newline % Row Count 10 (+ 2) return course in self.courses \newline % Row Count 11 (+ 1) def main(): \newline % Row Count 12 (+ 1) """Main function tests the Student class""" \newline % Row Count 13 (+ 1) astudent = Student(1234567, "ffn127", "first NAMES", "Family name") \# Hint: Create an Student instance \newline % Row Count 16 (+ 3) print(type(astudent)) \# Print its type \newline % Row Count 17 (+ 1) print(astudent) \# Print the student's id and name \newline % Row Count 19 (+ 2) \seqsplit{astudent.enrol\_course("COSC121")} \# Hint: Enrol the student in the course "COSC121" \newline % Row Count 21 (+ 2) \seqsplit{print(astudent.is\_enrolled\_in("COSC121"))} \#Should print True \newline % Row Count 23 (+ 2) \seqsplit{print(astudent.is\_enrolled\_in("COSC122"))} \#Should print False \newline % Row Count 25 (+ 2) \seqsplit{print(astudent.get\_email\_address()} ) \#Should print Student's email address \newline % Row Count 27 (+ 2) main()% Row Count 28 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{x{1.92248 cm} x{1.51052 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{3.833cm}}{\bf\textcolor{white}{list slicing}} \tn % Row 0 \SetRowColor{LightBackground} nums = {[}10, 20, 30, 40, 50, 60{]} & nums{[}1:4{]} {[}20, 30, 40{]} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} nums{[}:3{]}. {[}10, 20, 30{]} & nums{[}-2:{]} last 2 items \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} nums{[}:-1{]} all but last & nums{[}::2{]} every 2nd item \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{3.833cm}}{nums{[}::-1{]}. reverse} \tn % Row Count 7 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{x{1.75083 cm} x{1.68217 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{3.833cm}}{\bf\textcolor{white}{If statment}} \tn % Row 0 \SetRowColor{LightBackground} if num \% 2 == 0: \#even & if num \% 2 != 0: \#odd \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} 6 / 2 \#3.0 & 7 // 2 \#3 \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} 7 \% 2 \#1 & 3 ** 2 \#9 \tn % Row Count 4 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{matplotlib}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{import matplotlib.pyplot as plt \newline % Row Count 1 (+ 1) import numpy as np \newline % Row Count 2 (+ 1) \# Data \newline % Row Count 3 (+ 1) x = np.linspace(0, 10, 100) \newline % Row Count 4 (+ 1) y = np.sin(x) \newline % Row Count 5 (+ 1) \# Basic Plot \newline % Row Count 6 (+ 1) plt.plot(x, y, label='Sine wave') \newline % Row Count 7 (+ 1) plt.scatter(x, y, s=10, color='red') \newline % Row Count 8 (+ 1) plt.bar({[}1, 2, 3{]}, {[}3, 5, 2{]}) \newline % Row Count 9 (+ 1) \seqsplit{plt.hist(np.random.randn(1000)}, bins=20, alpha=0.5) \newline % Row Count 11 (+ 2) plt.pie({[}25, 35, 40{]}, labels={[}'A', 'B', 'C'{]}) \newline % Row Count 12 (+ 1) \# Labels and Title \newline % Row Count 13 (+ 1) plt.title("Main Title") \# Regular title \newline % Row Count 15 (+ 2) plt.title(r"\$y = x\textasciicircum{}2 + 3x + 500\$") \# LaTeX math formatted title \newline % Row Count 17 (+ 2) plt.xlabel("X Axis") \newline % Row Count 18 (+ 1) plt.ylabel("Y Axis") \newline % Row Count 19 (+ 1) plt.legend() \newline % Row Count 20 (+ 1) plt.grid(True) \newline % Row Count 21 (+ 1) plt.xlim(0, 10) \newline % Row Count 22 (+ 1) plt.ylim(-1, 1) \newline % Row Count 23 (+ 1) \# Axes Object (Manual) \newline % Row Count 24 (+ 1) ax = plt.axes() \newline % Row Count 25 (+ 1) ax.plot(x, y, label="sin(x)") \newline % Row Count 26 (+ 1) ax.set\_title(r"Axes Title: \$y = \textbackslash{}sin(x)\$") \newline % Row Count 27 (+ 1) ax.set\_xlabel("X label") \newline % Row Count 28 (+ 1) ax.set\_ylabel("Y label") \newline % Row Count 29 (+ 1) ax.legend() \newline % Row Count 30 (+ 1) } \tn \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{matplotlib (cont)}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{ax.grid(True) \newline % Row Count 1 (+ 1) \# Multiple Manual Axes (Optional Advanced Use) \newline % Row Count 2 (+ 1) fig = plt.figure() \newline % Row Count 3 (+ 1) ax1 = fig.add\_axes({[}0.1, 0.55, 0.35, 0.35{]}) \# {[}left, bottom, width, height{]} \newline % Row Count 5 (+ 2) ax1.plot(x, y) \newline % Row Count 6 (+ 1) ax2 = fig.add\_axes({[}0.6, 0.1, 0.35, 0.35{]}) \newline % Row Count 7 (+ 1) ax2.scatter(x, y, color='purple') \newline % Row Count 8 (+ 1) \# Save and Show \newline % Row Count 9 (+ 1) \seqsplit{plt.savefig("my\_plot.png")} \newline % Row Count 10 (+ 1) plt.show()% Row Count 11 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{For Loops}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{for i in range(5): print(i) \# 0 1 2 3 4 \newline % Row Count 2 (+ 2) for i in range(2,6): print(i) \# 2 3 4 5 \newline % Row Count 3 (+ 1) for i in range(1,10,3): print(i) \# 1 4 7 \newline % Row Count 4 (+ 1) lst={[}'a','b','c'{]} \newline % Row Count 5 (+ 1) for i in range(len(lst)): print(i,lst{[}i{]}) \# 0 a 1 b 2 c \newline % Row Count 7 (+ 2) for item in lst: print(item) \# a b c \newline % Row Count 9 (+ 2) for i,item in enumerate(lst): print(i,item) \# 0 a 1 b 2 c% Row Count 11 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{switching while loop to for loop}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{\# For loops \newline % Row Count 1 (+ 1) for op1 in range(0, value1): \newline % Row Count 2 (+ 1) for op2 in range(value1, value2, -1): \newline % Row Count 3 (+ 1) print(f"\{op1:3\} x \{op2:3\} = \{op1*op2:3\}") \newline % Row Count 4 (+ 1) \# Equivalent while loops \newline % Row Count 5 (+ 1) op1 = 0 \newline % Row Count 6 (+ 1) while op1 \textless{} value1: \newline % Row Count 7 (+ 1) op2 = value1 \newline % Row Count 8 (+ 1) while op2 \textgreater{} value2: \newline % Row Count 9 (+ 1) print(f"\{op1:3\} x \{op2:3\} = \{op1*op2:3\}") \newline % Row Count 10 (+ 1) op2 -= 1 \newline % Row Count 11 (+ 1) op1 += 1% Row Count 12 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{3.833cm}}{\bf\textcolor{white}{Sets and Dictionaries}} \tn \SetRowColor{white} \mymulticolumn{1}{x{3.833cm}}{\# Sets from list and operations \newline % Row Count 1 (+ 1) lst={[}1,2,2,3,4,4{]} \newline % Row Count 2 (+ 1) s=set(lst) \# \{1,2,3,4\} \newline % Row Count 3 (+ 1) s.add(5) \# \{1,2,3,4,5\} \newline % Row Count 4 (+ 1) s.remove(2) \# \{1,3,4,5\} \newline % Row Count 5 (+ 1) s.discard(6) \# \{1,3,4,5\} no error \newline % Row Count 6 (+ 1) print(3 in s) \# True \newline % Row Count 7 (+ 1) s2=\{3,4,5,6\} \newline % Row Count 8 (+ 1) print(s.union(s2)) \# \{1,3,4,5,6\} \newline % Row Count 9 (+ 1) \seqsplit{print(s.intersection(s2))\#} \{3,4,5\} \newline % Row Count 10 (+ 1) print(s.difference(s2)) \# \{1\} \newline % Row Count 11 (+ 1) print(s.issubset(s2)) \# False \newline % Row Count 12 (+ 1) for x in s: print(x) \# 1 3 4 5 (any order) \newline % Row Count 13 (+ 1) \# Dictionaries and methods \newline % Row Count 14 (+ 1) d=\{"a":1,"b":2\} \newline % Row Count 15 (+ 1) print(d.keys()) \# dict\_keys({[}'a','b'{]}) \newline % Row Count 16 (+ 1) print(d.values()) \# dict\_values({[}1,2{]}) \newline % Row Count 17 (+ 1) print(d.items()) \# dict\_items({[}('a',1),('b',2){]}) \newline % Row Count 19 (+ 2) print(d.get("a")) \# 1 \newline % Row Count 20 (+ 1) print(d.get("z",0)) \# 0 default if missing \newline % Row Count 21 (+ 1) d{[}"c"{]}=3 \newline % Row Count 22 (+ 1) for k in d: print(k) \# a b c \newline % Row Count 23 (+ 1) for v in d.values(): print(v) \# 1 2 3 \newline % Row Count 24 (+ 1) for k,v in d.items(): print(k,v) \# a 1 b 2 c 3% Row Count 25 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{3.833cm}{x{2.02547 cm} x{1.40753 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{3.833cm}}{\bf\textcolor{white}{Lists}} \tn % Row 0 \SetRowColor{LightBackground} fruits = {[}"apple", "banana", "cherry"{]} & fruits{[}0{]} \#apple \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} fruits{[}-1{]} \#cherry & len(fruits) \#3 \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} fruits.append("kiwi") & fruits.insert(1, "pear") \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} \seqsplit{fruits.remove("banana")} & fruits.pop() \#removes last \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} fruits.sort() & sorted(fruits) \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}