%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Python Cheatsheet (ver. 1.0)
% --Brad Sturt
% 	
%	The following is meant to be used as reference for individuals who already have some experience coding 
% 		with Python Programming Language. It is organized by common themes, but there is plenty more 
%		that could be added to each theme. Please visit www.python.org for more detailed documentation.
%		Additionally, this reference is based heavily on "Learning Python" by Mark Lutz. I highly recommend
%		it to anyone who is interested in learning Python throughly.
%	
%	Note: This code may look off, depending on the text editor your using to look at it. I used a GUI LaTeX
%		program to write the code (TeXworks for Windows, specifically). Sorry for any hassles this may
%		cause
%
%	Questions or comments? Please email me at sturt1@illinois.edu.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Latex headers and command declarations
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass{article}

\usepackage{hyperref}

% Adjust margins
\addtolength{\oddsidemargin}{-0.575in}
\addtolength{\evensidemargin}{0.575in}
\addtolength{\textwidth}{1.5in}
\addtolength{\topmargin}{-.95in}
\addtolength{\textheight}{0.75in}

% Custom commands

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Main Document
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

% Create title
\title{Python Cheatsheet}
\author{Brad Sturt}
\date{\today}

\maketitle

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Introduction
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Introduction}

\par The following is meant to be used as reference for individuals who already have some experience coding with Python Programming Language. It is organized by common themes, but there is plenty more that could be added to each theme. Please visit \url{www.python.org} for more detailed documentation. Additionally, this reference is based heavily on ``Learning Python" by Mark Lutz. I highly recommend it to anyone who is interested in learning Python throughly.

Python is a programming language that deserves a pretty good introduction. But in the interest of time, I am skipping that and going right to the info you want to reference. The sections are ordered by \textbf{Object Types}, \textbf{Loops}, \textbf{Functions}, and \textbf{Classes}.

\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Object Types
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Object Types}
\par There are 6 primitives (objects built into the language) that should be mentioned. They are:
\begin{itemize}
	\item Integers
	\item Strings
	\item Lists
	\item Dictionaries
	\item Tuples
	\item Files
\end{itemize}

