<gh_stars>100-1000
\title{Introduction to Programming in Python (2)}
\author{<NAME> \newline \mbox{ }<EMAIL>\mbox{ }}
\date{ICL --- 29 September 2005}

\begin{document}

\frame{\titlepage}



\mode<article>{\section[Outline]{ICL/Introduction to Python 2/2005-09-29}}
\mode<presentation>{
  \section[Outline]{}
}

\frame{\tableofcontents}

\section{Review}

\begin{frame}[fragile]
  \frametitle{Review}

  \begin{itemize}
  \item<1->  \textbf{Python modules}
    \begin{itemize}
    \item   Every file ending in \texttt{.py} is a Python module.
    \item Modules can contain attributes such as functions and variables.
    \end{itemize}
  \item<2-> \textbf{Built-in objects}: numbers, strings,  lists,
    dictionaries,  tuples,  files
  \end{itemize}

  \pause
  
{\small
\begin{verbatim}
level = { 'icl' : 9, 'nlssd' : 11, 'inf2b' : 8}
x = level['nlssd'] # 11
n = len(level) # 3

flag = level.has_key('inf2b') # True 
l = level.keys() # ['nlssd', 'inf2b', 'icl']
l.sort()
for x in l:
    print l,level[l]
\end{verbatim}
}
\end{frame}

\begin{frame}
  \frametitle{Files and tuples}
  
  \textbf{Tuples}: like lists, but immutable (cannot be changed)
  \pause
\begin{semiverbatim}\small
emptyT = () \newline
T1 = (1, 2, 3)\newline
x = T1[1]\newline
n = len(T1)
\end{semiverbatim}

  \pause
  \textbf{Files}:  objects with methods for reading and writing to files
    \pause
\begin{semiverbatim}\small
fil = open('myfile', 'w')\newline
fil.write('hello file\\n')\newline
fil.close()\newline
\end{semiverbatim}
\pause
\begin{semiverbatim}\small
f2 = open('myfile', 'r')\newline
s = f2.readline() \# 'hello file\\n'\newline
t = f2.readline() \# ''
\end{semiverbatim}
    (\emph{Learning Python}, chapter 7)    
\end{frame}

\section{Control Flow}

\subsection{Conditionals}
\begin{frame}[fragile]
  \frametitle{if tests}
{\small
\begin{verbatim}
course = 'icl'
if course == 'icl':
    print 'Ewan / Steve'
    print 'Semester 1'
elif course == 'dil':
    print 'Phillip'
    print 'Semester 2'
else:
    print 'Someone else'
    print 'Some semester'
\end{verbatim}}
  \pause
  \begin{itemize}
  \item \textbf{Indentation determines the block structure}
  \item Indentation enforces readability
  \item Tests after \texttt{if} and \texttt{elif} can be anything that
    returns True/False
  \end{itemize}
    (\emph{Learning Python}, chapter 9)    
\end{frame}


\subsection{Loops}

\begin{frame}[fragile]
  \frametitle{while loops}

  A while loop keeps iterating while the test at the top remains True.

{\small
\begin{verbatim}
a = 0
b = 10
while a < b:
    print a
    a = a + 1
\end{verbatim}
  \pause
\begin{verbatim}
s = 'icl'
while len(s) > 0:
    print s
    s = s[1:]
\end{verbatim}}
    (\emph{Learning Python}, chapter 10)    
\end{frame}

\begin{frame}[fragile]
  \frametitle{for loops}

  \texttt{for} is used to step through any sequence object
{\small
\begin{verbatim}
l = ['a', 'b', 'c']
for i in l:
    print i
\end{verbatim}}
  \pause
{\small
\begin{verbatim}
sum = 0
for x in [1, 2, 3, 4, 5, 6]:
    sum = sum + x
print sum
\end{verbatim}}
  \pause
\texttt{range()} is a useful function:
{\small
\begin{verbatim}
range(5) = [0, 1, 2, 3, 4]
range(2, 5) = [2, 3, 4]
range(0, 6, 2) = [0, 2, 4]
\end{verbatim}}
\end{frame}

\begin{frame}[fragile]
  \frametitle{for loops with style}

  Do something to each item in a list (eg print its square)

\begin{verbatim}
l = [1, 2, 3, 4, 5, 6, 7, 8]  #  or l = range(1,9)

# one way to print the square
for x in l:
    print x*x
\end{verbatim}
  \pause
\begin{verbatim}
# another way to do it
n = len(l)
for i in range(l):
    print l[i]*l[i]
\end{verbatim}
  \pause

  Which is better?

  \pause
  The top one...  Iterate directly over the sequence, try to avoid
  using counter-based loops...  
\end{frame}

\begin{frame}[fragile]
  \frametitle{Example: intersecting sequences}

  The intersection of \newline
  \texttt{['a', 'd', 'f', 'g']} and \texttt{['a', 'b', 'c', 'd']} \newline
  is \texttt{['a', 'd']}

  \pause
{\small
\begin{verbatim}
l1 = ['a', 'd', 'f', 'g']
l2 = ['a', 'b', 'c', 'd']
res = []
for x in l1:
    for y in l2:
        if x == y:
            res.append(x)
\end{verbatim}}
  \pause
{\small
\begin{verbatim}
res = []
for x in l1:
    if x in l2:
        res.append(x)
# res = ['a', 'd']
\end{verbatim}}
\end{frame}


\section{Functions}
\subsection{Function basics}
\begin{frame}[fragile]
  \frametitle{Built-in, imported and user-defined functions}

  \begin{itemize}
  \item<1-> Some functions are built-in, eg:
    \begin{verbatim}
