day2/cheatsheet4.tex
changeset 327 c78cad28c2f7
child 329 0a6ab1d81491
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/day2/cheatsheet4.tex	Wed Nov 25 12:11:03 2009 +0530
@@ -0,0 +1,74 @@
+\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: Python Development}\\
+\large{FOSSEE}
+\end{center}
+\section{Module}
+Packages like \typ{scipy}, \typ{pylab} etc we used for functions like \typ{plot} are Modules. Modules are Python script, which have various functions and objects, which if imported can be 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}
+This \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}