%	---------------------------------------------------------------------------------------------------------------------------
	% Integers
	\subsection{Integers}
	\begin{description}
	
		\item[Numeric Literals:] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l }
			Integers: & -5, 24, 0 \\
			Floating Points: & 1.23, 1.23e-20, -1.23E210 \\
			Octal: & 0177, 0011 \\
			Hexadecimal: & 0xFF, 0x3E89 \\
			Complex: & 3+4j, 0+.4j 
		\end{tabular} 
		\end{center}

		\item[Converting Types Manually:] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l }
			int(3.141) & becomes 3 \\
			float(3) & becomes 3.0 \\
			oct(64) & becomes 0100 \\
			hex(64) & becomes 0x40
		\end{tabular}
		\end{center}
		
		\item[math Module] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l }
			math.pi & math.sqrt() & math.e \\ 
			math.sin() & math.cos() & math.sin() \\ 
		\end{tabular}
		\end{center}
		
		\item[random Module:] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l }
			random.random() & returns a random number in [0, 1) \\
			random.randint(1, 10) & returns a random number in [1, 10) \\
			random.choice([1, Hello Math 198 Student", {'Goodbye': 42}]) & random item in list
		\end{tabular}
		\end{center}
		
		\item[Operations: ] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l}
			Operation & What it returns \\
			\hline
			123 + 122 & 145 \\
			1.5 * 4 & 6.0 \\
			2 ** 4 & 16 \\
			4 / 3 & 1 (note the rounding) \\
			3.0 / 2 & 1.5
		\end{tabular}
		\end{center}
	\end{description}

%	---------------------------------------------------------------------------------------------------------------------------
	% Strings
	% Note to reader: This section was coded a while ago. It uses a different Latex structure than
	% the other sections. Sorry for any confusion.
	\subsection{Strings}
	\begin{description}
	
		\item[String Examples] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l c }
			Type These In & This Returns & This Is Called & \\ \hline
			s = ``spam's''                  &                                   & Double quotes            & \\	
			'Hello' + ' world'             &  'Hello world'                     & Concatenation            & \\
			'Hello' * 3                    &      'HelloHelloHello'                   & Repeat                   & \\ 
			s = 'Spam'                     &                                   & & \\
			s[2]                           &      'a'                   & Returns the character at index 2          & \\ 
			s[-1]           & 'm'                    & Returns the character at (-1 + 4) = 3rd index      & \\ 
			s[1:4]                         & 'pam'             & Slice (returns characters at indexes [1, 4) & \\	
			s[2:]                          &  'am'                                & Slice (returns characters at index 2 and on)     & \\
			s[:2]                          &  'Sp'                                 & Slice (returns characters from inexes [0, 2)  & \\
			s[0:3:2]                       & 'Sa'                                  & Slice (returns every other (2) letters from indexes [0, 3) ) & \\
			len(s)                         &   4                & Length                   & \\
			word =       &                                   & String Formatting        & \\
			``Hypergraphics" & & & \\
			``Hello \%s" \% word"     &    'Hello Hypergraphics'                               &                          & \\
		\end{tabular} 
		\end{center}
		
		\item[String Methods] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l }
			S.capitalize() & S.center(width) & S.count(sub [, start [, end]]) \\
			S.encode([encoding [,errors]]) & S.endswith(suffix [, start [, end]]) & S.expandtabs([tabsize]) \\
			S.find(sub [, start [, end]]) & S.index(sub [, start [, end]]) & S.isalnum() \\
			S.isalpha() & S.isdigit() & S.islower() \\
			S.isspace() & S.istitle() & S.isupper() \\
			S.join(seq) & S.ljust(width) & S.lower() \\
			S.lstrip() & S.replace(old, new [, maxsplit]) & S.rfind(sub [, start [, end]]) \\
			S.rindex(sub [, start [, end]]) & S.rjust(width) & S.rstrip() \\
			S.split([sep [, maxsplit]]) & S.splitlines([keepends]) & S.startswith(prefix [, start [, end]]) \\
			S.strip() & S.swapcase() & S.title() \\
			S.translate(table [, delchars]) & S.upper() & \\
		\end{tabular} 
		\end{center}

		\item[String Backslash Characters] \hfill
		\begin{center}
		\begin{tabular}[t]{ l c c }
			\textbackslash newline         & Ignored (continuation)             & \\ 
			\textbackslash \textbackslash  & Backslash (keeps a \textbackslash) & \\
			\textbackslash '               & Single quote (keeps ')             & \\ 
			\textbackslash "               & Double quote (keeps ")             & \\ 
			\textbackslash a               & Bell                               & \\ 
			\textbackslash b               & Backspace                          & \\ 
			\textbackslash f               & Formfeed                           & \\ 
			\textbackslash n               & Newline (linefeed)                 & \\ 
			\textbackslash r               & Carriage Return                    & \\
			\textbackslash t               & Horizontal tab                     & \\
			\textbackslash v               & Verticle tab                       & \\
			\textbackslash xhh             & Hex digits value                   & \\ 
			\textbackslash ooo             & Octal digits value                 & \\
			\textbackslash 0               & Null (doesn't end string)          & \\ 
		\end{tabular}
		\end{center}	
	\end{description}

%	---------------------------------------------------------------------------------------------------------------------------
	% Lists
	\subsection{Lists}
	\begin{description}
	
		\item[List Examples] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l }
			Types These In & This Returns & This Is Called \\ \hline
			l1 = [] & & Empty List \\
			l2 = ['Francis', [42, 'Hypergraphics']] & & Nested lists \\
			l2[0] & 'Francis' & Returns item at index 0 \\
			l2[1] & [42, 'Hypergraphics'] & Returns item at index 1 \\
			l2[1][0] & 'Hypergraphics' & Returns item at index \\
			& & 1's 0th index \\
			l2[0, 2] & ['Francis', [42, 'Hypergraphics']] & Slice list from indexes [0, 2) \\
			L2 = L2 + [1] & ['Francis', [42, 'Hypergraphics'], 198, 1] & Concatanate lists \\
			L1 = [1, 2, 3] & & \\
			L1 * 3 & [1, 2, 3, 1, 2, 3, 1, 2, 3] & Repeat\\
		\end{tabular}
		\end{center}
		
		\item[List Methods] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l }
			Types These In & This Returns & This Is Called \\ \hline
			myList = [1, 2] & & \\
			len(myList) & 2 & Number of entries in list \\
			myList.append('1a2b') & & Sets myList to \\ 
			& & [1, 2, '1a2b'] \\
			myList.extend([3, 4]) & & Sets myList to \\
			& & [1, 2, '1a2b', 3, 4] \\
			myList.sort() & & Sorts L2 by ASCII characters \\
			myList.insert(2, 'Interrupting') & & Inserts 'Interrupting'\\
			& & into the 2nd index. Everything \\
			& & in the list after gets pushed back \\
			myList.index(2) & '1a2b' & another way of saying L2[2] \\
			myList.reverse() & & Reverse list \\
			myList.pop() & 4 & Removes last item and returns it \\
			myList.remove('1a2b') & & Removes '1a2b' from list \\
		\end{tabular}
		\end{center}
	\end{description}
	
