\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{solisoleille (soleille01)} \pdfinfo{ /Title (python-beginner-syntax.pdf) /Creator (Cheatography) /Author (solisoleille (soleille01)) /Subject (Python - Beginner Syntax 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}{46A337} \definecolor{LightBackground}{HTML}{F3F9F2} \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 - Beginner Syntax Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{solisoleille (soleille01)} via \textcolor{DarkBackground}{\uline{cheatography.com/130728/cs/32202/}}} \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}solisoleille (soleille01) \\ \uline{cheatography.com/soleille01} \\ \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 3rd August, 2022.\\ 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{0.9954 cm} x{3.9816 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Augmented assignment/ Assignment operators}} \tn % Row 0 \SetRowColor{LightBackground} a = b & Standard variable assignment \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} a += b & Equivalent to a = a + b \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} a -= b & Equivalent to a = a - b \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} a *= b & Equivalent to a = a * b \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} a /= b & Equivalent to a = a / b \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} a \%= b & Equivalent to a = a \% b \tn % Row Count 6 (+ 1) % Row 6 \SetRowColor{LightBackground} a **= b & Equivalent to a = a ** b; \tn % Row Count 7 (+ 1) % Row 7 \SetRowColor{white} a //= b & Equivalent to a = a // b; \tn % Row Count 8 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Augmented assignment}}: Python supports augmented assignment for common arithmetic and logical operators. \newline {\bf{Note:}} This is not an exhaustive list.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.74655 cm} x{4.23045 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Input and output}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{input()} & The input function prints text and expects a value from the user (string typed by user). Type functions (e.g. int()) can be used around it to get only certain types of values. \tn % Row Count 6 (+ 6) % Row 1 \SetRowColor{white} \seqsplit{print()} & The print function can print any number of expressions (separated by commas). Successive print statements will display on separate lines. A bare print will print a blank line. \tn % Row Count 12 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{General variable declaration and assignment}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Declaration and initial assignment: \newline % Row Count 1 (+ 1) `var\_name = new\_value` \newline % Row Count 2 (+ 1) `var\_name` = 3 ** new\_value` \newline % Row Count 3 (+ 1) `var\_name = other\_var` \newline % Row Count 4 (+ 1) etc. \newline % Row Count 5 (+ 1) Assignment statements involving initial variable value: \newline % Row Count 7 (+ 2) `var\_name = 2 * var\_name` \newline % Row Count 8 (+ 1) `var\_name = var\_name ** 2 + 5` \newline % Row Count 9 (+ 1) Simultaneous assignment: \newline % Row Count 10 (+ 1) `var\_1, var\_2... = value1, value2...`% Row Count 11 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Variables}}: The basic mechanism by which data is organised and stored (long-term, short-term, and communication etc.). Variables must be declared before referred to in other statements. \newline {\bf{Note:}} Variables can be reassigned as many times as needed.} \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}{General for loops}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{for variable in sequence\_name: \newline {\emph{code body}} \newline \newline for variable in {[}var1, var2, var3...{]}: \newline {\emph{code body}} \newline \newline for variable in {[}const1, const2...{]}: \newline {\emph{code body}} \newline \newline for variable in range(...): \newline {\emph{code body}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{For loops:}} A type of definite iterations. Also reference to as control strctures. \newline {\bf{Loop index:}} The variable after the for is called the loop index. It takes on each successive value in sequence.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.33919 cm} x{2.63781 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Dealing with Strings}} \tn % Row 0 \SetRowColor{LightBackground} "String"{[}{\emph{index}}{]} & String indexing, accesses an individual character found at the specified index in the string. \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} "String"{[}index1:index2{]} & String slicing, returning a substring of the original string between the specified indexes \tn % Row Count 10 (+ 5) % Row 2 \SetRowColor{LightBackground} "Stringa" + "Stringb" & String concatenation, achieved with the + operator and puts the multiple strings together \tn % Row Count 15 (+ 5) % Row 3 \SetRowColor{white} "String" * {\emph{int}} & Repetition, returns the same string repeated a specified number of times in the same new string \tn % Row Count 20 (+ 5) % Row 4 \SetRowColor{LightBackground} len("String") & Finds the character length of a string \tn % Row Count 22 (+ 2) % Row 5 \SetRowColor{white} for {\emph{var}} in "String" & Iterates through all the characters in a string \tn % Row Count 25 (+ 3) % Row 6 \SetRowColor{LightBackground} "string".upper() OR "string".lower() & The upper() function changes all characters to uppercase/lowercase \tn % Row Count 29 (+ 4) % Row 7 \SetRowColor{white} \seqsplit{ord("char\_string")} OR chr({\emph{int}}) & The ord() function returns the numeric (ordinal) code of a single character, the chr() function converts a numeric code to the corresponding character \tn % Row Count 37 (+ 8) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{5.377cm}{x{2.33919 cm} x{2.63781 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Dealing with Strings (cont)}} \tn % Row 8 \SetRowColor{LightBackground} \textbackslash{}n & Prints to a new line in a string \tn % Row Count 2 (+ 2) % Row 9 \SetRowColor{white} """ String \textbackslash{}n string \textbackslash{}n string """ & Multiline strings, using three double quotes on each side of the text \tn % Row Count 6 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Strings:}} Strings are used to represent a sequence of characters, such as: names, addresses, general text etc. They are written in double quotes. \newline {\bf{Slicing:}} The the substring starts at index1 but the last character is at index2-1. The indexes given must both be ints. \newline {\bf{Slicing:}} If either start or end expression is missing, then the start or the end of the string is used. \newline {\bf{Other:}} Not an exhausted list of functions, other useful ones include strip(), count(), find() and split() etc.} \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}{Searching}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Simple searching: \newline % Row Count 1 (+ 1) `wanted\_value in list\_name` - tests for list membership \newline % Row Count 3 (+ 2) \seqsplit{`list\_name.index(wanted\_value)`} - to find the position \newline % Row Count 5 (+ 2) Linear search: \newline % Row Count 6 (+ 1) `for i in range(len(list\_name))` \newline % Row Count 7 (+ 1) `. if list\_name{[}i{]} == wanted\_value:` \newline % Row Count 8 (+ 1) `. . return i` \newline % Row Count 9 (+ 1) `return None` \newline % Row Count 10 (+ 1) Binary search: \newline % Row Count 11 (+ 1) `low = 0` \newline % Row Count 12 (+ 1) `high = len(list\_name) - 1` \newline % Row Count 13 (+ 1) `while low \textless{}= high:` \newline % Row Count 14 (+ 1) `. mid = (low + high) // 2` \newline % Row Count 15 (+ 1) `. item = list\_name{[}mid{]}` \newline % Row Count 16 (+ 1) `. if wanted\_value == item:` \newline % Row Count 17 (+ 1) `. . return mid` \newline % Row Count 18 (+ 1) `. if wanted\_value \textless{} item:` \newline % Row Count 19 (+ 1) `. . high = mid - 1` \newline % Row Count 20 (+ 1) `. if wanted\_value \textgreater{} item:` \newline % Row Count 21 (+ 1) `. . low = mid + 1` \newline % Row Count 22 (+ 1) `return None`% Row Count 23 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Simple searching:}} The problem with this is that the index method raises an exception if the sought item is not present. \newline {\bf{Linear search:}} As soon as a value is encountered that is greater than the target value, the linear search can be stopped without looking at the rest of the data. \newline {\bf{Binary search:}} If the data is already sorted, at each step divide the remaining group of numbers into two parts and ignore the irrelevant one} \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}{Dealing with tuples}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Ex. \newline (value1, value2, value3, {\emph{etc.}}) \newline \newline Sorting by element: \newline list\_name.sort(key=lambda x:x{[}element\_index{]})} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Tuple:}} A sequence which looks like a list but uses () rather than {[}{]}. They are immutable, so are used to represent sequences that are not supposed to change. \newline {\bf{Lambda function:}} A small anonymous function which can take any number of arguments, but can only have one expression.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} x{4.4793 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Arithmetic operators}} \tn % Row 0 \SetRowColor{LightBackground} + & Addition - adds together two values. \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} - & Subtraction - subtracts one value from another. \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} * & Multiplication - multiplies two values together. \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} / & Floating point division - divides one value by another. The return value is exact (for floating point) \tn % Row Count 8 (+ 3) % Row 4 \SetRowColor{LightBackground} // & Integer/Floor division - divides one value by another. The remainder is truncated. \tn % Row Count 11 (+ 3) % Row 5 \SetRowColor{white} ** & Exponentiation - raises a number to the power of another number. \tn % Row Count 13 (+ 2) % Row 6 \SetRowColor{LightBackground} \% & Modulus - returns the remainder of dividing a number with another number. \tn % Row Count 16 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Arithmetic operators:}} Used to perform common mathematical operations. \newline {\bf{Precedence:}} Precedence and associativity are as normal as in maths.} \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}{Comments}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Single line comments: \newline % Row Count 1 (+ 1) `\# Comment1` \newline % Row Count 2 (+ 1) `{\emph{code}} \# Comment2` \newline % Row Count 3 (+ 1) Multi-line comments: \newline % Row Count 4 (+ 1) `"""` \newline % Row Count 5 (+ 1) `Comment` \newline % Row Count 6 (+ 1) `Continuing comment` \newline % Row Count 7 (+ 1) `"""`% Row Count 8 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Comments}}: Comments are ignored by the computer, they exist simply to make the code easier for people to understand.} \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}{Dealing with lists}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Creating a list (ex.): \newline % Row Count 1 (+ 1) `list\_name = {[}1, "Spam", 3.142, True{]}` \newline % Row Count 2 (+ 1) `months = {[}"Jan", "Feb", "mar", "apr", ...{\emph{etc.}}{]}` \newline % Row Count 4 (+ 2) Indexing/slicing lists: \newline % Row Count 5 (+ 1) list\_name{[}index{]} OR \newline % Row Count 6 (+ 1) list\_name{[}index1: index2{]} \newline % Row Count 7 (+ 1) Some methods: \newline % Row Count 8 (+ 1) \seqsplit{`list\_name.append(new\_item)`} \newline % Row Count 9 (+ 1) `list.index(object)` (returns index of first occurence) \newline % Row Count 11 (+ 2) `list\_name.min()` and `list\_name.max()` \newline % Row Count 12 (+ 1) `list\_name.reverse()` \newline % Row Count 13 (+ 1) `len(list\_name)` \newline % Row Count 14 (+ 1) `list\_1 + list2` \newline % Row Count 15 (+ 1) `var in list\_name: {\emph{etc.}}` \newline % Row Count 16 (+ 1) `list\_name.sort()` \newline % Row Count 17 (+ 1) \seqsplit{`list\_name.remove(object\_to\_remove)`} \newline % Row Count 18 (+ 1) `list\_name.pop(index)`% Row Count 19 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Lists:}} Lists are sequences of arbitrary values enclosed in square brackets. They can hold any datatype. \newline {\bf{Mutable:}} Lists are mutable, meaning they can be changed. Strings can not be changed. \newline {\bf{Note:}} Not an exhaustive list \newline {\emph{TBC check}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.54747 cm} x{4.42953 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Numeric data types}} \tn % Row 0 \SetRowColor{LightBackground} int & Represents whole numbers/integers. Can be positive or negative \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} float & Represents numbers that can have fractional parts - floating point values. (Even if the fractional part is 0) \tn % Row Count 6 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Note}}: The float type stores only an approximation to the real number being represented. \newline {\bf{Note:}} Operations on ints produce ints (excluding /), operations on floats produce floats. \newline {\bf{Type conversion:}} Combining an int with a float in an expression will return a float. And we can use the int and round functions to explicitly convert between different types. Converting a float to an int will truncate. \newline {\bf{Type:}} We can use the type function to find the data type.} \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}{General if -elif-else-statements}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{if {\emph{boolean\_condition}}: \newline {\emph{statements to execute if condition is True}} \newline elif {\bf{boolean\_conditino}}: \newline {\emph{do these statements if the if-statement and elif}} \newline {\emph{-statements above returned False,}} \newline {\emph{but the test for this statement returned True.}} \newline else: \newline {\emph{do these statements if none of the above tests returned True.}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{if statements:}} The condition statement is evaluated and if it evaluates to True, the indented statements in the body are executed; otherwise, execution proceeds to next statement. \newline {\bf{Note:}} Don't forget the colon!} \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}{General while loops}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{while {\emph{boolean\_condition}}: \newline {\emph{code body}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{While loop:}} A form of indefinite/conditional interation loop. It keeps iterating until the boolean condition is no longer true.} \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}{Break statement}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\emph{loop decl}}: \newline {\emph{code body etc.}} \newline if boolean\_condition: \newline break \newline {\emph{code body etc.}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Break statement:}} Executing break cases Python to immediately exit the enclosing loop. \newline {\bf{Note:}} It is sometimes used to exit what looks like an infinite loop. \newline {\bf{Loop and a half:}} The loop exit is in the middle of the loop body. It is an elegant way to avoid the priming read in a sentinel loop. \newline {\bf{Note:}} Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits.} \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}{Continue statement}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\emph{loop decl}}: \newline {\emph{code body etc.}} \newline if boolean\_condition: \newline continue \newline {\emph{code body etc.}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Continue statement:}} Returns the control to the beginning of the loop escaping the rest of the code body.} \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}{Recursion}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{def rec\_func(n): \newline if {\emph{base\_case\_condition}}: \newline return value \newline else: \newline return computation * rec\_func(n\_closertobc)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Recursion:}} A description of something that refers to itself is called a recursive definition. \newline {\bf{Base case:}} Recursion is not circular because we eventually get to the base case that has a closed expression that can be directly computed.} \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}{Dealing with dictionaries}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Creating dictionaries: \newline % Row Count 1 (+ 1) `dict\_name = \{\}` \newline % Row Count 2 (+ 1) `dict\_name = \{key1:value1, key2:value2, key3...{\emph{etc.}}\}` \newline % Row Count 4 (+ 2) \seqsplit{Adding/initialising/changing} key-value pairs: \newline % Row Count 5 (+ 1) `dict\_name{[}key{]} = new\_value` \newline % Row Count 6 (+ 1) Getting objects from keys: \newline % Row Count 7 (+ 1) `dict\_name{[}key{]}` (if the dictionary does not have the key an exception is raised \newline % Row Count 9 (+ 2) Some functions/operations: \newline % Row Count 10 (+ 1) `key in dict\_name` to check if the key exists \newline % Row Count 11 (+ 1) `del dict\_name{[}key{]}` to delete the entry corresponding to the key \newline % Row Count 13 (+ 2) `dict\_name.pop(key)` to delete the entry and return the value \newline % Row Count 15 (+ 2) `dict\_name.clear()` to delete all entries in the dictionary \newline % Row Count 17 (+ 2) `dict\_name.keys()` to return all the key values only \newline % Row Count 19 (+ 2) `dict\_name.items()` to return tuples of all the key-value pairs \newline % Row Count 21 (+ 2) `dict\_name.values()` to return all the values only \newline % Row Count 23 (+ 2) `dict\_name.get(key, default)` if dictionary has the key return its value, otherwise returns default \newline % Row Count 25 (+ 2) \seqsplit{`dict\_name.setdefault(key}, value)` if dictionary has the key do nothing, otherwise set it to value% Row Count 27 (+ 2) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Dictionary:}} Widely used collection/compound data type. Allows us to look up information associated with arbitrary keys (mapping) \newline {\bf{Note:}} The order of the keys won't matter.} \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}{String formatting}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{"index : width.precision,type".format({\emph{text}}) \newline \newline Ex. \newline "Count \{0:0.20f\}".format(3.14) \newline -\textgreater{} 'Count 3.1400000000000001243'} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Meanings:}} index - which parameter to insert into the slot; width tells us how many spaces to use to display the value; 0 means to use as much space as necessary; precision is the number of decimal places \newline {\bf{Fixed point numbers:}} Denoted using f in the example.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} x{4.4793 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Logical/Boolean operators}} \tn % Row 0 \SetRowColor{LightBackground} not & Inverse the comparison result \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} and & Returns True only if both inputs are True \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} or & Returns True if at least one input is True \tn % Row Count 5 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Precedence:}} The interpretation of the expressions relies on the precedence rules for the operators.} \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}{Range function}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{`range(stop)` (starts from 0 and goes up 1 until (stop - 1)) \newline % Row Count 2 (+ 2) `range(start, stop)` starts from start and goes up 1 until (stop - 1)) \newline % Row Count 4 (+ 2) `range(start, stop, step)` starts from start and goes by step (positive or negative) until (stop - 1) \newline % Row Count 7 (+ 3) `list(range(...))` makes a list% Row Count 8 (+ 1) } \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}{Importing modules}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Importing: \newline % Row Count 1 (+ 1) `import module\_name` OR \newline % Row Count 2 (+ 1) `import module\_name as new\_name` \newline % Row Count 3 (+ 1) `from module\_name import function1` \newline % Row Count 4 (+ 1) Calling functions: \newline % Row Count 5 (+ 1) \seqsplit{`module\_name.function\_name(...)`} \newline % Row Count 6 (+ 1) \seqsplit{`new\_name.function\_name(...)`} \newline % Row Count 7 (+ 1) `function1(...)`% Row Count 8 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Module:}} A file consisting of Python code which can define functions, classes, variables and may also include runnable code. \newline {\bf{Note:}} When Python imports a module, it executes each line. Modules need to be imported in a session only once. \newline {\bf{Library}}: A library is a module with some useful definitions/functions.} \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}{Defining a function}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{def func\_name(): \newline {\emph{code body}} \newline \newline def func\_name(paramname1, paramname2 etc.): \newline {\emph{code body}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Function:}} A function is a block of organised, reusable code that is used to perform a single, related action. It is invoked or executed by typing its name. \newline {\bf{Parameters:}} Parameters can be used to customise the output of a function. A function that has parameters requires arguments. If that parameter is not specified an error is returned.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{p{0.4977 cm} x{4.4793 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Relational/Comparison operators}} \tn % Row 0 \SetRowColor{LightBackground} == & Equal to \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} != & Not equal to \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \textless{} & Less than \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \textless{}= & Less than or equal to \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \textgreater{} & Greater than \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} \textgreater{}= & Greater than or equal to \tn % Row Count 6 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Relational operators:}} Operators used to compare two values - usually numbers, but also sometimes other types. \newline {\bf{Precedence:}} All have lower precedence than all arithmetic operators, and higher than all logical operators.} \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}{File processing}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{Opening files: \newline % Row Count 1 (+ 1) `file\_var = open (file\_name, mode)` (mode - 'r' (read), 'w' (write), or 'a' (append)) OR \newline % Row Count 3 (+ 2) `with open(file\_name) as file\_var: {\emph{processing}}` (when statements in that block have finished running, file will close automatically) \newline % Row Count 6 (+ 3) File methods: \newline % Row Count 7 (+ 1) `file.read()` - returns entire remaining contents as single string \newline % Row Count 9 (+ 2) `file.readline()` - returns next line of file. All text up to and including next newline character \newline % Row Count 11 (+ 2) `file.readlines()` - returns list of remaining lines in file. Each list item is single line including newline characters \newline % Row Count 14 (+ 3) Efficient processing: \newline % Row Count 15 (+ 1) `for line in infile: {\emph{processing}}`% Row Count 16 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{File:}} A sequence of data that is stored in secondary memory (disk drive). They can contain any data type, and usually contains more than one line of text. \newline {\bf{Note:}} When you've finished working with a file, it needs to be closed. In some cases, not properly closing a file could result in data loss. \newline {\bf{Note:}} Multiple calls to readline() is inefficient. \newline {\bf{Note:}} May use writelines() for writing sequence(list) of strings.} \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}{Exception handling}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{try: \newline {\emph{code body}} \newline except ErrorType: \newline {\emph{handler code}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Try-except:}} When python encounters a try statement, it attempts to execute the try body. If an exception is raised, the handler is executed. If not, control passes to the statement after. \newline {\bf{Note:}} There can be multiple except blocks. This acts like 'elif'. \newline {\bf{Except:}} A bare except acts like an 'else' and catches any errors without a specific exception type. \newline {\bf{Note:}} Exceptions are intended for exceptional circumstances and should not be used as a substitute for if statements.} \tn \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}{PseudoRandom numbers}} \tn % Row 0 \SetRowColor{LightBackground} randrange(start, stop, step) & Randomly selects an integer value from a range. range() rules apply. \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \seqsplit{choice(list\_name)} & Chooses a random member of a given list. \tn % Row Count 5 (+ 2) % Row 2 \SetRowColor{LightBackground} random() & Returns a random number in the range {[}0...1.0). (0 can be returned but not 1.0)) \tn % Row Count 9 (+ 4) % Row 3 \SetRowColor{white} seed() & Assign the random number generator a fixed starting point (to give reproducible behaviour during testing) \tn % Row Count 14 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{{\bf{Pseudorandom number generator}}: Starts with a seed value to produce a "random" output. The next time a random number is required, the current value is fed back into the function to produce a new number. \newline {\bf{Note:}} This sequence of numbers appears to be random, but if you start the process over again with the same seed number, you'll get the same sequence of "random" numbers.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}