day2/session2.tex
changeset 238 1575143284cd
parent 228 238f3010c981
child 239 8953675dc056
equal deleted inserted replaced
237:78ce38a1e383 238:1575143284cd
       
     1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
     2 %Tutorial slides on Python.
       
     3 %
       
     4 % Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in>
       
     5 % Copyright (c) 2005-2009, Prabhu Ramachandran
       
     6 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
     7 
       
     8 \documentclass[14pt,compress]{beamer}
       
     9 %\documentclass[draft]{beamer}
       
    10 %\documentclass[compress,handout]{beamer}
       
    11 %\usepackage{pgfpages} 
       
    12 %\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm]
       
    13 
       
    14 % Modified from: generic-ornate-15min-45min.de.tex
       
    15 \mode<presentation>
       
    16 {
       
    17   \usetheme{Warsaw}
       
    18   \useoutertheme{split}
       
    19   \setbeamercovered{transparent}
       
    20 }
       
    21 
       
    22 \usepackage[english]{babel}
       
    23 \usepackage[latin1]{inputenc}
       
    24 %\usepackage{times}
       
    25 \usepackage[T1]{fontenc}
       
    26 
       
    27 % Taken from Fernando's slides.
       
    28 \usepackage{ae,aecompl}
       
    29 \usepackage{mathpazo,courier,euler}
       
    30 \usepackage[scaled=.95]{helvet}
       
    31 
       
    32 \definecolor{darkgreen}{rgb}{0,0.5,0}
       
    33 
       
    34 \usepackage{listings}
       
    35 \lstset{language=Python,
       
    36     basicstyle=\ttfamily\bfseries,
       
    37     commentstyle=\color{red}\itshape,
       
    38   stringstyle=\color{darkgreen},
       
    39   showstringspaces=false,
       
    40   keywordstyle=\color{blue}\bfseries}
       
    41 
       
    42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    43 % Macros
       
    44 \setbeamercolor{emphbar}{bg=blue!20, fg=black}
       
    45 \newcommand{\emphbar}[1]
       
    46 {\begin{beamercolorbox}[rounded=true]{emphbar} 
       
    47       {#1}
       
    48  \end{beamercolorbox}
       
    49 }
       
    50 \newcounter{time}
       
    51 \setcounter{time}{0}
       
    52 \newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}}
       
    53 
       
    54 \newcommand{\typ}[1]{\texttt{#1}}
       
    55 
       
    56 \newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}}  }
       
    57 
       
    58 %%% This is from Fernando's setup.
       
    59 % \usepackage{color}
       
    60 % \definecolor{orange}{cmyk}{0,0.4,0.8,0.2}
       
    61 % % Use and configure listings package for nicely formatted code
       
    62 % \usepackage{listings}
       
    63 % \lstset{
       
    64 %    language=Python,
       
    65 %    basicstyle=\small\ttfamily,
       
    66 %    commentstyle=\ttfamily\color{blue},
       
    67 %    stringstyle=\ttfamily\color{orange},
       
    68 %    showstringspaces=false,
       
    69 %    breaklines=true,
       
    70 %    postbreak = \space\dots
       
    71 % }
       
    72 
       
    73 
       
    74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    75 % Title page
       
    76 \title[Basic Python]{Python:\\A formal approach}
       
    77 
       
    78 \author[FOSSEE Team] {The FOSSEE Group}
       
    79 
       
    80 \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
       
    81 \date[] {1, November 2009\\Day 2, Session 2}
       
    82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
    83 
       
    84 %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo}
       
    85 %\logo{\pgfuseimage{iitmlogo}}
       
    86 
       
    87 
       
    88 %% Delete this, if you do not want the table of contents to pop up at
       
    89 %% the beginning of each subsection:
       
    90 \AtBeginSubsection[]
       
    91 {
       
    92   \begin{frame}<beamer>
       
    93     \frametitle{Outline}
       
    94     \tableofcontents[currentsection,currentsubsection]
       
    95   \end{frame}
       
    96 }
       
    97 
       
    98 \AtBeginSection[]
       
    99 {
       
   100   \begin{frame}<beamer>
       
   101     \frametitle{Outline}
       
   102     \tableofcontents[currentsection,currentsubsection]
       
   103   \end{frame}
       
   104 }
       
   105 
       
   106 % If you wish to uncover everything in a step-wise fashion, uncomment
       
   107 % the following command: 
       
   108 %\beamerdefaultoverlayspecification{<+->}
       
   109 
       
   110 %\includeonlyframes{current,current1,current2,current3,current4,current5,current6}
       
   111 
       
   112 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
   113 % DOCUMENT STARTS
       
   114 \begin{document}
       
   115 
       
   116 \begin{frame}
       
   117   \titlepage
       
   118 \end{frame}
       
   119 
       
   120 \begin{frame}
       
   121   \frametitle{Outline}
       
   122   \tableofcontents
       
   123   % You might wish to add the option [pausesections]
       
   124 \end{frame}
       
   125 
       
   126 \section{Data structures}
       
   127 \subsection{Lists}
       
   128 \begin{frame}[fragile]
       
   129   \frametitle{Lists}
       
   130 \begin{block}{We already know that}
       
   131   \begin{lstlisting}
       
   132 num = [1, 2, 3, 4, 5, 6, 7, 8]
       
   133   \end{lstlisting}
       
   134 \centerline{is a list}
       
   135 \end{block}
       
   136 \end{frame}
       
   137 
       
   138 \begin{frame}[fragile]
       
   139   \frametitle{Lists: methods}
       
   140   \begin{lstlisting}
       
   141 In []: num.reverse()
       
   142 In []: num
       
   143 Out[]: [8, 7, 6, 5, 4, 3, 2, 1]
       
   144 
       
   145 In []: num.extend([0, -1, -2])
       
   146 In []: num
       
   147 Out[]: [8, 7, 6, 5, 4, 3, 2, 1, 0, -1]
       
   148 
       
   149 In []: num.remove(0)
       
   150 In []: num
       
   151 Out[]: [8, 7, 6, 5, 4, 3, 2, 1, -1]
       
   152   \end{lstlisting}
       
   153 \end{frame}
       
   154 
       
   155 \begin{frame}[fragile]
       
   156 \frametitle{List containership}
       
   157 \begin{lstlisting}
       
   158 In []: a = 8
       
   159 
       
   160 In []: a in num
       
   161 Out[]: True
       
   162 
       
   163 In []: b = 10
       
   164 In []: b in num
       
   165 Out[]: False
       
   166 
       
   167 In []: b not in num
       
   168 Out[]: True
       
   169 \end{lstlisting}
       
   170 \end{frame}
       
   171 
       
   172 \subsection{Tuples}
       
   173 \begin{frame}[fragile]
       
   174 \frametitle{Tuples: Immutable lists}
       
   175 \begin{lstlisting}
       
   176 In []: t = (1, 2, 3, 4, 5, 6, 7, 8)
       
   177 In []: t[0] + t[3] + t[-1]
       
   178 Out[]: 13
       
   179 \end{lstlisting}
       
   180 \begin{block}{Note:}
       
   181 \begin{itemize}
       
   182   \item Tuples are immutable - cannot be changed
       
   183 \end{itemize}
       
   184 \end{block}
       
   185   \inctime{10}
       
   186 \end{frame}
       
   187 
       
   188 \begin{frame}
       
   189   {A classic problem}
       
   190   \begin{block}
       
   191     {Interchange values}
       
   192     How to interchange values of two variables? 
       
   193   \end{block}
       
   194   \pause
       
   195   \begin{block}{Note:}
       
   196     This Python idiom works for all types of variables.\\
       
   197 They need not be of the same type!
       
   198   \end{block}
       
   199 \end{frame}
       
   200 
       
   201 \subsection{Dictionaries}
       
   202 \begin{frame}[fragile]
       
   203   \frametitle{Dictionaries: Recall}
       
   204   \begin{lstlisting}
       
   205 In []: player = {'Mat': 134,'Inn': 233,
       
   206           'Runs': 10823, 'Avg': 52.53}
       
   207 
       
   208 In []: player['Avg']
       
   209 Out[]: 52.530000000000001
       
   210   \end{lstlisting}
       
   211   \begin{block}{Note!}
       
   212     Duplicate keys are not allowed!\\
       
   213     Dictionaries are iterable through keys.
       
   214   \end{block}
       
   215 \end{frame}
       
   216 
       
   217 \begin{frame} {Problem Set 2.1: Problem 2.1.1}
       
   218 You are given date strings of the form ``29, Jul 2009'', or ``4 January 2008''. In other words a number a string and another number, with a comma sometimes separating the items.Write a function that takes such a string and returns a tuple (yyyy, mm, dd) where all three elements are ints.
       
   219 \end{frame}
       
   220 
       
   221 \subsection{Set}
       
   222 \begin{frame}[fragile]
       
   223   \frametitle{Set}
       
   224     \begin{itemize}
       
   225       \item Simplest container, mutable
       
   226       \item No ordering, no duplicates
       
   227       \item usual suspects: union, intersection, subset \ldots
       
   228       \item >, >=, <, <=, in, \ldots
       
   229     \end{itemize}
       
   230     \begin{lstlisting}
       
   231 >>> f10 = set([1,2,3,5,8])
       
   232 >>> p10 = set([2,3,5,7])
       
   233 >>> f10|p10
       
   234 set([1, 2, 3, 5, 7, 8])
       
   235 >>> f10&p10
       
   236 set([2, 3, 5])
       
   237 >>> f10-p10
       
   238 set([8, 1])
       
   239 \end{lstlisting}
       
   240 \end{frame}
       
   241 
       
   242 \begin{frame}[fragile]
       
   243   \frametitle{Set}
       
   244     \begin{lstlisting}
       
   245 >>> p10-f10, f10^p10
       
   246 set([7]), set([1, 7, 8])
       
   247 >>> set([2,3]) < p10
       
   248 True
       
   249 >>> set([2,3]) <= p10
       
   250 True
       
   251 >>> 2 in p10
       
   252 True
       
   253 >>> 4 in p10
       
   254 False
       
   255 >>> len(f10)
       
   256 5
       
   257 \end{lstlisting}
       
   258 \end{frame}
       
   259 
       
   260 \begin{frame}
       
   261   \frametitle{Problem set 2.2}
       
   262   \begin{description}
       
   263     \item[2.2.1] Given a dictionary of the names of students and their marks, identify how many duplicate marks are there? and what are these?
       
   264     \item[2.2.2] Given a string of the form ``4-7, 9, 12, 15'' find the numbers missing in this list for a given range.
       
   265 \end{description}
       
   266 \inctime{15}
       
   267 \end{frame}
       
   268 
       
   269 \section{Functions}
       
   270 \begin{frame}[fragile]
       
   271   \frametitle{Functions}
       
   272   \begin{itemize}
       
   273     \item \kwrd{def} - keyword to define a function
       
   274     \item Arguments are local to a function
       
   275     \item Docstrings are important!
       
   276     \item Functions can return multiple values
       
   277   \end{itemize}
       
   278 \end{frame}
       
   279 
       
   280 \begin{frame}[fragile]
       
   281   \frametitle{Functions: example}
       
   282   \begin{lstlisting}
       
   283 def signum( r ):
       
   284     """returns 0 if r is zero
       
   285     -1 if r is negative
       
   286     +1 if r is positive"""
       
   287     if r < 0:
       
   288         return -1
       
   289     elif r > 0:
       
   290         return 1
       
   291     else:
       
   292         return 0
       
   293   \end{lstlisting}
       
   294 \end{frame}
       
   295 
       
   296 \begin{frame}[fragile]
       
   297   {What does this function do?}
       
   298 \begin{lstlisting}
       
   299 def what( n ):
       
   300     i = 1
       
   301     while i * i < n:
       
   302         i += 1
       
   303     return i * i == n, i
       
   304   \end{lstlisting}
       
   305 \end{frame}
       
   306 
       
   307 \subsection{Default arguments}
       
   308 \begin{frame}[fragile]
       
   309   \frametitle{Functions: default arguments}
       
   310   \small
       
   311   \begin{lstlisting}
       
   312 def ask_ok(prompt, complaint='Yes or no!'):
       
   313     while True:
       
   314         ok = raw_input(prompt)
       
   315         if ok in ('y', 'ye', 'yes'): 
       
   316             return True
       
   317         if ok in ('n', 'no', 'nop',
       
   318                   'nope'): 
       
   319             return False
       
   320         print complaint
       
   321 
       
   322 ask_ok('?')
       
   323 ask_ok('?', '[Y/N]')
       
   324   \end{lstlisting}
       
   325 \end{frame}
       
   326 
       
   327 \subsection{Built-in functions}
       
   328 \begin{frame}
       
   329   {Before writing a function}
       
   330   \begin{itemize}
       
   331       \item Variety of builtin functions are available
       
   332       \item \typ{abs, any, all, len, max, min}
       
   333       \item \typ{pow, range, sum, type}
       
   334       \item Refer here:
       
   335           \url{http://docs.python.org/library/functions.html}
       
   336   \end{itemize}
       
   337   \inctime{10} 
       
   338 \end{frame}
       
   339 
       
   340 \subsection{Exercises}
       
   341 \begin{frame}{Problem set 3: Problem 3.1}
       
   342   Write a function to return the gcd of two numbers.
       
   343 \end{frame}
       
   344 
       
   345 \begin{frame}{Problem 3.2}
       
   346 Write a program to print all primitive pythagorean triads (a, b, c) where a, b are in the range 1---100 \\
       
   347 A pythagorean triad $(a,b,c)$ has the property $a^2 + b^2 = c^2$.\\By primitive we mean triads that do not `depend' on others. For example, (4,3,5) is a variant of (3,4,5) and hence is not primitive. And (10,24,26) is easily derived from (5,12,13) and is also not primitive.
       
   348 \end{frame}
       
   349 
       
   350 \begin{frame}{Problem 3.3}
       
   351   Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\newline\\\emph{For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square).}
       
   352 \inctime{15}
       
   353 \end{frame}
       
   354 
       
   355 \section{Modules}
       
   356 \begin{frame}[fragile]
       
   357     {Modules}
       
   358 \begin{lstlisting}
       
   359 >>> sqrt(2)
       
   360 Traceback (most recent call last):
       
   361   File "<stdin>", line 1, in <module>
       
   362 NameError: name 'sqrt' is not defined
       
   363 >>> import math        
       
   364 >>> math.sqrt(2)
       
   365 1.4142135623730951
       
   366 \end{lstlisting}
       
   367 \end{frame}
       
   368 
       
   369 \begin{frame}[fragile]
       
   370     {Modules}
       
   371   \begin{itemize}
       
   372     \item The \kwrd{import} keyword ``loads'' a module
       
   373     \item One can also use:
       
   374       \begin{lstlisting}
       
   375 >>> from math import sqrt
       
   376 >>> from math import *
       
   377       \end{lstlisting}    
       
   378     \item What is the difference?
       
   379     \item \alert{Use the latter only in interactive mode}
       
   380     \end{itemize}
       
   381   \emphbar{Package hierarchies}
       
   382       \begin{lstlisting}
       
   383 >>> from os.path import exists
       
   384       \end{lstlisting}
       
   385 \end{frame}
       
   386 
       
   387 \begin{frame}
       
   388   \frametitle{Modules: Standard library}
       
   389   \begin{itemize}
       
   390   \item Very powerful, ``Batteries included''
       
   391   \item Some standard modules:
       
   392     \begin{itemize}
       
   393     \item Math: \typ{math}, \typ{random}
       
   394     \item Internet access: \typ{urllib2}, \typ{smtplib}
       
   395     \item System, Command line arguments: \typ{sys}
       
   396     \item Operating system interface: \typ{os}
       
   397     \item Regular expressions: \typ{re}
       
   398     \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile}
       
   399     \item And a whole lot more!
       
   400     \end{itemize}
       
   401   \item Check out the Python Library reference:
       
   402     \url{http://docs.python.org/library/}
       
   403   \end{itemize}
       
   404 \inctime{5}
       
   405 \end{frame}
       
   406 
       
   407 \section{Coding Style}
       
   408 \begin{frame}{Readability and Consistency}
       
   409     \begin{itemize}
       
   410         \item Readability Counts!\\Code is read more often than its written.
       
   411         \item Consistency!
       
   412         \item Know when to be inconsistent.
       
   413       \end{itemize}
       
   414 \end{frame}
       
   415 
       
   416 \begin{frame}[fragile] \frametitle{A question of good style}
       
   417   \begin{lstlisting}
       
   418     amount = 12.68
       
   419     denom = 0.05
       
   420     nCoins = round(amount/denom)
       
   421     rAmount = nCoins * denom
       
   422   \end{lstlisting}
       
   423   \pause
       
   424   \begin{block}{Style Rule \#1}
       
   425     Naming is 80\% of programming
       
   426   \end{block}
       
   427 \end{frame}
       
   428 
       
   429 \begin{frame}[fragile]
       
   430   \frametitle{Code Layout}
       
   431   \begin{itemize}
       
   432         \item Indentation
       
   433         \item Tabs or Spaces??
       
   434         \item Maximum Line Length
       
   435         \item Blank Lines
       
   436         \item Encodings
       
   437    \end{itemize}
       
   438 \end{frame}
       
   439 
       
   440 \begin{frame}{Whitespaces in Expressions}
       
   441   \begin{itemize}
       
   442         \item When to use extraneous whitespaces??
       
   443         \item When to avoid extra whitespaces??
       
   444         \item Use one statement per line
       
   445    \end{itemize}
       
   446 \end{frame}
       
   447 
       
   448 \begin{frame}{Comments}
       
   449   \begin{itemize}
       
   450         \item No comments better than contradicting comments
       
   451         \item Block comments
       
   452         \item Inline comments
       
   453    \end{itemize}
       
   454 \end{frame}
       
   455 
       
   456 \begin{frame}{Docstrings}
       
   457   \begin{itemize}
       
   458         \item When to write docstrings?
       
   459         \item Ending the docstrings
       
   460         \item One liner docstrings
       
   461    \end{itemize}
       
   462 More information at PEP8: http://www.python.org/dev/peps/pep-0008/
       
   463 \inctime{5}
       
   464 \end{frame}
       
   465 
       
   466 \section{Objects}
       
   467 \begin{frame}{Objects in general}
       
   468     \begin{itemize}
       
   469         \item What is an Object? (Types and classes)
       
   470         \item identity
       
   471         \item type
       
   472         \item method
       
   473       \end{itemize}
       
   474 \end{frame}
       
   475 
       
   476 \begin{frame}{Almost everything is an Object!}
       
   477   \begin{itemize}
       
   478     \item \typ{list}
       
   479     \item \typ{tuple}
       
   480     \item \typ{string}
       
   481     \item \typ{dictionary}
       
   482     \item \typ{function}
       
   483     \item Of course, user defined class objects!
       
   484   \end{itemize}
       
   485 \end {frame}
       
   486 
       
   487 \begin{frame}{Using Objects}
       
   488   \begin{itemize}
       
   489     \item Creating Objects: Initialization
       
   490     \item Object Manipulation: Object methods and ``.'' operator
       
   491   \end{itemize}
       
   492 \end{frame}
       
   493 
       
   494 \begin{frame}[fragile]
       
   495   \frametitle{Objects provide consistency}
       
   496   \small
       
   497   \begin{lstlisting}
       
   498 for element in (1, 2, 3):
       
   499     print element
       
   500 for key in {'one':1, 'two':2}:
       
   501     print key
       
   502 for char in "123":
       
   503     print char
       
   504 for line in open("myfile.txt"):
       
   505     print line
       
   506 for line in urllib2.urlopen('http://site.com'):
       
   507     print line
       
   508   \end{lstlisting}
       
   509 \inctime{10}
       
   510 \end{frame}
       
   511 
       
   512 \begin{frame}
       
   513   \frametitle{What did we learn?}
       
   514   \begin{itemize}
       
   515     \item Lists, Tuples, Dictionaries, Sets: creation and manipulation
       
   516     \item More about functions
       
   517     \item Coding style
       
   518     \item Objects: creation and manipulation
       
   519   \end{itemize}
       
   520 \end{frame}
       
   521 
       
   522 \end{document}