%	---------------------------------------------------------------------------------------------------------------------------
	% Tuples
	\subsection{Tuples}
	Tuples are virtually identitical to lists, with one major difference. Tuples cannot be changed. No items can be removed or added to the tuple. If you want to do so, you must make a new tuple that will store the new changes. So why do they exist? Since they are \textit{immutable}, they require less resources of your computer so they can be created faster and in greater numbers. Also, if you are just trying to store information without changing that information, tuples just make more sense. Tuples use () instead of list's [].

%	---------------------------------------------------------------------------------------------------------------------------
	% Dictionaries
	\subsection{Dictionaries}
	\begin{description}
	
		\item[Dictionary Examples] \hfill
		\begin{center}
		\begin{tabular}[t]{ l l l }
			Type These In & This Returns & This Is Called \\ \hline
			myDict = \{'foo': 4, 'bar': 2\} & & A dictionary! \\
			myDict['foo'] & 4 & Fetch value with key 'foo' \\
			myDict['Francis'] = & & Add key:value to dictionary \\
			\verb+['Math', 'Programmer']+ & & \\
			len(myDict) & 3 & Length \\
			\verb+myDict.has_key('Brad')+ & False & does myDict have key 'Brad' \\
			myDict.keys() & ['foo', 'bar', 'Francis'] & returns list of keys \\
			myDict.values() & [4, 2, ['Math', 'Programmer']] & returns list of values \\
			myDict.items() & [('foo', 4), ('bar', 2), & returns dictionary as \\
			& ('Francis', ['Math', 'Programmer'])] & a list of tuples for each item \\
			myDict.get('foo') & 4 & same as myDict['foo'] \\
		\end{tabular}
		\end{center}
	\end{description}

