day2/cheatsheet4.tex
changeset 334 2214b5dba4d4
parent 329 0a6ab1d81491
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/day2/cheatsheet4.tex	Tue Dec 29 19:25:11 2009 +0530
@@ -0,0 +1,75 @@
+\documentclass[12pt]{article}
+
+
+\title{Python: Data Structures}
+\author{FOSSEE}
+\usepackage{listings}
+\lstset{language=Python,
+    basicstyle=\ttfamily,
+commentstyle=\itshape\bfseries, 
+showstringspaces=false
+}
+\newcommand{\typ}[1]{\lstinline{#1}}
+\usepackage[english]{babel}
+\usepackage[latin1]{inputenc}
+\usepackage{times}
+\usepackage[T1]{fontenc}
+\usepackage{ae,aecompl}
+\usepackage{mathpazo,courier,euler}
+\usepackage[scaled=.95]{helvet}
+
+\begin{document}
+\date{}
+\vspace{-1in}
+\begin{center}
+\LARGE{Python Development}\\
+\large{FOSSEE}
+\end{center}
+\section{Module}
+Packages like \typ{scipy}, \typ{pylab} etc we used for functions like \typ{plot}, \typ{linspace} are \textbf{Modules}. They are Python script, which have various functions and objects, which can be imported and reused. 
+\begin{lstlisting}
+def gcd(a, b):
+  if a % b == 0: 
+    return b
+  return gcd(b, a%b)
+
+print gcd(15, 65)
+print gcd(16, 76)
+\end{lstlisting}
+Save above mentioned python script with name 'gcd.py'. Now we can \typ{import} \typ{gcd} function. For example, in same directory create 'lcm.py' with following content:
+\begin{lstlisting}
+from gcd import gcd    
+
+def lcm(a, b):
+  return (a * b) / gcd(a, b)
+    
+print lcm(14, 56)
+\end{lstlisting}
+Here since both gcd.py and lcm.py are in same directory, import statement imports \typ{gcd} function from gcd.py.\\
+When you try to run lcm.py it prints three results, two from gcd.py and third from lcm.py.
+\begin{lstlisting}
+$ python lcm.py
+5
+4
+56
+\end{lstlisting} %$
+\newpage
+We have print statements to make sure \typ{gcd} and \typ{lcm} are working properly. So to suppress output of \typ{gcd} module when imported in lcm.py we use \typ{'__main__'} \
+\begin{lstlisting}
+def gcd(a, b):
+  if a % b == 0: 
+    return b
+  return gcd(b, a%b)
+if __name__ == '__main__':
+  print gcd(15, 65)
+  print gcd(16, 76)
+\end{lstlisting}
+\typ{__main__()} helps to create standalone scripts. Code inside it is only executed when we run gcd.py. Hence
+\begin{lstlisting}
+$ python gcd.py
+5
+4
+$ python lcm.py 
+56
+\end{lstlisting}
+\end{document}