day2/cheatsheet3.tex
author Shantanu <shantanu@fossee.in>
Wed, 25 Nov 2009 12:11:03 +0530
changeset 327 c78cad28c2f7
parent 301 49bdffe4dca5
child 329 0a6ab1d81491
permissions -rw-r--r--
modifeid cheat sheets for session 3, 4 day 2.

\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: Functions and Objects}\\
\large{FOSSEE}
\end{center}
\section{Function}
They allows us to enclose a set of statements and call the function again and again instead of repeating the group of statements every-time. 
\subsection{Function definition}
  \begin{lstlisting}
def signum( r ):    
    if r < 0:
        return -1
    elif r > 0:
        return 1
    else:
        return 0
  \end{lstlisting}
%\typ{def} is a keyword, which is used to define a function with given name.
\subsection{Usage}
\begin{lstlisting}
In []: signum(4)
Out[]: 1
In []: signum(0)
Out[]: 0
In []: signum(-4)
Out[]: -1
In []: signum() # ERROR signum() takes exactly 1 argument(0 given)
\end{lstlisting}
\textbf{Note:} Arguments passed to a function are passed by-value \textbf{only if} they are basic Python data type(int, float). In case one pass immutable types(String, tupels), they cant be modified in the function, but objects like \typ{list} and dictionary can be manipulated.
\subsection{Default Arguments}
This feature allow the functions to take the arguments optionally. For example:
\begin{lstlisting}
In []: greet = 'hello world'

In []: greet.split()
Out[]: ['hello', 'world']
\end{lstlisting}
In above case, default argument which \typ{split} function uses is a blank space. One can pass argument also, to split the string for a different delimiter.
\begin{lstlisting}
In []: line = 'Rossum, Guido, 54, 46, 55'

In []: line.split(',') #split with ','
Out[]: ['Rossum', ' Guido', ' 54',
                        ' 46', ' 55']
\end{lstlisting}
Function to work with default argument can be defined as:
\begin{lstlisting}
def welcome(greet, name='world!'):
  print greet, name
\end{lstlisting}
above function can be used as:
\begin{lstlisting}
In []: welcome("Hello") #using default argument
Hello World!
In []: welcome("Hi", "Guido") #taking name via argument
Hi Guido
\end{lstlisting}
\subsection{Keyword Arguments}
This feature provides the facility of passing arguments by specifying the name of the parameter as defined in the function definition. You dont have to remember the order of the parameters in function definition. For example:
\begin{lstlisting}
In []: plot(y, sin(y), 'g', linewidth=2)
In []: plot(y, cos(y), linewidth=1, color='g')
\end{lstlisting}
Both call to \typ{plot} function will work and paramenters are set accordingly.\\
One can define a function such that keyword arguments can be used in following way:
\begin{lstlisting}
def wish(name='World', greetings='Hello'):
  print greetings, name
\end{lstlisting}
This function can be called as:
\begin{lstlisting}
In [13]: wish() #default arguments will work
Hello World
In [14]: wish(greetings='hey', name='madhu')
hey madhu
In [15]: wish(name='vattam', greetings = 'get lost')
get lost vattam
\end{lstlisting}
\section{Self contained python script}
Functions like \typ{plot}, \typ{linspace} etc are not inbuilt functions. One have to import them to use them.
  \begin{lstlisting}
from scipy import linspace, pi, sin
from pylab import plot, legend, annotate
from pylab import xlim, ylim

x = linspace(-5*pi, 5*pi, 500)
plot(x, x, 'b')
plot(x, -x, 'b')
plot(x, sin(x), 'g', linewidth=2)
plot(x, x*sin(x), 'r', linewidth=3)
legend(['x', '-x', 'sin(x)', 'xsin(x)'])
annotate('origin', xy = (0, 0))
xlim(-5*pi, 5*pi)
ylim(-5*pi, 5*pi)
  \end{lstlisting}
Above mentioned code will work with following setup:
\begin{lstlisting}
$ ipython -pylab
In []: %run -i sine_plot.py
\end{lstlisting} %$
as we are already including \typ{pylab} into \typ{ipython}. But to make it work independently so that even\\
\typ{$ python sine_plot.py} \\ %$ 
works, one will have to use \typ{import} statements.\\
\section{objects}
In Python everything is a object! All variables, lists, tuples, dictionaries and even functions are objects. 
\begin{lstlisting}
In []: a = str() 
In []: b = "Hello World"
In []: b.split()
Out[]: ['Hello', 'World']
\end{lstlisting}
``.'' is a operator used to call functions defined for given object.
\section{Links and References}
\begin{itemize}
\item Some of inbult functions available with Python are listed at\\ \url{http://docs.python.org/library/functions.html}
\item Reference manual to describe the standard libraries  that are distributed with Python is available at \url{http://docs.python.org/library/} 
\end{itemize}
\end{document}