%	---------------------------------------------------------------------------------------------------------------------------
	% Files
	\subsection{Files}
	If you have used C/C++ for working with files, you will find the syntax here to be very similar. If you haven't, no worries.
	\begin{enumerate}
	
		\item Write to a new file:
		\begin{center}
		\begin{tabular}[t]{ l l }
			\verb+f = open('myfile.txt', 'w')+ & open file to write \\
			\verb+f.write('Hello \n')+ & write a string to buffer \\
			\verb+f.writelines(['Hello', 'Programmer'])+ & write lines of strings \\
			& from a list to buffer \\
			f.close() & flush buffer to disk, or, \\
			& in English, \textit{save the file} \\
		\end{tabular}
		\end{center}
		
		\item Read from an existing file:
		\begin{center}
		\begin{tabular}[t]{ l l }
			\verb+f = open('myfile.txt', 'r')+ & open file to read \\
			myString = f.read() & read entire file to myString \\
			myString = f.read(10) & read next 10 characters \\
			myString = f.readline() & read next line \\
			myList = f.readlines() & read entire file into list\\
			& of strings \\
		\end{tabular}
		\end{center}
		
		\item pickle Module:
		\begin{description}
			\item[What is it:] pickle is a module that writes objects to a file and retrieve it from the file kinda easily
		\end{description}
		\begin{enumerate}
			
			\item Pickle object to file:
			\begin{center}
			\begin{tabular}[t]{ l l }
				\verb+myFile = open('myfile.txt', 'w')+ & open file to write \\
				import pickle & import pickle module \\
				pickle.dump(someObject, myFile) & pickle someObject to myFile \\
				pickle.close() & flush buffer to disk \\
			\end{tabular}
			\end{center}
			
			\item Load object from file
			\begin{center}
			\begin{tabular}[t]{ l l }
				\verb+myFile = open('myfile.txt', 'r')+ & open file to write \\
				import pickle & import pickle module \\
				obj = pickle.load(myFile) & retrieve someObject from myFile and \\
				& store it to obj \\
				pickle.close() & flush buffer to disk \\
			\end{tabular}
			\end{center}
			
		\end{enumerate}
		\begin{description}
			\item[What are the alternatives:] Check out the shelve module for a pickle-like parsing-alternative with indexing. For databases, check out ZODB module. Python also can script with SQL.
		\end{description}

	\end{enumerate}


\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Loops
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Loops and Other Statements}

These loops and statements are found commonly in code. In here are:
\begin{itemize}
	\item for Loops
	\item if/elif/else Loops
	\item Miscellaneous
\end{itemize}

%	---------------------------------------------------------------------------------------------------------------------------
	% for loops
	\subsection{for Loops}
	\begin{verbatim}
	for <target> in <object>: # for each <target> in <object>
		something # note the indent
	
	Example:
	for i in range(10): # for each i in [0, 1, ..., 9]
		print i ** 2
	
	Output:
	0
	1
	4
	9
	16
	25
	36
	49
	64
	81
	
	What did this do? It did
		i = 0: print i ** 2
		i  = 1: print i ** 2
		...
		i = 9: print i ** 2
	
	Example: 
	for char in 'I love Hypergraphics':
		print char, # the comma means not to skip a line
		print ' ',
	
	Output:
	I   l o v e   H y p e r g r a p h i c s 
	\end{verbatim}
%	---------------------------------------------------------------------------------------------------------------------------
	% if/elif/else loops
	\subsection{if/elif/else Loops}
	\begin{verbatim}
	if <True or False expression>: # if expression in <> is true
		something # do what is indented below it
	
	Example:
	if 1 < 2:
		print 3
	
	Output:
	3
	
	Example:
	if 1>2:
		print 3
	else:
		print 4

	Output:
	4
	
	Example:
	x = 1
	y = 2
	if x < y:
		print 'x < y'
	elif x == y: # else, if x has the same value as y...
		print 'x equals y'
	else:
		print 'x > y'
	
	Output:
	x < y
	
	\end{verbatim}

%	---------------------------------------------------------------------------------------------------------------------------
	% Miscellaneous
	\subsection{Miscellaneous}

	\begin{center}
	\begin{tabular}[t]{ l l l }
		x or y & x and y & not x \\
		& & \\
		zip(['a', 'b', 'c'], [1, 2, 3]) & returns [('a', 1), ('b', 2), ('c', 3)] & zip function \\
		dict( [('a', 1), ('b', 2), ('c', 3)] ) & returns \{'a':1, 'b':2, 'c':3\} & dict function \\
		range(5) & returns [0, 1, 2, 3, 4] & range function \\
	\end{tabular} 
	\end{center}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Functions and Classes
% 
%
% Don't have Latex code for those sections. If I come across my old ones, I will add it.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{document}