l = len(['a', 'b', 'c'])      
    \end{verbatim}
  \item<2-> Some functions may be imported, eg:
    \begin{verbatim}
import math
from os import getcwd
print getcwd()         # which directory am I in?
x = math.sqrt(9)       # 3
    \end{verbatim}
  \item<3-> Some functions are user-defined, eg:
    \begin{verbatim}
def multiply(a, b):
    return a * b
print multiply(4, 5)
print multiply('-', 5)
    \end{verbatim}
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Functions in Python}

  \begin{itemize}
  \item<1-> Functions are a way to group a set of statements that can be run
    more than once in a program.
  \item<1-> They can take parameters as inputs, and can return a value as
    output
  \item<2-> Example
\begin{verbatim}
def square(x):         # create and assign function
    return x*x
y = square(5)          # y gets assigned the value 25
\end{verbatim}

    \item<3-> \texttt{def} creates a function object, and assigns it to a
      name (\texttt{square} in this case)
    \item<3-> \texttt{return} sends an object back to the caller
    \item<3-> Adding \texttt{()} after the functions name calls the function
  \end{itemize}
  \uncover<4->{(\emph{Learning Python}, chapter 12)}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Intersection function}

\begin{verbatim}
def intersect(seq1, seq2):
    res = []
    for x in seq1:
        if x in seq2:
            res.append(x)
    return res
\end{verbatim}

  \pause

  \begin{itemize}
  \item Putting the code in a function means you can run it many times
  \item General --- callers pass any 2 sequences
  \item Code is in one place, makes changing it easier (if you have to)
  \end{itemize}
\end{frame}

\subsection{Variables and functions}
\begin{frame}[fragile]
  \frametitle{Local variables}
Variables inside a function are \emph{local} to that function
{\footnotesize
\begin{verbatim}
>>> def intersect(s1, s2):   
...     res = []
...     for x in s1:
...         if x in s2:
...             res.append(x)
...     return res
... 
>>> intersect([1,2,3,4], [1,5,6,4])
[1, 4]
>>> res
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'res' is not defined
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
\end{verbatim}}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Argument passing}

  Arguments are passed by assigning objects to \emph{local} names:

\begin{verbatim}
>>> def plusone(x):
...     x = x+1
...     return x
... 
>>> plusone(3)     
4
>>> x=6
>>> plusone(x)
7
>>> x
6
\end{verbatim}  
\end{frame}

\begin{frame}[fragile]
  \frametitle{Passing mutable arguments}

  Recall that numbers, strings, tuples are \emph{immutable}, and that
  lists and dictionaries are \emph{mutable}:
{\small
\begin{verbatim}
>>> def appendone(s):
...     s.append('one')
...     return s
... 
>>> appendone(['a', 'b'])
['a', 'b', 'one']
>>> l = ['a', 'b']
>>> appendone(l)
['a', 'b', 'one']
>>> l
['a', 'b', 'one']
\end{verbatim}}
\end{frame}

\begin{frame}[fragile]
  \frametitle{But variable names are still local}

\begin{verbatim}
>>> def doesnothing(l):
...     l = ['1', '2']
... 
>>> l = ['a', 'b']
>>> doesnothing(l)
>>> l
['a', 'b']
\end{verbatim}
\end{frame}

\subsection{Importing functions}
\begin{frame}[fragile]
  \frametitle{Importing functions}

    Put the definition of intersect in a module (call the file
    \texttt{foo.py}), then you can import it:  
    
    \pause
\begin{verbatim}
from foo import intersect
# ... define lst1 and lst2
l3 = intersect(lst1, lst2)
\end{verbatim}

    \pause
    or
\begin{verbatim}
import foo
# ... define lst1 and lst2
l3 = foo.intersect(lst1, lst2)
\end{verbatim}
\end{frame}

\subsection{Functional programming}

\begin{frame}[fragile]
  \frametitle{map}
\begin{verbatim}
>>> counters = range(1, 6)
>>> updated = []
>>> for x in counters:
...     updated.append(x+3)
... 
>>> updated
[4, 5, 6, 7, 8]
\end{verbatim}
  \pause
\begin{verbatim}
>>> def addthree(x): 
...     return x+3
... 
# map applies its first argument (a function) 
# to each element of its second (a list)
>>> map(addthree, counters)
[4, 5, 6, 7, 8]
\end{verbatim}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Anonymous functions and list comprehensions}
  \pause
\begin{verbatim}
# lambda is a way of defining a function with no name 
>>> map((lambda x: x+3), counters)
[4, 5, 6, 7, 8]
\end{verbatim}
  \pause
\begin{verbatim}
# you can even have a list comprehension...
>>> res = [addthree(x) for x in counters]
>>> res
[4, 5, 6, 7, 8]
\end{verbatim}

  Also check out \texttt{apply}, \texttt{filter} and \texttt{reduce}
  
\end{frame}


\subsection{Designing functions}
\begin{frame}
  \frametitle{Function design}

  \begin{itemize}
  \item Use arguments for the inputs, and return for outputs:  try to
    make a function independent of things outside it
  \item Avoid global variables when possible
  \item Don't change mutable arguments if possible
  \item Functions should do one thing well (not do many things)
  \item Functions should be relatively small
  \end{itemize}
\end{frame}


\section{Summary}

\begin{frame}
  \frametitle{Summary}

  \begin{itemize}
  \item Loops: \texttt{for} and \texttt{while}
  \item Functions in Python: built-in, supplied in modules, user-defined
  \item Defining functions with \texttt{def}
  \item Function arguments and return values
  \item Variables defined in functions are local to the function
  \item Mutable objects can be changed in functions
  \item Fancier stuff: mapping functions onto sequences
  \end{itemize}
\end{frame}


\end{document}
