\documentclass[english,serif,mathserif,xcolor=pdftex,dvipsnames,table]{beamer}
\usepackage[utf8]{inputenc}
%\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{color}
  % for the color names, see: http://en.wikibooks.org/wiki/LaTeX/Colors#Predefined_colors
  % Apricot     Aquamarine      Bittersweet     Black
  % Blue        BlueGreen       BlueViolet      BrickRed
  % Brown       BurntOrange     CadetBlue       CarnationPink
  % Cerulean    CornflowerBlue  Cyan    Dandelion
  % DarkOrchid  Emerald         ForestGreen     Fuchsia
  % Goldenrod   Gray    Green   GreenYellow
  % JungleGreen Lavender        LimeGreen       Magenta
  % Mahogany    Maroon  Melon   MidnightBlue
  % Mulberry    NavyBlue        OliveGreen      Orange
  % OrangeRed   Orchid  Peach   Periwinkle
  % PineGreen   Plum    ProcessBlue     Purple
  % RawSienna   Red     RedOrange       RedViolet
  % Rhodamine   RoyalBlue       RoyalPurple     RubineRed
  % Salmon      SeaGreen        Sepia   SkyBlue
  % SpringGreen Tan     TealBlue        Thistle
  % Turquoise   Violet  VioletRed       White
  % WildStrawberry      Yellow  YellowGreen     YellowOrange
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{colortbl}%
  %\newcommand{\cellcolor}[2]{\multicolumn{1}{>{\columncolor{#1}}c}{#2}}
\usepackage[procnames]{listings}%
  \lstloadlanguages{python}%
  \lstset{
    language=python,%
    % --- basic appearance ---
    basicstyle=\small\ttfamily,%
    %columns=fullflexible,% best results for proportional fonts
    commentstyle=\slshape,%
    keywordstyle=\bfseries,% or \normalfont
    %identifierstyle=\color{black},%
    procnamestyle=\bfseries\color{BrickRed},%
    procnamekeys={def},%
    stringstyle=\color{MidnightBlue},%
    showstringspaces=true,%
    emph={self},%
    emphstyle=\bfseries\color{gray},%
    % --- escaping and special displays ---
    escapechar=@,% text between "@" will be rendered as normal TeX
    %moredelim=[il][\small\itshape]{\#},% ditto for text beween "#" and end-of-line
    texcl,%
    mathescape=false,%
    %literate={*{=}{{$\gets$ }}1 {==}{{$=$ }}1 {<=}{{$\leq$ }}1 {>=}{{$\geq$ }}1 {!=}{{$\neq$ }}1},%
    % --- display ---
    %showspaces=false,%
    %showstringspaces=false,%
    %xleftmargin=2em,%
    % --- line numbers ---
    %numbers=left,%
    %numberstyle=\tiny,%
    %stepnumber=1,%
    %firstnumber=1%
  }%
  \lstMakeShortInline{@}%
\usepackage{longtable}
\usepackage{mdwtab}
\usepackage{multirow}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{relsize}
\usepackage{soul}
\usepackage{textcomp}
\usepackage{tikz}%
  \usetikzlibrary{arrows,shapes}%
  % For every picture that defines or uses external nodes, you'll have to
  % apply the 'remember picture' style. To avoid some typing, we'll apply
  % the style to all pictures.
  \tikzstyle{every picture}+=[remember picture]%
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{latexsym}
\usepackage{amssymb}
\usepackage{hyperref}
  % color links
  \hypersetup{%
    colorlinks=true,%
    urlcolor=BurntOrange%
  }%
\usepackage{url}
\tolerance=1000
\providecommand{\alert}[1]{\textbf{#1}}

\usetheme{uzhneu-en-informal}


\title[Python I]{%
  Introduction to Python programming, I
}
\author[R. Murri]{%
  \textbf{Riccardo Murri} \\
  Grid Computing Competence Center, \\
  Organisch-Chemisches Institut, \\
  University of Zurich
}
\date{Nov.~9,~2011}

%% Use `\largeskip` to get a larger vertical white space between two
%% lines/paragraphs:
\newcommand{\largeskip}{\vspace{1em}}
\def\+{\largeskip}
\setlength{\parsep}{1.0em}

\begin{document}

% title frame
\maketitle


\section{Introduction}

\begin{frame}
  \frametitle{Today's class}
  
  A quick introduction to the Python programming language. (Assuming
  you already know how to program, so we'll focus on the differences
  with other languages rather than the concepts.)

  \+
  {\small These slides are available for download from: 
    \url{http://www.gc3.uzh.ch/teaching/lsci2011/lecture07.pdf}}
\end{frame}


\begin{frame}
  \frametitle{References} 

  See the \href{http://www.gc3.uzh.ch/teaching/lsci2011.html}{course
    website} for an extensive and commented list.

  \begin{itemize}
    \item \textbf{The Python tutorial},
      {\small \url{http://docs.python.org/tutorial/}}
    \item {Google's Python class},
      {\small \url{http://code.google.com/edu/languages/google-python-class/index.html}}
    \item {Python for Java programmers}, 
      {\small \url{http://python4java.necaiseweb.org/Main/TableOfContents}}
  \end{itemize}
\end{frame}


\begin{frame}
  \frametitle{Python 2 vs Python 3}

  There are currently two major versions of Python available, with
  slightly different syntax and features.

  \+
  Python 2.7 is the last release in the 2.x series. 

  \+
  Python 3.x has a more polished syntax, removing inconsistencies and
  some historical baggage.

  \+
  But Python 2.x is still the default on most Linux distributions and
  some major Python packages have not yet been ported to Py3, so we
  shall focus on Py2 syntax.
\end{frame}


\begin{frame}
  \frametitle{Set-up for Python development}
  A bare-bones development environment consists of:
  \begin{itemize}
  \item A text editor (e.g.,
    \href{http://en.wikipedia.org/wiki/Gedit}{gedit}, 
    \href{http://hide1713.wordpress.com/2009/01/30/setup-perfect-python-environment-in-emacs/}{emacs},
    \href{http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/}{vim})
  \item The Python interpreter (it is installed by default on
    Ubuntu)
  \item A terminal application to run the interpreter in.
  \end{itemize}

  \+ See
  {\small \url{http://wiki.python.org/moin/IntegratedDevelopmentEnvironments}}
  for a commented list of {IDEs} with Python support.
\end{frame}


\begin{frame}[fragile]
  \frametitle{The REPL, I}
  Python is an \emph{interpreted} language.

  \+
  It also features an interactive toplevel
  (\href{http://en.wikipedia.org/wiki/REPL}{REPL}) for evaluating
  expressions and statements immediately.

  \+
  The REPL is started by invoking the command \texttt{python} in a
  terminal window.
\begin{semiverbatim}\small
\$ \textbf{python}
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" 
for more information.
>>> 
\end{semiverbatim}
\end{frame}

\begin{frame}[fragile,fragile]
  \frametitle{The REPL, II}
  Expressions can be entered at the REPL prompt \texttt{>>>}; they are
  evaluated and the result is printed:
\begin{semiverbatim}
>>> 2+2
4
\end{semiverbatim}

  \+
  A line can be continued onto the next by ending it with the
  character `\texttt{\textbackslash}'
\begin{semiverbatim}
>>> "hello" + \textbackslash
... " world!"
'hello world!'
\end{semiverbatim}
  The prompt changes to `\texttt{...}' on continuation lines.

  \+\scriptsize
  Reference:
  \url{http://docs.python.org/reference/lexical_analysis.html#line-structure}
\end{frame}


\begin{frame}[fragile,fragile]
  \frametitle{Statements}
  Statements are commands that do not return a value.
\begin{semiverbatim}
>>> pass
{\small\it (No output)}
\end{semiverbatim}

  \+
  \textbf{The assignment operator is a statement:}
\begin{semiverbatim}
>>> a = 1
\end{semiverbatim}
  Similarly for the update operators \texttt{+=}, \texttt{-=}, etc.

  \+
  Other Python statements include definitions and
  control-flow constructs.  Everything else is an expression. 

  \+\scriptsize
  References:
  \url{http://lambda-the-ultimate.org/node/1044#comment-10878}
  \url{http://docs.python.org/reference/expressions.html}
  
\end{frame}


\begin{frame}[fragile]
  \frametitle{Statements, II}
  Well, almost: \texttt{print} is a \emph{statement} in Python 2:
\begin{semiverbatim}
>>> print 'a string'
a string
>>> print (2+2)
4
\end{semiverbatim}
  However, \texttt{print} is a \emph{function} in Python 3.

\end{frame}


\begin{frame}[fragile,fragile]
  \frametitle{Assignment, I}
  Assignment is done via the `\texttt{=}' statement:
\begin{semiverbatim}
>>> a = 1
>>> print a
1
\end{semiverbatim}
  \emph{Remember:} Assignement is a statement in Python, so no value is
  returned!

  \+
  \emph{Quiz:} Do you think the following will work?  If yes, what
  values are assigned to \texttt{a}, \texttt{b}, \texttt{c}?
\begin{semiverbatim}
>>> a = b = c = 1
\end{semiverbatim}
  \only<2>{Yes, it works. It's a special exception in Python
    syntax. (Recall that Python strives for readability.)}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Assignment, II}
  Multiple assignments can be performed in one statement:
\begin{semiverbatim}
>>> a, b, c = 1, 2, 3
>>> print a
1
>>> print b, c
2 3
\end{semiverbatim}

  The multiple assignments are effected \emph{left-to-right, one after
  the other}.

\end{frame}


\begin{frame}
  \frametitle{Types, I}
  Basic object types in Python:
  \begin{description}
  \item[int] Integer numbers: \texttt{1}, \texttt{-2}, \ldots
  %   up to \texttt{9223372036854775807} (on a 64-bit machine)
  % \item[long] Integer numbers of arbitrary size; Python switches
  %   automatically from \texttt{int} to \texttt{long} when needed.
  \item[bool] The class of the two boolean constants \texttt{True}, \texttt{False}.
  \item[float] Double precision floating-point numbers, e.g.:
    \texttt{3.1415}, \texttt{-1e-3}.
  \item[str] Strings of byte-size characters.
  \item[unicode] Strings of UNICODE characters.
  \end{description}
\end{frame}

\begin{frame}[fragile]
  \frametitle{String literals, I}
  There are several ways to express string literals in Python.

  \+
  Single and double quotes can be used interchangeably:
\begin{semiverbatim}
>>> "a string" == 'a string'
True
\end{semiverbatim}

  \+
  You can use the single quotes inside double-quoted strings, and viceversa:
\begin{semiverbatim}
>>> a = "Isn't it ok?"
>>> b = '"Yes", he said.'
\end{semiverbatim}
\end{frame}


\begin{frame}[fragile]
  \frametitle{String literals, II}
  Multi-line strings are delimited by three quote characters.
\begin{lstlisting}
>>> a = """This is a string,
... that extends over more
... than one line.
... """
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{String literals, III}
  Other string literals:
  \begin{description}
  \item[u"..."] A literal string of UNICODE characters (default in
    Python 3); example:
    \texttt{a = u'Universität Zürich'}.
  \item[r"..."] Suppress interpretation of backslash-sequences in the
    the string: the statement \texttt{a = r"\textbackslash n"} makes \texttt{a} into
    a string composed of the two bytes \texttt{\textbackslash} and \texttt{n}
  \item[b"..."] A literal string of byte-size characters (default in
    Python 2).
  \end{description}

  {\small Reference:
    \url{http://docs.python.org/reference/lexical_analysis.html#string-literals}}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Operators}
  All the usual unary and binary arithmetic and logical operators are
  defined in Python: \texttt{+}, \texttt{-}, \texttt{*}, \texttt{/},
  \texttt{**}~(exponentiation), \texttt{<<}, \texttt{>>}, etc.

  \+
  The comma operator (\texttt{,}) has a different meaning than in C:
\begin{lstlisting}
>>> 1,2,3
(1, 2, 3)
\end{lstlisting}
  (It is the \texttt{tuple} constructor --- more on it later.)
\end{frame}

\begin{frame}[fragile]
  \frametitle{Operators, II}
  Some operators are defined for non-numeric types:
\begin{lstlisting}
>>> "U" + 'ZH'
'UZH'
\end{lstlisting}

  \+ 
  Some support operands of mixed type:
\begin{lstlisting}
>>> "a" * 2
'aa'
>>> 2 * "a"
'aa'
\end{lstlisting}

  \+
  Some do not:
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
>>> "aaa" / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Function calls}
  Functions are called by postfixing the function name with a
  parenthesized argument list.

  \+
\begin{lstlisting}
>>> abs(-4)
4
\end{lstlisting}

  \+
  In other words, \textbf{the \emph{postfix} \texttt{()} is the function call operator}.
\end{frame}


\begin{frame}[fragile]
  \frametitle{Everything is an object!}
  In Python, \textbf{every value is an object.}

  \+
  The \texttt{dir()} built-in function can be used to list the
  attributes defined on any object:
\begin{semiverbatim}
>>> \textbf{dir("a string")}
['__add__', '__class__', '__contains__', {\small\em\ldots}, 
'capitalize', 'center', 'count', 'decode', 
{\small\em \ldots (Many lines omitted) \ldots}
'upper', 'zfill']
\end{semiverbatim}

  \+
  \emph{Quiz:} Is the expression \texttt{dir(1)} valid? Why?

  \only<2>{Yes it is: The integer \texttt{1} is an object, so we can
    list its attributes.}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Type conversion}

  Type conversion is done via function calls:
  \begin{description}
  \item[str($x$)] Converts the argument $x$ to a string; for numbers,
    the base 10 representation is used.
  \item[int($x$)] Converts its argument $x$ (a number or a string) to an integer;
    decimal digits are truncated.
  \item[float($x$)] Converts its argument $x$ (a number or a string) to a
    floating-point number.
  \end{description}

  \+ 
  It is possible to define conversion of an arbitrary object class
  to one of the basic types, see:
  {\small\url{http://docs.python.org/reference/datamodel.html#emulating-numeric-types}}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Types, II}
  To get the class of an object, use the \texttt{type()} function:
\begin{semiverbatim}
>>> type(1)
<type 'int'>

>>> type("a string")
<type 'str'>
\end{semiverbatim}

  \+
  In Python, \textbf{the terms \emph{class} and \emph{type} are synonyms}.
\end{frame}


\begin{frame}
  \frametitle{Assignment, III}
  The usual updating assignment operators \texttt{+=},
  \texttt{-=}, etc. are supported as a shortcut notation.

  \+ 
  \textbf{Always think of} 
  \emph{var}~\texttt{+=}~\emph{expr}, \emph{var}~\texttt{-=}~\emph{expr}, etc.
  \textbf{as an abbreviation for}
  \emph{var}~\texttt{=}~\emph{var}\texttt{+}\emph{expr},
  \emph{var}~\texttt{=}~\emph{var}\texttt{-}\emph{expr},
  etc.
  (The reason will be clear in a moment.)
\end{frame}


\begin{frame}
  \frametitle{Sequences}
  
  Python provides a few built-in ``collection'' classes:
  \begin{description}
  \item[list] mutable, possibly inhomogeneous
  \item[tuple] immutable, possibly inhomogeneous
  \item[str] immutable, only holds characters
  \end{description}
  An additional class is provided by the NumPy package, and in common
  use in scientific Python codes:
  \begin{description}
  \item[array] mutable, homogeneous
  \end{description}
\end{frame}

\begin{frame}[fragile,fragile]
  \frametitle{Sequences, II}
  You can access individual items in a sequence using the postfix
  \texttt{[]} operator.

  \+
  Sequence indices start at 0.
\begin{lstlisting}
>>> L = ['U', 'Z', 'H']
>>> print L[0], L[1], L[2]
'U' 'Z' 'H'
\end{lstlisting}

  \+
  The \texttt{len()} function returns the number of elements in a
  sequence.
\begin{lstlisting}
>>> len(L)
3
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Slices}
  The notation \texttt{[$n$:$m$]} is used for accessing a \emph{slice}
  of sequence (the items at positions $n$, $n+1$, \ldots, $m-1$).
\begin{lstlisting}
>>> # list numbers from 0 to 9
>>> L = range(0,10)
>>> L[1:4]
[1, 2, 3]
\end{lstlisting}

  \+
  If $n$ is omitted it defaults to 0, if $m$ is omitted it defaults to
  the length of the sequence.
\end{frame}


\begin{frame}[fragile]
  \frametitle{Mutable sequences}
  You can replace items in a \emph{mutable} sequence by assigning them
  a new value:
\begin{lstlisting}
>>> L[2] = 'h'
>>> print L
['U', 'Z', 'h']
\end{lstlisting}

  You can also replace an entire slice of a mutable sequence:
\begin{lstlisting}
>>> L[1:3] = 'SI'
>>> print L
['U', 'S', 'I']
\end{lstlisting}
  The new slice does not need to have the same length:
\begin{lstlisting}
>>> L[1:] = 'Zurich'
>>> print L
['U', 'Z', 'u', 'r', 'i', 'c', 'h']
\end{lstlisting}
\end{frame}


\begin{frame}[fragile,fragile]
  \frametitle{More data structures}
  The \texttt{dict} type implements a key/value mapping:
\begin{lstlisting}
>>> D = { } # equivalently: dict()
>>> D['a'] = 1
>>> D[2] = 'b'
>>> D
{'a': 1, 2: 'b'}
\end{lstlisting}

  \+
  The \texttt{set} type implements an unordered container that holds
  exactly one object per equivalence class:
\begin{lstlisting}
>>> S = set()
>>> S.add(1)
>>> S.add(2)
>>> S.add(1)
>>> S
set([1, 2])
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Mutable vs Immutable}
  Some objects (e.g., \texttt{tuple}, \texttt{int}, \texttt{str})
  cannot be modified.
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
>>> T = ('U', 'Z', 'H')
>>> T[2] = 'h'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
\end{lstlisting}
  
  \+
  \texttt{list}, \texttt{dict}, \texttt{set} and user-defined objects
  are mutable and can be modified in-place.
\end{frame}

\begin{frame}[fragile]
  \frametitle{Useful data structures operations}

  Read {\url{http://docs.python.org/tutorial/datastructures.html}}.

  \+
  Really, you will need it.

  \+
  And remember that \texttt{dir()} and \texttt{help()} are your friends!
\end{frame}


\begin{frame}[fragile]
  \frametitle{All variables are references}

  In Python, \textbf{all objects are ever passed by reference}.

  \+
  In particular, \textbf{variables always store a reference to an
    object}, never a copy!

  \+
  Hence, you have to be careful when modifying objects:
\begin{lstlisting}
>>> a = [1,2,3]
>>> b = a
>>> b.remove(2)
>>> a
[1, 3]
\end{lstlisting}

  \+
  This applies particularly for variables that capture the arguments
  to a function call!
\end{frame}


\begin{frame}[fragile]
  \frametitle{All variables are references, II}
  \emph{However:}
\begin{lstlisting}
>>> a = 1
>>> b = a
>>> b += 1
>>> a
1
>>> b
2
\end{lstlisting}
  \emph{How can you explain this?}
\end{frame}


\begin{frame}[fragile]
\begin{lstlisting}
def hello(name):
  """
  A friendly function.
  """
  print ("Hello, " + name + "!")

# the customary greeting
hello("world")
\end{lstlisting}

  \+
  \textbf{Indentation is significant in Python}: it is used to delimit
  blocks of code, like `\texttt{\{}' and `\texttt{\}}' in Java and C.
  (Blank lines and comments are ignored.)

  \+
  {\small 
    \emph{Exercise:} Type and run the above program at the interactive
    prompt. What does \texttt{help(hello)} print?  What's the result of
    evaluating the function \texttt{hello("world")}?}
\end{frame}


\begin{frame}[fragile]
  Function arguments can have default values:
\begin{lstlisting}
def hello(name="world"):
  """
  A friendly function.
  """
  print ("Hello, " + name + "!")

hello()
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
Python allows calling a function with named arguments:
\begin{lstlisting}
hello(name="Alice")
\end{lstlisting}
When passing arguments by name, they can be passed in any order:
\begin{lstlisting}
>>> from fractions import Fraction
>>> Fraction(numerator=1, denominator=2)
Fraction(1, 2)
>>> Fraction(denominator=2, numerator=1)
Fraction(1, 2)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Modules}
  The \texttt{import} statement reads a \texttt{.py} file and makes
  its contents available to the current program.
\begin{lstlisting}
>>> import hello
>>> hello.hello("Bob")
Hello, Bob!
\end{lstlisting}

  \+
  To import definitions into the current namespace, use the
  `\texttt{from $x$ import $y$}' form:
\begin{lstlisting}
>>> from fractions import Fraction
\end{lstlisting}

  \+
  \textbf{Modules are only read once}, no matter how many times an
  \texttt{import} statement is issued.
\end{frame}

\begin{frame}
  \frametitle{The \texttt{sys} module}
  
  The \texttt{sys} module provides standard functionality; you always
  want to import it.
  \begin{description}
  \item[sys.argv] Arguments given to the program (list of strings);
    \texttt{sysargv[0]} is the program name, \texttt{sys.argv[1]} is
    the first argument, etc.
  \item[sys,stdin] Standard input stream.
  \item[sys.stdout] Standard output steam.
  \item[sys.stderr] Standard error stream.
  \item[sys.maxint] Maximum positive \texttt{int} (before switching to \texttt{long})
  \end{description}
\end{frame}

\begin{frame}[fragile]
  Conditional execution uses the \texttt{if} statement:
\begin{lstlisting}
if @\it expr@:
  # indented block
elif @\it other-expr@:
  # indented block
else:
  # executed if none of the above matched
\end{lstlisting}

  \+ The \texttt{elif} can be repeated, with different conditions, or
  left out entirely.

  \+ 
  Also the \texttt{else} clause is optional.

  \+
  \emph{Where's the `end if'?}

  \only<2>{There's no `end if': indentation delimits blocks!}
\end{frame}


\begin{frame}[fragile]
  Conditional looping uses the \texttt{while} statement:
\begin{lstlisting}
while @\it expr@:
  # indented block
else:
  # executed at natural end of the loop
\end{lstlisting}

  \+
  To break out of a \texttt{while} loop, use the \texttt{break}
  statement. 

  \+
  If a loop is exited via a \texttt{break} statement, the
  \texttt{else} clause is \emph{not} executed.
\end{frame}

\begin{frame}[fragile]
    With the  \texttt{for} statement, you can loop over the values in
    a list:
\begin{lstlisting}
for i in range(0, 4):
  # loop block
  print i*i
else:
  # executed at the natural end of the loop
  print "loop ended naturally"
\end{lstlisting}

  \+
  To break out of a \texttt{for} loop, use the \texttt{break}
  statement. 

  \+
  If a loop is exited via a \texttt{break} statement, the
  \texttt{else} clause is \emph{not} executed.
\end{frame}

\begin{frame}[fragile]
  The \texttt{for} statement can more generally loop over a generic
  \emph{iterable}.

  \+
  For instance, you can iterate over lines read from a stream:
\begin{lstlisting}
for line in sys.stdin:
  if line == 'bye':
    print ("good bye!")
    break
  else:
    print ("you said: " + line)
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  Multiple assignment can be used in \texttt{for} statements as well.
\begin{lstlisting}
>>> L = [(1,'a'), (2,'b'), (3, 'c')]
>>> for num, char in L:
...     print "num is " + str(num) + ' and char is ' + char
\end{lstlisting}

  \+
  This is particularly useful with functions that return a tuple.
  For instance the \texttt{enumerate()} function (look it up with
  \texttt{help()}!).

  \+
  {\small \emph{Exercise:} Write a program that reads lines from its input,
    and outputs the line number, followed by the line content.}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Homework}
  \emph{Exercise:} write a function \texttt{sp($C$,$L$)} that returns
  the first pair (\texttt{tuple}) of elements from a \texttt{list}
  $L$ whose sum is integer $C$.

  {\small\em Source: 
    \url{http://code.google.com/codejam/contest/dashboard?c=351101#s=p0}}
\end{frame}

% - objects and classes
%   - example: unittest (class definition, single inheritance)
% - interfaces and protocols
% - iterator protocol
%   - example: counter (class attributes)
%   - exercise: word iterator
% - stdlib: file I/O
% - exercise: simple wordcount
% - file format example
%   - multiple inheritance
%   - ctor chaining
%   - *-arguments
% - stdlib: `os`, `os.path`
% - list comprehensions
%   - exercise: list all dotfiles

\end{document}

%%% Local Variables: 
%%% mode: latex
%%% TeX-master: t
%%% End: 

