|
1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
2 % Tutorial slides on Python. |
|
3 % |
|
4 % Author: Prabhu Ramachandran <prabhu at aero.iitb.ac.in> |
|
5 % Copyright (c) 2005-2008, 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, |
|
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 great programming toolkit} |
|
77 |
|
78 \author[Asokan \& Prabhu] {Asokan Pichai\\Prabhu Ramachandran} |
|
79 |
|
80 \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} |
|
81 \date[] {25, July 2009} |
|
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 |
|
99 % If you wish to uncover everything in a step-wise fashion, uncomment |
|
100 % the following command: |
|
101 %\beamerdefaultoverlayspecification{<+->} |
|
102 |
|
103 %\includeonlyframes{current,current1,current2,current3,current4,current5,current6} |
|
104 |
|
105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
106 % DOCUMENT STARTS |
|
107 \begin{document} |
|
108 |
|
109 \begin{frame} |
|
110 \titlepage |
|
111 \end{frame} |
|
112 \begin{frame} |
|
113 {Acknowledgements} |
|
114 \begin{center} |
|
115 This program is conducted by\\ |
|
116 IIT, Bombay\\ |
|
117 through CDEEP\\as part of the open source initiatives\\ |
|
118 under the aegis of\\ |
|
119 \alert{National Mission on Education through ICT,} \\ |
|
120 Ministry of HRD. |
|
121 \end{center} |
|
122 \end{frame} |
|
123 |
|
124 \begin{frame} |
|
125 \frametitle{Outline} |
|
126 \tableofcontents |
|
127 % You might wish to add the option [pausesections] |
|
128 \end{frame} |
|
129 |
|
130 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
131 % TODO |
|
132 % |
|
133 % * Add slide on Python packages (modules) |
|
134 % * Add slides on reference counting. |
|
135 |
|
136 \section{Agenda} |
|
137 \begin{frame}{About the Workshop} |
|
138 \begin{description} |
|
139 \item[Session 1] Sat 14:00--15:55 |
|
140 \item[Session 2] Sat 16:05--18:00 |
|
141 \item[Session 3] Sun 14:00--15:55 |
|
142 \item[Session 4] Sun 16:05--18:00 |
|
143 \end{description} |
|
144 |
|
145 \begin{block}{Goal of the workshop} |
|
146 At the end of this program, successful participants will be able to use python as their scripting and problem solving language. Aimed at Engg. students--focus on basic numerics and plotting-- but should serve a similar purpose for others. |
|
147 \end{block} |
|
148 \end{frame} |
|
149 |
|
150 \begin{frame}{Checklist} |
|
151 Let us verify that all of us are having the same (similar) tools and environment |
|
152 \begin{description} |
|
153 \item[python] Type python at the command line. Do you see version 2.5 or later? |
|
154 \item[IPython] Is IPython available? |
|
155 \item[Editor] Which editor? scite, vim, emacs, \ldots |
|
156 \end{description} |
|
157 \end{frame} |
|
158 |
|
159 \section{Overview} |
|
160 \begin{frame}{Session 1} |
|
161 \begin{itemize} |
|
162 \item Introduction and motivation |
|
163 \item Using the interpreter(s) |
|
164 \item Basic data types: int, float, string |
|
165 \item Basic data structures: list |
|
166 \item Basic console IO: \texttt{raw\_input(), print} |
|
167 \item Basic control flow: \texttt{if, while} |
|
168 \item Problem set 1 |
|
169 \item Functions $\rightarrow$ Problem set 2 |
|
170 \item lists, \texttt{for} $\rightarrow$ Problem set 3 |
|
171 \item IO, Modules $\rightarrow$ Problem sets 4,5, \ldots |
|
172 \end{itemize} |
|
173 \end{frame} |
|
174 |
|
175 \begin{frame} |
|
176 \frametitle{Introduction} |
|
177 \begin{itemize} |
|
178 \item Creator and BDFL: Guido van Rossum |
|
179 \item Conceived in December 1989 |
|
180 \item ``Python'' as in Monty Python's Flying Circus |
|
181 \item Current stable version of Python is 2.6.x |
|
182 \item PSF license (like BSD: no strings attached) |
|
183 \item Highly cross platform |
|
184 \item Runs on the Nokia series 60! |
|
185 \item \alert{Philosophy:} Simple and complete by design |
|
186 \end{itemize} |
|
187 \end{frame} |
|
188 |
|
189 \begin{frame} |
|
190 \frametitle{Resources} |
|
191 \begin{itemize} |
|
192 \item Part of many GNU/Linux distributions |
|
193 \item Web: \url{http://www.python.org} |
|
194 \item Doc: \url{http://www.python.org/doc} |
|
195 \item Free Tutorials: |
|
196 \begin{itemize} |
|
197 \item Official Python tutorial: \url{http://docs.python.org/tut/tut.html} |
|
198 \item Byte of Python: \url{http://www.byteofpython.info/} |
|
199 \item Dive into Python: \url{http://diveintopython.org/} |
|
200 \end{itemize} |
|
201 \end{itemize} |
|
202 \end{frame} |
|
203 |
|
204 \begin{frame} |
|
205 \frametitle{Why Python?} |
|
206 \begin{itemize} |
|
207 \item Designed to be readable and easy to use |
|
208 \item High level, interpreted, modular, OO |
|
209 \item Much faster development cycle |
|
210 \item Powerful interactive environment |
|
211 \item Rapid application development |
|
212 \item Rich standard library and modules |
|
213 \item Interfaces well with C++, C and FORTRAN |
|
214 \item \alert{More than a math package $\Rightarrow$ some extra work compared to math packages} |
|
215 \end{itemize} |
|
216 \end{frame} |
|
217 |
|
218 \begin{frame} |
|
219 \frametitle{Use cases} |
|
220 \begin{itemize} |
|
221 \item NASA: Space Shuttle Mission Design |
|
222 \item AstraZeneca: Collaborative Drug Discovery |
|
223 \item ForecastWatch.com: Helps Meteorologists |
|
224 \item Industrial Light \& Magic: Runs on Python |
|
225 \item Zope: Commercial grade Toolkit |
|
226 \item Plone: Professional high feature CMS |
|
227 \item RedHat: install scripts, sys-admin tools |
|
228 \item Django: A great web application framework |
|
229 \item Google: A strong python shop |
|
230 \end{itemize} |
|
231 \end{frame} |
|
232 |
|
233 \begin{frame} |
|
234 \frametitle{To sum up, python is\ldots} |
|
235 \begin{itemize} |
|
236 \item dynamically typed, interpreted $\rightarrow$ rapid testing/prototyping |
|
237 \item powerful, very high level |
|
238 \item has full introspection |
|
239 \item Did we mention powerful? |
|
240 \end{itemize} |
|
241 \begin{block}{But \ldots} |
|
242 may be wanting in performance. specialised resources such as SWIG, \alert{Cython} are available |
|
243 \end{block} |
|
244 \inctime{15} |
|
245 \end{frame} |
|
246 |
|
247 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
248 % TIME: 15 m, running 15m |
|
249 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
250 |
|
251 \section{Python} |
|
252 |
|
253 \subsection{Getting Started} |
|
254 |
|
255 \begin{frame}[fragile]{At the prompt, type the following} |
|
256 \begin{lstlisting} |
|
257 >>> print 'Hello Python' |
|
258 >>> print 3124 * 126789 |
|
259 >>> 1786 % 12 |
|
260 >>> 3124 * 126789 |
|
261 >>> a = 3124 * 126789 |
|
262 >>> big = 12345678901234567890 ** 3 |
|
263 >>> verybig = big * big * big * big |
|
264 >>> 12345**6, 12345**67, 12345**678 |
|
265 \end{lstlisting} |
|
266 \end{frame} |
|
267 |
|
268 \begin{frame}[fragile]{At the prompt, type the following} |
|
269 \begin{lstlisting} |
|
270 >>> s = 'Hello ' |
|
271 >>> p = 'World' |
|
272 >>> s + p |
|
273 >>> s * 12 |
|
274 >>> s * s |
|
275 >>> s + p * 12, (s + p)* 12 |
|
276 >>> s * 12 + p * 12 |
|
277 >>> 12 * s |
|
278 \end{lstlisting} |
|
279 \end{frame} |
|
280 |
|
281 \begin{frame}[fragile]{At the prompt, type the following} |
|
282 \begin{lstlisting} |
|
283 >>> 17/2 |
|
284 >>> 17/2.0 |
|
285 >>> 17.0/2 |
|
286 >>> 17.0/8.5 |
|
287 >>> int(17/2.0) |
|
288 >>> float(17/2) |
|
289 >>> str(17/2.0) |
|
290 >>> round( 7.5 ) |
|
291 \end{lstlisting} |
|
292 \begin{block}{Mini exercise} |
|
293 Round a float to the nearest integer, using \texttt{int()}? |
|
294 \end{block} |
|
295 \end{frame} |
|
296 |
|
297 \begin{frame}{Midi exercises} |
|
298 \begin{center} |
|
299 \begin{itemize} |
|
300 \item What does this do? |
|
301 \item \texttt{round(amount * 10) /10.0 } |
|
302 \end{itemize} |
|
303 \end{center} |
|
304 \end{frame} |
|
305 |
|
306 \begin{frame}{More exercises?} |
|
307 \begin{center} |
|
308 \begin{block}{Round sums} |
|
309 How to round a number to the nearest 5 paise?\\ |
|
310 \begin{description} |
|
311 \item[Remember] 17.23 $\rightarrow$ 17.25,\\ while 17.22 $\rightarrow$ 17.20\\ |
|
312 \end{description} |
|
313 How to round a number to the nearest 20 paise? |
|
314 \end{block} |
|
315 \end{center} |
|
316 \end{frame} |
|
317 |
|
318 \begin{frame}[fragile] {A question of good style} |
|
319 \begin{lstlisting} |
|
320 amount = 12.68 |
|
321 denom = 0.05 |
|
322 nCoins = round(amount/denom) |
|
323 rAmount = nCoins * denom |
|
324 \end{lstlisting} |
|
325 \pause |
|
326 \begin{block}{Style Rule \#1} |
|
327 Naming is 80\% of programming |
|
328 \end{block} |
|
329 \end{frame} |
|
330 |
|
331 |
|
332 \begin{frame}[fragile] |
|
333 \frametitle{Odds and ends} |
|
334 \begin{itemize} |
|
335 \item Case sensitive |
|
336 \item Dynamically typed $\Rightarrow$ need not specify a type |
|
337 \begin{lstlisting} |
|
338 a = 1 |
|
339 a = 1.1 |
|
340 a = "Now I am a string!" |
|
341 \end{lstlisting} |
|
342 \item Comments: |
|
343 \begin{lstlisting} |
|
344 a = 1 # In-line comments |
|
345 # Comment in a line to itself. |
|
346 a = "# This is not a comment!" |
|
347 \end{lstlisting} |
|
348 \end{itemize} |
|
349 \inctime{15} |
|
350 \end{frame} |
|
351 |
|
352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
353 % TIME: 15 m, running 30m |
|
354 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
355 |
|
356 \subsection{Data types} |
|
357 \begin{frame} |
|
358 \frametitle{Basic types} |
|
359 \begin{itemize} |
|
360 \item numbers: float, int, long, complex |
|
361 \item strings |
|
362 \item boolean |
|
363 \end{itemize} |
|
364 \begin{block}{Also to be discussed later} |
|
365 tuples, lists, dictionaries, functions, objects\ldots |
|
366 \end{block} |
|
367 \end{frame} |
|
368 |
|
369 \begin{frame}[fragile] |
|
370 \frametitle{Numbers} |
|
371 \vspace*{-0.25in} |
|
372 \begin{lstlisting} |
|
373 >>> a = 1 # Int. |
|
374 >>> l = 1000000L # Long |
|
375 >>> e = 1.01325e5 # float |
|
376 >>> f = 3.14159 # float |
|
377 >>> c = 1+1j # Complex! |
|
378 >>> print f*c/a |
|
379 (3.14159+3.14159j) |
|
380 >>> print c.real, c.imag |
|
381 1.0 1.0 |
|
382 >>> abs(c) |
|
383 1.4142135623730951 |
|
384 >>> abs( 8 - 9.5 ) |
|
385 1.5 |
|
386 \end{lstlisting} |
|
387 \end{frame} |
|
388 |
|
389 \begin{frame}[fragile] |
|
390 \frametitle{Boolean} |
|
391 \begin{lstlisting} |
|
392 >>> t = True |
|
393 >>> f = not t |
|
394 False |
|
395 >>> f or t |
|
396 True |
|
397 >>> f and t |
|
398 False |
|
399 \end{lstlisting} |
|
400 \begin{block}{Try:} |
|
401 NOT True\\ |
|
402 not TRUE |
|
403 \end{block} |
|
404 \end{frame} |
|
405 |
|
406 \begin{frame}[fragile] |
|
407 \frametitle{Relational and logical operators} |
|
408 \begin{lstlisting} |
|
409 >>> a, b, c = -1, 0, 1 |
|
410 >>> a == b |
|
411 False |
|
412 >>> a <= b |
|
413 True |
|
414 >>> a + b != c |
|
415 True |
|
416 >>> a < b < c |
|
417 True |
|
418 >>> c >= a + b |
|
419 True |
|
420 \end{lstlisting} |
|
421 \end{frame} |
|
422 |
|
423 \begin{frame}[fragile] |
|
424 \frametitle{Strings} |
|
425 \begin{lstlisting} |
|
426 s = 'this is a string' |
|
427 s = 'This one has "quotes" inside!' |
|
428 s = "I have 'single-quotes' inside!" |
|
429 l = "A string spanning many lines\ |
|
430 one more line\ |
|
431 yet another" |
|
432 t = """A triple quoted string does |
|
433 not need to be escaped at the end and |
|
434 "can have nested quotes" etc.""" |
|
435 \end{lstlisting} |
|
436 \end{frame} |
|
437 |
|
438 \begin{frame}[fragile] |
|
439 \frametitle{More Strings} |
|
440 \vspace*{-0.2in} |
|
441 \begin{lstlisting} |
|
442 >>> w = "hello" |
|
443 >>> print w[0] + w[2] + w[-1] |
|
444 hlo |
|
445 >>> len(w) # guess what |
|
446 5 |
|
447 >>> s = u'Unicode strings!' |
|
448 >>> # Raw strings (note the leading 'r') |
|
449 ... r_s = r'A string $\alpha \nu$' |
|
450 \end{lstlisting} |
|
451 \pause |
|
452 \begin{lstlisting} |
|
453 >>> w[0] = 'H' # Can't do that! |
|
454 Traceback (most recent call last): |
|
455 File "<stdin>", line 1, in ? |
|
456 TypeError: object does not support item assignment |
|
457 \end{lstlisting} |
|
458 \end{frame} |
|
459 |
|
460 \begin{frame} |
|
461 \frametitle{Let us switch to IPython} |
|
462 Why? |
|
463 \begin{block} |
|
464 {Better help (and a lot more)} |
|
465 Tab completion\\ |
|
466 ?\\ |
|
467 .?\\ |
|
468 object.function? |
|
469 \end{block} |
|
470 \end{frame} |
|
471 |
|
472 \begin{frame}[fragile] |
|
473 \frametitle{More on strings} |
|
474 \begin{lstlisting} |
|
475 In [1]: a = 'hello world' |
|
476 In [2]: a.startswith('hell') |
|
477 Out[2]: True |
|
478 In [3]: a.endswith('ld') |
|
479 Out[3]: True |
|
480 In [4]: a.upper() |
|
481 Out[4]: 'HELLO WORLD' |
|
482 In [5]: a.upper().lower() |
|
483 Out[5]: 'hello world' |
|
484 \end{lstlisting} |
|
485 \end{frame} |
|
486 |
|
487 \begin{frame}[fragile]{Still with strings} |
|
488 \begin{lstlisting} |
|
489 In [6]: a.split() |
|
490 Out[6]: ['hello', 'world'] |
|
491 In [7]: ''.join(['a', 'b', 'c']) |
|
492 Out[7]: 'abc' |
|
493 In [8] 'd' in ''.join( 'a', 'b', 'c') |
|
494 Out[8]: False |
|
495 \end{lstlisting} |
|
496 \begin{block}{Try:} |
|
497 \texttt{a.split( 'o' )}\\ |
|
498 \texttt{'x'.join( a.split( 'o' ) )} |
|
499 \end{block} |
|
500 \end{frame} |
|
501 |
|
502 \begin{frame}[fragile]{Surprise! strings!!} |
|
503 \begin{lstlisting} |
|
504 In [11]: x, y = 1, 1.2 |
|
505 In [12]: 'x is %s, y is %s' %(x, y) |
|
506 Out[12]: 'x is 1, y is 1.234' |
|
507 \end{lstlisting} |
|
508 \begin{block}{Try:} |
|
509 \texttt{'x is \%d, y is \%f' \%(x, y) }\\ |
|
510 \texttt{'x is \%3d, y is \%4.2f' \%(x, y) } |
|
511 \end{block} |
|
512 \small |
|
513 \url{docs.python.org/lib/typesseq-strings.html}\\ |
|
514 \end{frame} |
|
515 |
|
516 \begin{frame} |
|
517 {Interlude} |
|
518 \begin{block} |
|
519 {A classic problem} |
|
520 How to interchange values of two variables? Please note that the type of either variable is unknown and it is not necessary that both be of the same type even! |
|
521 \end{block} |
|
522 \inctime{30} |
|
523 \end{frame} |
|
524 |
|
525 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
526 % TIME: 25 m+ Interlude break 5 mins, running 60m |
|
527 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
528 |
|
529 \subsection{Control flow} |
|
530 \begin{frame} |
|
531 \frametitle{Control flow constructs} |
|
532 \begin{itemize} |
|
533 \item \kwrd{if/elif/else}: branching |
|
534 \item \kwrd{while}: looping |
|
535 \item \kwrd{for}: iterating |
|
536 \item \kwrd{break, continue}: modify loop |
|
537 \item \kwrd{pass}: syntactic filler |
|
538 \end{itemize} |
|
539 \end{frame} |
|
540 |
|
541 \begin{frame}[fragile] |
|
542 \frametitle{Basic conditional flow} |
|
543 \begin{lstlisting} |
|
544 In [21]: a = 7 |
|
545 In [22]: b = 8 |
|
546 In [23]: if a > b: |
|
547 ....: print 'Hello' |
|
548 ....: else: |
|
549 ....: print 'World' |
|
550 ....: |
|
551 ....: |
|
552 World |
|
553 \end{lstlisting} |
|
554 Let us switch to creating a file |
|
555 \end{frame} |
|
556 |
|
557 \begin{frame} |
|
558 {Creating python files} |
|
559 \begin{itemize} |
|
560 \item aka scripts |
|
561 \item use your editor |
|
562 \item Note that white space is the way to specify blocks! |
|
563 \item extension \typ{.py} |
|
564 \item run with \texttt{python hello.py} at the command line |
|
565 \item in IPython\ldots |
|
566 \end{itemize} |
|
567 \end{frame} |
|
568 |
|
569 \begin{frame}[fragile] |
|
570 \frametitle{\typ{If...elif...else} example} |
|
571 \begin{lstlisting} |
|
572 x = int(raw_input("Enter an integer:")) |
|
573 if x < 0: |
|
574 print 'Be positive!' |
|
575 elif x == 0: |
|
576 print 'Zero' |
|
577 elif x == 1: |
|
578 print 'Single' |
|
579 else: |
|
580 print 'More' |
|
581 \end{lstlisting} |
|
582 \end{frame} |
|
583 |
|
584 \begin{frame}{Simple IO} |
|
585 \begin{block} |
|
586 {Console Input} |
|
587 \texttt{raw\_input(}) waits for user input.\\Prompt string is optional.\\ |
|
588 All keystrokes are Strings!\\\texttt{int()} converts string to int. |
|
589 \end{block} |
|
590 \begin{block} |
|
591 {Console output} |
|
592 \texttt{print} is straight forward. Major point to remember is the distinction between \texttt{print x} and \texttt{print x,} |
|
593 \end{block} |
|
594 \end{frame} |
|
595 |
|
596 \begin{frame}[fragile] |
|
597 \frametitle{Basic looping} |
|
598 \begin{lstlisting} |
|
599 # Fibonacci series: |
|
600 # the sum of two elements |
|
601 # defines the next |
|
602 a, b = 0, 1 |
|
603 while b < 10: |
|
604 print b, |
|
605 a, b = b, a + b |
|
606 |
|
607 \end{lstlisting} |
|
608 \typ{1 1 2 3 5 8}\\ |
|
609 \alert{Recall it is easy to write infinite loops with \kwrd{while}} |
|
610 \inctime{20} |
|
611 \end{frame} |
|
612 |
|
613 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
614 % TIME: 20 m, running 80m |
|
615 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
616 |
|
617 \begin{frame} |
|
618 \frametitle{Problem set 1} |
|
619 \begin{itemize} |
|
620 \item All the problems can be\\ |
|
621 solved using \kwrd{if} and \kwrd{while} |
|
622 \end{itemize} |
|
623 \end{frame} |
|
624 |
|
625 \begin{frame}{Problem 1.1} |
|
626 Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ |
|
627 These are called $Armstrong$ numbers. |
|
628 \end{frame} |
|
629 |
|
630 \begin{frame}{Problem 1.2 - Collatz sequence} |
|
631 \begin{enumerate} |
|
632 \item Start with an arbitrary (positive) integer. |
|
633 \item If the number is even, divide by 2; if the number is odd multiply by 3 and add 1. |
|
634 \item Repeat the procedure with the new number. |
|
635 \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. |
|
636 \end{enumerate} |
|
637 Write a program that accepts the starting value and prints out the Collatz sequence. |
|
638 |
|
639 \end{frame} |
|
640 |
|
641 \begin{frame}{Problem 1.3 - Kaprekar's constant} |
|
642 \begin{enumerate} |
|
643 \item Take a four digit number--with at least two digits different. |
|
644 \item Arrange the digits in ascending and descending order, giving A and D respectively. |
|
645 \item Leave leading zeros in A! |
|
646 \item Subtract A from D. |
|
647 \item With the result, repeat from step 2. |
|
648 \end{enumerate} |
|
649 Write a program to accept a 4-digit number and display the progression to Kaprekar's constant. |
|
650 \end{frame} |
|
651 |
|
652 \begin{frame}[fragile]{Problem 1.4} |
|
653 Write a program that prints the following pyramid on the screen. |
|
654 \begin{lstlisting} |
|
655 1 |
|
656 2 2 |
|
657 3 3 3 |
|
658 4 4 4 4 |
|
659 \end{lstlisting} |
|
660 The number of lines must be obtained from the user as input.\\ |
|
661 \pause |
|
662 When can your code fail? |
|
663 \only<2->{\inctime{25}} |
|
664 \end{frame} |
|
665 |
|
666 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
667 % TIME: 25 m, running 105m |
|
668 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
669 |
|
670 \subsection{Functions} |
|
671 \begin{frame}[fragile] |
|
672 \frametitle{Functions: examples} |
|
673 \begin{lstlisting} |
|
674 def signum( r ): |
|
675 """returns 0 if r is zero |
|
676 -1 if r is negative |
|
677 +1 if r is positive""" |
|
678 if r < 0: |
|
679 return -1 |
|
680 elif r > 0: |
|
681 return 1 |
|
682 else: |
|
683 return 0 |
|
684 \end{lstlisting} |
|
685 \end{frame} |
|
686 |
|
687 \begin{frame}[fragile] |
|
688 \frametitle{Functions: examples} |
|
689 \begin{lstlisting} |
|
690 def pad( n, size ): |
|
691 """pads integer n with spaces |
|
692 into a string of length size |
|
693 """ |
|
694 SPACE = ' ' |
|
695 s = str( n ) |
|
696 padSize = size - len( s ) |
|
697 return padSize * SPACE + s |
|
698 \end{lstlisting} |
|
699 \pause |
|
700 What about \%3d? |
|
701 \end{frame} |
|
702 |
|
703 \begin{frame}[fragile] |
|
704 {What does this function do?} |
|
705 \begin{lstlisting} |
|
706 def what( n ): |
|
707 if n < 0: n = -n |
|
708 while n > 0: |
|
709 if n % 2 == 1: |
|
710 return False |
|
711 n /= 10 |
|
712 return True |
|
713 \end{lstlisting} |
|
714 \end{frame} |
|
715 |
|
716 \begin{frame}[fragile] |
|
717 {What does this function do?} |
|
718 \begin{lstlisting} |
|
719 def what( n ): |
|
720 i = 1 |
|
721 while i * i < n: |
|
722 i += 1 |
|
723 return i * i == n, i |
|
724 \end{lstlisting} |
|
725 \end{frame} |
|
726 |
|
727 \begin{frame}[fragile] |
|
728 {What does this function do?} |
|
729 \begin{lstlisting} |
|
730 def what( n, x ): |
|
731 z = 1.0 |
|
732 if n < 0: |
|
733 x = 1.0 / x |
|
734 n = -n |
|
735 while n > 0: |
|
736 if n % 2 == 1: |
|
737 z *= x |
|
738 n /= 2 |
|
739 x *= x |
|
740 return z |
|
741 \end{lstlisting} |
|
742 \end{frame} |
|
743 |
|
744 \begin{frame} |
|
745 {Before writing a function} |
|
746 \begin{itemize} |
|
747 \item Builtin functions for various and sundry |
|
748 \item \typ{abs, any, all, len, max, min} |
|
749 \item \typ{pow, range, sum, type} |
|
750 \item Refer here: |
|
751 \url{http://docs.python.org/library/functions.html} |
|
752 \end{itemize} |
|
753 \inctime{15} |
|
754 \end{frame} |
|
755 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
756 % TIME: 15 m, running 120m |
|
757 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
758 |
|
759 \begin{frame}{Problem set 2} |
|
760 The focus is on writing functions and calling them. |
|
761 \end{frame} |
|
762 |
|
763 \begin{frame}{Problem 2.1} |
|
764 Write a function to return the gcd of two numbers. |
|
765 \end{frame} |
|
766 |
|
767 \begin{frame}{Problem 2.2} |
|
768 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 should not be displayed by our program. \\ |
|
769 Write a program to print primitive pythagorean triads. The program should generate all triads with a, b values in the range 0---100 |
|
770 \end{frame} |
|
771 |
|
772 \begin{frame}{Problem 2.3} |
|
773 Write a program that generates a list of all four digit numbers that have all their digits even and are perfect squares.\\For example, the output should include 6400 but not 8100 (one digit is odd) or 4248 (not a perfect square). |
|
774 \end{frame} |
|
775 |
|
776 \begin{frame}{Problem 2.4} |
|
777 The aliquot of a number is defined as: the sum of the \emph{proper} divisors of the number. For example, the aliquot(12) = 1 + 2 + 3 + 4 + 6 = 16.\\ |
|
778 Write a function that returns the aliquot number of a given number. |
|
779 \end{frame} |
|
780 |
|
781 \begin{frame}{Problem 2.5} |
|
782 A pair of numbers (a, b) is said to be \alert{amicable} if the aliquot number of a is b and the aliquot number of b is a.\\ |
|
783 Example: \texttt{220, 284}\\ |
|
784 Write a program that prints all five digit amicable pairs. |
|
785 \inctime{30} |
|
786 \end{frame} |
|
787 |
|
788 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
789 % TIME: 30 m, running 150m |
|
790 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
791 |
|
792 \subsection{Lists} |
|
793 |
|
794 \begin{frame}[fragile] |
|
795 \frametitle{List creation and indexing} |
|
796 \begin{lstlisting} |
|
797 >>> a = [] # An empty list. |
|
798 >>> a = [1, 2, 3, 4] # More useful. |
|
799 >>> len(a) |
|
800 4 |
|
801 >>> a[0] + a[1] + a[2] + a[-1] |
|
802 10 |
|
803 \end{lstlisting} |
|
804 \begin{itemize} |
|
805 \item Indices start with ? |
|
806 \item Negative indices indicate ? |
|
807 \end{itemize} |
|
808 \end{frame} |
|
809 |
|
810 \begin{frame}[fragile] |
|
811 \frametitle{List: slices} |
|
812 \begin{itemize} |
|
813 \item Slicing is a basic operation |
|
814 \item \typ{list[initial:final:step]} |
|
815 \item The step is optional |
|
816 \end{itemize} |
|
817 \begin{lstlisting} |
|
818 >>> a[1:3] # A slice. |
|
819 [2, 3] |
|
820 >>> a[1:-1] |
|
821 [2, 3, 4] |
|
822 >>> a[1:] == a[1:-1] |
|
823 False |
|
824 \end{lstlisting} |
|
825 Explain last result |
|
826 \end{frame} |
|
827 |
|
828 \begin{frame}[fragile] |
|
829 \frametitle{List: more slices} |
|
830 \begin{lstlisting} |
|
831 >>> a[0:-1:2] # Notice the step! |
|
832 [1, 3] |
|
833 >>> a[::2] |
|
834 [1, 3] |
|
835 >>> a[-1::-1] |
|
836 \end{lstlisting} |
|
837 What do you think the last one will do? |
|
838 \emphbar{Note: Strings also use same indexing and slicing.} |
|
839 \end{frame} |
|
840 |
|
841 \begin{frame}[fragile] |
|
842 \frametitle{List: examples} |
|
843 \begin{lstlisting} |
|
844 >>> a = [1, 2, 3, 4] |
|
845 >>> a[:2] |
|
846 [1, 3] |
|
847 >>> a[0:-1:2] |
|
848 [1, 3] |
|
849 \end{lstlisting} |
|
850 \pause |
|
851 \alert{Lists are mutable (unlike strings)} |
|
852 \begin{lstlisting} |
|
853 >>> a[1] = 20 |
|
854 >>> a |
|
855 [1, 20, 3, 4] |
|
856 \end{lstlisting} |
|
857 \end{frame} |
|
858 |
|
859 \begin{frame}[fragile] |
|
860 \frametitle{Lists are mutable and heterogenous} |
|
861 \begin{lstlisting} |
|
862 >>> a = ['spam', 'eggs', 100, 1234] |
|
863 >>> a[2] = a[2] + 23 |
|
864 >>> a |
|
865 ['spam', 'eggs', 123, 1234] |
|
866 >>> a[0:2] = [1, 12] # Replace items |
|
867 >>> a |
|
868 [1, 12, 123, 1234] |
|
869 >>> a[0:2] = [] # Remove items |
|
870 >>> a.append( 12345 ) |
|
871 >>> a |
|
872 [123, 1234, 12345] |
|
873 \end{lstlisting} |
|
874 \end{frame} |
|
875 |
|
876 \begin{frame}[fragile] |
|
877 \frametitle{List methods} |
|
878 \begin{lstlisting} |
|
879 >>> a = ['spam', 'eggs', 1, 12] |
|
880 >>> a.reverse() # in situ |
|
881 >>> a |
|
882 [12, 1, 'eggs', 'spam'] |
|
883 >>> a.append(['x', 1]) |
|
884 >>> a |
|
885 [12, 1, 'eggs', 'spam', ['x', 1]] |
|
886 >>> a.extend([1,2]) # Extend the list. |
|
887 >>> a.remove( 'spam' ) |
|
888 >>> a |
|
889 [12, 1, 'eggs', ['x', 1], 1, 2] |
|
890 \end{lstlisting} |
|
891 \end{frame} |
|
892 |
|
893 \begin{frame}[fragile] |
|
894 \frametitle{List containership} |
|
895 \begin{lstlisting} |
|
896 >>> a = ['cat', 'dog', 'rat', 'croc'] |
|
897 >>> 'dog' in a |
|
898 True |
|
899 >>> 'snake' in a |
|
900 False |
|
901 >>> 'snake' not in a |
|
902 True |
|
903 >>> 'ell' in 'hello world' |
|
904 True |
|
905 \end{lstlisting} |
|
906 \end{frame} |
|
907 |
|
908 \begin{frame}[fragile] |
|
909 \frametitle{Tuples: immutable} |
|
910 \begin{lstlisting} |
|
911 >>> t = (0, 1, 2) |
|
912 >>> print t[0], t[1], t[2], t[-1] |
|
913 0 1 2 2 |
|
914 >>> t[0] = 1 |
|
915 Traceback (most recent call last): |
|
916 File "<stdin>", line 1, in ? |
|
917 TypeError: object does not support item |
|
918 assignment |
|
919 \end{lstlisting} |
|
920 \begin{itemize} |
|
921 \item Multiple return values are actually a tuple. |
|
922 \item Exchange is tuple (un)packing |
|
923 \end{itemize} |
|
924 |
|
925 \end{frame} |
|
926 |
|
927 \begin{frame}[fragile] |
|
928 \frametitle{\typ{range()} function} |
|
929 \begin{lstlisting} |
|
930 >>> range(7) |
|
931 [0, 1, 2, 3, 4, 5, 6] |
|
932 >>> range( 3, 9) |
|
933 [3, 4, 5, 6, 7, 8] |
|
934 >>> range( 4, 17, 3) |
|
935 [4, 7, 10, 13, 16] |
|
936 >>> range( 5, 1, -1) |
|
937 [5, 4, 3, 2] |
|
938 >>> range( 8, 12, -1) |
|
939 [] |
|
940 \end{lstlisting} |
|
941 \end{frame} |
|
942 |
|
943 \begin{frame}[fragile] |
|
944 \frametitle{\typ{for\ldots range(\ldots)} idiom} |
|
945 \begin{lstlisting} |
|
946 In [83]: for i in range(5): |
|
947 ....: print i, i * i |
|
948 ....: |
|
949 ....: |
|
950 0 0 |
|
951 1 1 |
|
952 2 4 |
|
953 3 9 |
|
954 4 16 |
|
955 \end{lstlisting} |
|
956 \end{frame} |
|
957 |
|
958 \begin{frame}[fragile] |
|
959 \frametitle{\typ{for}: the list companion} |
|
960 |
|
961 \begin{lstlisting} |
|
962 In [84]: a = ['a', 'b', 'c'] |
|
963 In [85]: for x in a: |
|
964 ....: print x, chr( ord(x) + 10 ) |
|
965 ....: |
|
966 a k |
|
967 b l |
|
968 c m |
|
969 \end{lstlisting} |
|
970 Iterating over the list and not the index + reference\\ |
|
971 what if you want the index? |
|
972 \end{frame} |
|
973 |
|
974 \begin{frame}[fragile] |
|
975 \frametitle{\typ{for}: the list companion} |
|
976 \begin{lstlisting} |
|
977 In [89]: for p, ch in enumerate( a ): |
|
978 ....: print p, ch |
|
979 ....: |
|
980 ....: |
|
981 0 a |
|
982 1 b |
|
983 2 c |
|
984 \end{lstlisting} |
|
985 Try: \typ{print enumerate(a)} |
|
986 \inctime{20} |
|
987 \end{frame} |
|
988 |
|
989 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
990 % TIME: 20 m, running 170m |
|
991 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
992 |
|
993 \begin{frame} |
|
994 {Problem set 3} |
|
995 As you can guess, idea is to use \kwrd{for}! |
|
996 \end{frame} |
|
997 |
|
998 \begin{frame}{Problem 3.1} |
|
999 Which of the earlier problems is simpler when we use \kwrd{for} instead of \kwrd{while}? |
|
1000 \end{frame} |
|
1001 |
|
1002 \begin{frame}{Problem 3.2} |
|
1003 Given an empty chessboard and one Bishop placed in any square, say (r, c), generate the list of all squares the Bishop could move to. |
|
1004 \end{frame} |
|
1005 |
|
1006 \begin{frame}[fragile] |
|
1007 \frametitle{Problem 3.3} |
|
1008 |
|
1009 Given two real numbers \typ{a, b}, and an integer \typ{N}, write a |
|
1010 function named \typ{linspace( a, b, N)} that returns an ordered list |
|
1011 of \typ{N} points starting with \typ{a} and ending in \typ{b} and |
|
1012 equally spaced.\\ |
|
1013 |
|
1014 For example, \typ{linspace(0, 5, 11)}, should return, \\ |
|
1015 \begin{lstlisting} |
|
1016 [ 0.0 , 0.5, 1.0 , 1.5, 2.0 , 2.5, |
|
1017 3.0 , 3.5, 4.0 , 4.5, 5.0 ] |
|
1018 \end{lstlisting} |
|
1019 \end{frame} |
|
1020 |
|
1021 \begin{frame}[fragile] |
|
1022 \frametitle{Problem 3.4a (optional)} |
|
1023 |
|
1024 Use the \typ{linspace} function and generate a list of N tuples of the form\\ |
|
1025 \typ{[($x_1$,f($x_1$)),($x_2$,f($x_2$)),\ldots,($x_N$,f($x_N$))]}\\for the following functions,\begin{itemize} |
|
1026 \item \typ{f(x) = sin(x)} |
|
1027 \item \typ{f(x) = sin(x) + sin(10*x)}. |
|
1028 \end{itemize} |
|
1029 \end{frame} |
|
1030 |
|
1031 \begin{frame}[fragile] |
|
1032 \frametitle{Problem 3.4b (optional)} |
|
1033 |
|
1034 Using the tuples generated earlier, determine the intervals where the roots of the functions lie. |
|
1035 |
|
1036 \inctime{15} |
|
1037 \end{frame} |
|
1038 |
|
1039 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1040 % TIME: 15 m, running 185m |
|
1041 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1042 |
|
1043 \subsection{IO} |
|
1044 |
|
1045 \begin{frame}[fragile] |
|
1046 \frametitle{Simple tokenizing and parsing} |
|
1047 \begin{lstlisting} |
|
1048 s = """The quick brown fox jumped |
|
1049 over the lazy dog""" |
|
1050 for word in s.split(): |
|
1051 print word.capitalize() |
|
1052 \end{lstlisting} |
|
1053 \end{frame} |
|
1054 |
|
1055 \begin{frame}[fragile] |
|
1056 \frametitle{Problem 4.1} |
|
1057 Given a string like, ``1, 3-7, 12, 15, 18-21'', produce the list \\ |
|
1058 \begin{lstlisting} |
|
1059 [1,3,4,5,6,7,12,15,18,19,20,21] |
|
1060 \end{lstlisting} |
|
1061 \end{frame} |
|
1062 |
|
1063 \begin{frame}[fragile] |
|
1064 \frametitle{File handling} |
|
1065 \begin{lstlisting} |
|
1066 >>> f = open('/path/to/file_name') |
|
1067 >>> data = f.read() # Read entire file. |
|
1068 >>> line = f.readline() # Read one line. |
|
1069 >>> f.close() # close the file. |
|
1070 \end{lstlisting} |
|
1071 Writing files |
|
1072 \begin{lstlisting} |
|
1073 >>> f = open('/path/to/file_name', 'w') |
|
1074 >>> f.write('hello world\n') |
|
1075 >>> f.close() |
|
1076 \end{lstlisting} |
|
1077 \begin{itemize} |
|
1078 \item Everything read or written is a string |
|
1079 \end{itemize} |
|
1080 \emphbar{Try \typ{file?} for more help} |
|
1081 \end{frame} |
|
1082 |
|
1083 \begin{frame}[fragile] |
|
1084 \frametitle{File and \kwrd{for}} |
|
1085 \begin{lstlisting} |
|
1086 >>> f = open('/path/to/file_name') |
|
1087 >>> for line in f: |
|
1088 ... print line |
|
1089 ... |
|
1090 \end{lstlisting} |
|
1091 \end{frame} |
|
1092 |
|
1093 \begin{frame}{Problem 4.2} |
|
1094 The given file has lakhs of records in the form:\\ |
|
1095 \typ{RGN;ID;NAME;MARK1;\ldots;MARK5;TOTAL;PFW}\\ |
|
1096 Some entries may be empty. Read the data from this file and print the |
|
1097 name of the student with the maximum total marks. |
|
1098 \end{frame} |
|
1099 |
|
1100 \begin{frame}{Problem 4.3} |
|
1101 For the same data file compute the average marks in different |
|
1102 subjects, the student with the maximum mark in each subject and also |
|
1103 the standard deviation of the marks. Do this efficiently. |
|
1104 |
|
1105 \inctime{20} |
|
1106 \end{frame} |
|
1107 |
|
1108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1109 % TIME: 20 m, running 205m |
|
1110 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1111 |
|
1112 \subsection{Modules} |
|
1113 |
|
1114 \begin{frame}[fragile] |
|
1115 {Modules} |
|
1116 \begin{lstlisting} |
|
1117 >>> sqrt(2) |
|
1118 Traceback (most recent call last): |
|
1119 File "<stdin>", line 1, in <module> |
|
1120 NameError: name 'sqrt' is not defined |
|
1121 >>> import math |
|
1122 >>> math.sqrt(2) |
|
1123 1.4142135623730951 |
|
1124 \end{lstlisting} |
|
1125 \end{frame} |
|
1126 |
|
1127 \begin{frame}[fragile] |
|
1128 {Modules} |
|
1129 \begin{itemize} |
|
1130 \item The \kwrd{import} keyword ``loads'' a module |
|
1131 \item One can also use: |
|
1132 \begin{lstlisting} |
|
1133 >>> from math import sqrt |
|
1134 >>> from math import * |
|
1135 \end{lstlisting} |
|
1136 \item What is the difference? |
|
1137 \item \alert{Use the later only in interactive mode} |
|
1138 \end{itemize} |
|
1139 \emphbar{Package hierarchies} |
|
1140 \begin{lstlisting} |
|
1141 >>> from os.path import exists |
|
1142 \end{lstlisting} |
|
1143 \end{frame} |
|
1144 |
|
1145 \begin{frame} |
|
1146 \frametitle{Modules: Standard library} |
|
1147 \begin{itemize} |
|
1148 \item Very powerful, ``Batteries included'' |
|
1149 \item Some standard modules: |
|
1150 \begin{itemize} |
|
1151 \item Math: \typ{math}, \typ{random} |
|
1152 \item Internet access: \typ{urllib2}, \typ{smtplib} |
|
1153 \item System, Command line arguments: \typ{sys} |
|
1154 \item Operating system interface: \typ{os} |
|
1155 \item Regular expressions: \typ{re} |
|
1156 \item Compression: \typ{gzip}, \typ{zipfile}, and \typ{tarfile} |
|
1157 \item And a whole lot more! |
|
1158 \end{itemize} |
|
1159 \item Check out the Python Library reference: |
|
1160 \url{http://docs.python.org/library/} |
|
1161 \end{itemize} |
|
1162 \end{frame} |
|
1163 |
|
1164 \begin{frame}[fragile] |
|
1165 {Modules of special interest} |
|
1166 \begin{description}[matplotlibfor2d] |
|
1167 |
|
1168 \item[\typ{numpy}] Efficient, powerful numeric arrays |
|
1169 |
|
1170 \item[\typ{matplotlib}] Easy, interactive, 2D plotting |
|
1171 |
|
1172 \item[\typ{scipy}] statistics, optimization, integration, linear |
|
1173 algebra, Fourier transforms, signal and image processing, |
|
1174 genetic algorithms, ODE solvers, special functions, and more |
|
1175 |
|
1176 \item[Mayavi] Easy, interactive, 3D plotting |
|
1177 |
|
1178 \end{description} |
|
1179 \end{frame} |
|
1180 |
|
1181 \begin{frame}[fragile] |
|
1182 {Creating your own modules} |
|
1183 \begin{itemize} |
|
1184 \item Define variables, functions and classes in a file with a |
|
1185 \typ{.py} extension |
|
1186 \item This file becomes a module! |
|
1187 \item Accessible when in the current directory |
|
1188 \item Use \typ{cd} in IPython to change directory |
|
1189 |
|
1190 \item Naming your module |
|
1191 \end{itemize} |
|
1192 \end{frame} |
|
1193 |
|
1194 \begin{frame}[fragile] |
|
1195 \frametitle{Modules: example} |
|
1196 \begin{lstlisting} |
|
1197 # --- arith.py --- |
|
1198 def gcd(a, b): |
|
1199 if a%b == 0: return b |
|
1200 return gcd(b, a%b) |
|
1201 def lcm(a, b): |
|
1202 return a*b/gcd(a, b) |
|
1203 # ------------------ |
|
1204 >>> import arith |
|
1205 >>> arith.gcd(26, 65) |
|
1206 13 |
|
1207 >>> arith.lcm(26, 65) |
|
1208 130 |
|
1209 \end{lstlisting} |
|
1210 \end{frame} |
|
1211 |
|
1212 \begin{frame}[fragile] |
|
1213 \frametitle{Problem 5.1} |
|
1214 |
|
1215 Put all the functions you have written so far as part of the problems |
|
1216 into one module called \typ{iitb.py} and use this module from IPython. |
|
1217 |
|
1218 \inctime{20} |
|
1219 \end{frame} |
|
1220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1221 % TIME: 20 m, running 225m |
|
1222 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
|
1223 |
|
1224 \begin{frame} |
|
1225 \frametitle{Did we meet the goal?} |
|
1226 \tableofcontents |
|
1227 % You might wish to add the option [pausesections] |
|
1228 \end{frame} |
|
1229 |
|
1230 \begin{frame} |
|
1231 {Tomorrow} |
|
1232 \begin{itemize} |
|
1233 \item Plotting: 2D, 3D |
|
1234 \item NumPy, SciPy |
|
1235 \item Dictionary, Set |
|
1236 \item Debugging |
|
1237 \item Testing |
|
1238 \item \ldots |
|
1239 \end{itemize} |
|
1240 11:30--13:00 Discussion of answers to problems OPTIONAL |
|
1241 \end{frame} |
|
1242 \end{document} |
|
1243 |
|
1244 |
|
1245 \begin{frame}[fragile] |
|
1246 \frametitle{More on functions} |
|
1247 \begin{itemize} |
|
1248 \item Support default and keyword arguments |
|
1249 \item Scope of variables in the function is local |
|
1250 \item Mutable items are \alert{passed by reference} |
|
1251 \item First line after definition may be a documentation string |
|
1252 (\alert{recommended!}) |
|
1253 \item Function definition and execution defines a name bound to the |
|
1254 function |
|
1255 \item You \emph{can} assign a variable to a function! |
|
1256 \end{itemize} |
|
1257 \end{frame} |
|
1258 |
|
1259 |
|
1260 \begin{frame}[fragile] |
|
1261 \frametitle{Functions: default arguments} |
|
1262 \begin{lstlisting} |
|
1263 def ask_ok(prompt, retries=4, complaint='Yes or no!'): |
|
1264 while True: |
|
1265 ok = raw_input(prompt) |
|
1266 if ok in ('y', 'ye', 'yes'): |
|
1267 return True |
|
1268 if ok in ('n', 'no', 'nop', 'nope'): |
|
1269 return False |
|
1270 retries = retries - 1 |
|
1271 if retries < 0: |
|
1272 raise IOError, 'bad user' |
|
1273 print complaint |
|
1274 \end{lstlisting} |
|
1275 \end{frame} |
|
1276 |
|
1277 \begin{frame}[fragile] |
|
1278 \frametitle{Functions: keyword arguments} |
|
1279 \begin{lstlisting} |
|
1280 def parrot(voltage, state='a stiff', |
|
1281 action='voom', type='Norwegian Blue'): |
|
1282 print "-- This parrot wouldn't", action, |
|
1283 print "if you put", voltage, "Volts through it." |
|
1284 print "-- Lovely plumage, the", type |
|
1285 print "-- It's", state, "!" |
|
1286 |
|
1287 parrot(1000) |
|
1288 parrot(action = 'VOOOOOM', voltage = 1000000) |
|
1289 parrot('a thousand', state = 'pushing up the daisies') |
|
1290 parrot('a million', 'bereft of life', 'jump') |
|
1291 \end{lstlisting} |
|
1292 \end{frame} |
|
1293 |
|
1294 \begin{frame}[fragile] |
|
1295 \frametitle{Functions: arbitrary argument lists} |
|
1296 \begin{itemize} |
|
1297 \item Arbitrary number of arguments using \verb+*args+ or |
|
1298 \verb+*whatever+ |
|
1299 \item Keyword arguments using \verb+**kw+ |
|
1300 \item Given a tuple/dict how do you call a function? |
|
1301 \begin{itemize} |
|
1302 \item Using argument unpacking |
|
1303 \item For positional arguments: \verb+foo(*[5, 10])+ |
|
1304 \item For keyword args: \verb+foo(**{'a':5, 'b':10})+ |
|
1305 \end{itemize} |
|
1306 \end{itemize} |
|
1307 \begin{lstlisting} |
|
1308 def foo(a=10, b=100): |
|
1309 print a, b |
|
1310 def func(*args, **keyword): |
|
1311 print args, keyword |
|
1312 # Unpacking: |
|
1313 args = [5, 10] |
|
1314 foo(*args) |
|
1315 kw = {'a':5, 'b':10} |
|
1316 foo(**kw) |
|
1317 \end{lstlisting} |
|
1318 \end{frame} |
|
1319 |
|
1320 \subsection{Modules, exceptions, classes} |
|
1321 |
|
1322 \begin{frame} |
|
1323 \frametitle{Modules} |
|
1324 \begin{itemize} |
|
1325 \item Define variables, functions and classes in a file with a |
|
1326 \typ{.py} extension |
|
1327 \item This file becomes a module! |
|
1328 \item Modules are searched in the following: |
|
1329 \begin{itemize} |
|
1330 \item Current directory |
|
1331 \item Standard: \typ{/usr/lib/python2.3/site-packages/} etc. |
|
1332 \item Directories specified in PYTHONPATH |
|
1333 \item \typ{sys.path}: current path settings (from the \typ{sys} |
|
1334 module) |
|
1335 \end{itemize} |
|
1336 \item The \typ{import} keyword ``loads'' a module |
|
1337 \item One can also use: |
|
1338 \mbox{\typ{from module import name1, name2, name2}}\\ |
|
1339 where \typ{name1} etc. are names in the module, ``module'' |
|
1340 \item \typ{from module import *} \ --- imports everything from module, |
|
1341 \alert{use only in interactive mode} |
|
1342 \end{itemize} |
|
1343 \end{frame} |
|
1344 |
|
1345 \begin{frame}[fragile] |
|
1346 \frametitle{Modules: example} |
|
1347 \begin{lstlisting} |
|
1348 # --- foo.py --- |
|
1349 some_var = 1 |
|
1350 def fib(n): # write Fibonacci series up to n |
|
1351 """Print a Fibonacci series up to n.""" |
|
1352 a, b = 0, 1 |
|
1353 while b < n: |
|
1354 print b, |
|
1355 a, b = b, a+b |
|
1356 # EOF |
|
1357 |
|
1358 >>> import foo |
|
1359 >>> foo.fib(10) |
|
1360 1 1 2 3 5 8 |
|
1361 >>> foo.some_var |
|
1362 1 |
|
1363 \end{lstlisting} |
|
1364 \end{frame} |
|
1365 |
|
1366 \begin{frame}[fragile] |
|
1367 \frametitle{Namespaces} |
|
1368 \begin{itemize} |
|
1369 \item A mapping from names to objects |
|
1370 \item Modules introduce a namespace |
|
1371 \item So do classes |
|
1372 \item The running script's namespace is \verb+__main__+ |
|
1373 \item A modules namespace is identified by its name |
|
1374 \item The standard functions (like \typ{len}) are in the |
|
1375 \verb+__builtin__+ namespace |
|
1376 \item Namespaces help organize different names and their bindings to |
|
1377 different objects |
|
1378 \end{itemize} |
|
1379 \end{frame} |
|
1380 |
|
1381 \begin{frame} |
|
1382 \frametitle{Exceptions} |
|
1383 \begin{itemize} |
|
1384 \item Python's way of notifying you of errors |
|
1385 \item Several standard exceptions: \typ{SyntaxError}, \typ{IOError} |
|
1386 etc. |
|
1387 \item Users can also \typ{raise} errors |
|
1388 \item Users can create their own exceptions |
|
1389 \item Exceptions can be ``caught'' via \typ{try/except} blocks |
|
1390 \end{itemize} |
|
1391 \end{frame} |
|
1392 |
|
1393 \begin{frame}[fragile] |
|
1394 \frametitle{Exception: examples} |
|
1395 \begin{lstlisting} |
|
1396 >>> 10 * (1/0) |
|
1397 Traceback (most recent call last): |
|
1398 File "<stdin>", line 1, in ? |
|
1399 ZeroDivisionError: integer division or modulo by zero |
|
1400 >>> 4 + spam*3 |
|
1401 Traceback (most recent call last): |
|
1402 File "<stdin>", line 1, in ? |
|
1403 NameError: name 'spam' is not defined |
|
1404 >>> '2' + 2 |
|
1405 Traceback (most recent call last): |
|
1406 File "<stdin>", line 1, in ? |
|
1407 TypeError: cannot concatenate 'str' and 'int' objects |
|
1408 \end{lstlisting} |
|
1409 \end{frame} |
|
1410 |
|
1411 \begin{frame}[fragile] |
|
1412 \frametitle{Exception: examples} |
|
1413 \begin{lstlisting} |
|
1414 >>> while True: |
|
1415 ... try: |
|
1416 ... x = int(raw_input("Enter a number: ")) |
|
1417 ... break |
|
1418 ... except ValueError: |
|
1419 ... print "Invalid number, try again..." |
|
1420 ... |
|
1421 >>> # To raise exceptions |
|
1422 ... raise ValueError, "your error message" |
|
1423 Traceback (most recent call last): |
|
1424 File "<stdin>", line 2, in ? |
|
1425 ValueError: your error message |
|
1426 \end{lstlisting} |
|
1427 \end{frame} |
|
1428 |
|
1429 \begin{frame}[fragile] |
|
1430 \frametitle{Classes: the big picture} |
|
1431 \begin{itemize} |
|
1432 \item Lets you create new data types |
|
1433 \item Class is a template for an object belonging to that class |
|
1434 \item Note: in Python a class is also an object |
|
1435 \item Instantiating a class creates an instance (an object) |
|
1436 \item An instance encapsulates the state (data) and behavior |
|
1437 (methods) |
|
1438 \item Allows you to define an inheritance hierarchy |
|
1439 \begin{itemize} |
|
1440 \item ``A Honda car \alert{is a} car.'' |
|
1441 \item ``A car \alert{is an} automobile.'' |
|
1442 \item ``A Python \alert{is a} reptile.'' |
|
1443 \end{itemize} |
|
1444 \item Programmers need to think OO |
|
1445 \end{itemize} |
|
1446 \end{frame} |
|
1447 |
|
1448 \begin{frame}[fragile] |
|
1449 \frametitle{Classes: what's the big deal?} |
|
1450 \begin{itemize} |
|
1451 \item Lets you create objects that mimic a real problem being |
|
1452 simulated |
|
1453 \item Makes problem solving more natural and elegant |
|
1454 \item Easier to create code |
|
1455 \item Allows for code-reuse |
|
1456 \item Polymorphism |
|
1457 \end{itemize} |
|
1458 \end{frame} |
|
1459 |
|
1460 \begin{frame}[fragile] |
|
1461 \frametitle{Class definition and instantiation} |
|
1462 \begin{itemize} |
|
1463 \item Class definitions when executed create class objects |
|
1464 \item Instantiating the class object creates an instance of the |
|
1465 class |
|
1466 \end{itemize} |
|
1467 \footnotesize |
|
1468 \begin{lstlisting} |
|
1469 class Foo(object): |
|
1470 pass |
|
1471 # class object created. |
|
1472 # Create an instance of Foo. |
|
1473 f = Foo() |
|
1474 # Can assign an attribute to the instance |
|
1475 f.a = 100 |
|
1476 print f.a |
|
1477 100 |
|
1478 \end{lstlisting} |
|
1479 \end{frame} |
|
1480 |
|
1481 \begin{frame}[fragile] |
|
1482 \frametitle{Classes \ldots} |
|
1483 \begin{itemize} |
|
1484 \item All attributes are accessed via the \typ{object.attribute} |
|
1485 syntax |
|
1486 \item Both class and instance attributes are supported |
|
1487 \item \emph{Methods} represent the behavior of an object: crudely |
|
1488 think of them as functions ``belonging'' to the object |
|
1489 \item All methods in Python are ``virtual'' |
|
1490 \item Inheritance through subclassing |
|
1491 \item Multiple inheritance is supported |
|
1492 \item No special public and private attributes: only good |
|
1493 conventions |
|
1494 \begin{itemize} |
|
1495 \item \verb+object.public()+: public |
|
1496 \item \verb+object._private()+ \& \verb+object.__priv()+: |
|
1497 non-public |
|
1498 \end{itemize} |
|
1499 \end{itemize} |
|
1500 \end{frame} |
|
1501 |
|
1502 \begin{frame}[fragile] |
|
1503 \frametitle{Classes: examples} |
|
1504 \begin{lstlisting} |
|
1505 class MyClass(object): |
|
1506 """Example class (this is the class docstring).""" |
|
1507 i = 12345 # A class attribute |
|
1508 def f(self): |
|
1509 """This is the method docstring""" |
|
1510 return 'hello world' |
|
1511 |
|
1512 >>> a = MyClass() # creates an instance |
|
1513 >>> a.f() |
|
1514 'hello world' |
|
1515 >>> # a.f() is equivalent to MyClass.f(a) |
|
1516 ... # This also explains why f has a 'self' argument. |
|
1517 ... MyClass.f(a) |
|
1518 'hello world' |
|
1519 \end{lstlisting} |
|
1520 \end{frame} |
|
1521 |
|
1522 \begin{frame}[fragile] |
|
1523 \frametitle{Classes (continued)} |
|
1524 \begin{itemize} |
|
1525 \item \typ{self} is \alert{conventionally} the first argument for a |
|
1526 method |
|
1527 \item In previous example, \typ{a.f} is a method object |
|
1528 \item When \typ{a.f} is called, it is passed the instance \typ{a} as |
|
1529 the first argument |
|
1530 \item If a method called \verb+__init__+ exists, it is called when |
|
1531 the object is created |
|
1532 \item If a method called \verb+__del__+ exists, it is called before |
|
1533 the object is garbage collected |
|
1534 \item Instance attributes are set by simply ``setting'' them in |
|
1535 \typ{self} |
|
1536 \item Other special methods (by convention) like \verb+__add__+ let |
|
1537 you define numeric types: |
|
1538 {\footnotesize \url{http://docs.python.org/ref/specialnames.html} |
|
1539 \\ \url{http://docs.python.org/ref/numeric-types.html} |
|
1540 } |
|
1541 \end{itemize} |
|
1542 \end{frame} |
|
1543 |
|
1544 \begin{frame}[fragile] |
|
1545 \frametitle{Classes: examples} |
|
1546 \begin{lstlisting} |
|
1547 class Bag(MyClass): # Shows how to derive classes |
|
1548 def __init__(self): # called on object creation. |
|
1549 self.data = [] # an instance attribute |
|
1550 def add(self, x): |
|
1551 self.data.append(x) |
|
1552 def addtwice(self, x): |
|
1553 self.add(x) |
|
1554 self.add(x) |
|
1555 >>> a = Bag() |
|
1556 >>> a.f() # Inherited method |
|
1557 'hello world' |
|
1558 >>> a.add(1); a.addtwice(2) |
|
1559 >>> a.data |
|
1560 [1, 2, 2] |
|
1561 \end{lstlisting} |
|
1562 \end{frame} |
|
1563 |
|
1564 \begin{frame}[fragile] |
|
1565 \frametitle{Derived classes} |
|
1566 \begin{itemize} |
|
1567 \item Call the parent's \verb+__init__+ if needed |
|
1568 \item If you don't need a new constructor, no need to define it in subclass |
|
1569 \item Can also use the \verb+super+ built-in function |
|
1570 \end{itemize} |
|
1571 \begin{lstlisting} |
|
1572 class AnotherBag(Bag): |
|
1573 def __init__(self): |
|
1574 # Must call parent's __init__ explicitly |
|
1575 Bag.__init__(self) |
|
1576 # Alternatively use this: |
|
1577 super(AnotherBag, self).__init__() |
|
1578 # Now setup any more data. |
|
1579 self.more_data = [] |
|
1580 \end{lstlisting} |
|
1581 \end{frame} |
|
1582 |
|
1583 \begin{frame}[fragile] |
|
1584 \frametitle{Classes: polymorphism} |
|
1585 \begin{lstlisting} |
|
1586 class Drawable(object): |
|
1587 def draw(self): |
|
1588 # Just a specification. |
|
1589 pass |
|
1590 \end{lstlisting} |
|
1591 \mode<presentation>{\pause} |
|
1592 \begin{lstlisting} |
|
1593 class Square(Drawable): |
|
1594 def draw(self): |
|
1595 # draw a square. |
|
1596 class Circle(Drawable): |
|
1597 def draw(self): |
|
1598 # draw a circle. |
|
1599 \end{lstlisting} |
|
1600 \mode<presentation>{\pause} |
|
1601 \begin{lstlisting} |
|
1602 class Artist(Drawable): |
|
1603 def draw(self): |
|
1604 for obj in self.drawables: |
|
1605 obj.draw() |
|
1606 \end{lstlisting} |
|
1607 \end{frame} |
|
1608 |
|
1609 \subsection{Miscellaneous} |
|
1610 |
|
1611 \begin{frame}[fragile] |
|
1612 \frametitle{Stand-alone scripts} |
|
1613 Consider a file \typ{f.py}: |
|
1614 \begin{lstlisting} |
|
1615 #!/usr/bin/env python |
|
1616 """Module level documentation.""" |
|
1617 # First line tells the shell that it should use Python |
|
1618 # to interpret the code in the file. |
|
1619 def f(): |
|
1620 print "f" |
|
1621 |
|
1622 # Check if we are running standalone or as module. |
|
1623 # When imported, __name__ will not be '__main__' |
|
1624 if __name__ == '__main__': |
|
1625 # This is not executed when f.py is imported. |
|
1626 f() |
|
1627 \end{lstlisting} |
|
1628 \end{frame} |
|
1629 |
|
1630 \begin{frame}[fragile] |
|
1631 \frametitle{List comprehensions} |
|
1632 \begin{lstlisting} |
|
1633 >>> veg = ['tomato', 'cabbage', 'carrot', 'potato'] |
|
1634 >>> [x.upper() for x in veg] |
|
1635 ['TOMATO', 'CABBAGE', 'CARROT', 'POTATO'] |
|
1636 >>> vec = range(0, 8) |
|
1637 >>> even = [x for x in vec if x%2 == 0] |
|
1638 >>> even |
|
1639 [0, 2, 4, 6] |
|
1640 >>> [x*x for x in even] |
|
1641 [0, 4, 16, 36] |
|
1642 >>> odd = [x for x in vec if x%2 == 1] |
|
1643 >>> odd |
|
1644 [1, 3, 5, 7] |
|
1645 >>> [x*y for x in even for y in odd] |
|
1646 [0, 0, 0, 0, 2, 6, 10, 14, 4, 12, 20, 28, 6, 18,30,42] |
|
1647 \end{lstlisting} |
|
1648 \end{frame} |
|
1649 |
|
1650 \begin{frame}[fragile] |
|
1651 \frametitle{More IPython features} |
|
1652 \begin{itemize} |
|
1653 \item Input and output caching: |
|
1654 \begin{itemize} |
|
1655 \item \verb+In+: a list of all entered input |
|
1656 \item \verb+Out+: a dict of all output |
|
1657 \item \verb+_+, \verb+__+, \verb+__+ are the last three results as |
|
1658 is \verb+_N+ |
|
1659 \item \verb+%hist [-n]+ macro shows previous history, \verb+-n+ |
|
1660 suppresses line number information |
|
1661 \end{itemize} |
|
1662 \item Log the session using \verb+%logstart+, \verb+%logon+ and |
|
1663 \verb+%logoff+ |
|
1664 \item \verb+%run [options] file[.py]+ -- running Python code |
|
1665 \begin{itemize} |
|
1666 \item \verb+%run -d [-b<N>]+: debug script with pdb |
|
1667 \verb+N+ is the line number to break at (defaults to 1) |
|
1668 \item \verb+%run -t+: time the script |
|
1669 \item \verb+%run -p+: Profile the script |
|
1670 \end{itemize} |
|
1671 \item \verb+%prun+ runs a statement/expression under the profiler |
|
1672 \item \verb+%macro [options] macro_name n1-n2 n3-n4 n6+ save specified |
|
1673 lines to a macro with name \verb+macro_name+ |
|
1674 \end{itemize} |
|
1675 \end{frame} |
|
1676 |
|
1677 \begin{frame}[fragile] |
|
1678 \frametitle{More IPython features \ldots} |
|
1679 \begin{itemize} |
|
1680 \item \verb+%edit [options] [args]+: edit lines of code or file |
|
1681 specified in editor (configure editor via \verb+$EDITOR+) |
|
1682 \item \verb+%cd+ changes directory, see also \verb+%pushd, %popd, %dhist+ |
|
1683 \item Shell access |
|
1684 \begin{itemize} |
|
1685 \item \verb+!command+ runs a shell command and returns its output |
|
1686 \item \verb+files = %sx ls+ or \verb+files = !ls+ sets |
|
1687 \verb+files+ to all result of the \verb+ls+ command |
|
1688 \item \verb+%sx+ is quiet |
|
1689 \item \verb+!ls $files+ passes the \verb+files+ variable to the |
|
1690 shell command |
|
1691 \item \verb+%alias alias_name cmd+ creates an alias for a system |
|
1692 command |
|
1693 \end{itemize} |
|
1694 \item \verb+%colors+ lets you change the color scheme to |
|
1695 \verb+NoColor, Linux, LightBG+ |
|
1696 \end{itemize} |
|
1697 \end{frame} |
|
1698 |
|
1699 \begin{frame}[fragile] |
|
1700 \frametitle{More IPython features \ldots} |
|
1701 \begin{itemize} |
|
1702 \item Use \verb+;+ at the end of a statement to suppress printing |
|
1703 output |
|
1704 \item \verb+%bookmark+: store a bookmarked location, for use with \verb+%cd+ |
|
1705 \item \verb+%who, %whos+: print information on variables |
|
1706 \item \verb+%save [options] filename n1-n2 n3-n4+: save lines to a |
|
1707 file |
|
1708 \item \verb+%time statement+: Time execution of a Python statement or |
|
1709 expression |
|
1710 \item \verb+%timeit [-n<N> -r<R> [-t|-c]] statement+: time execution |
|
1711 using Python's timeit module |
|
1712 \item Can define and use profiles to setup IPython differently: |
|
1713 \verb+math, scipy, numeric, pysh+ etc. |
|
1714 \item \verb+%magic+: \alert{Show help on all magics} |
|
1715 \end{itemize} |
|
1716 \end{frame} |
|
1717 |
|
1718 \begin{frame}[fragile] |
|
1719 \frametitle{File handling} |
|
1720 \begin{lstlisting} |
|
1721 >>> # Reading files: |
|
1722 ... f = open('/path/to/file_name') |
|
1723 >>> data = f.read() # Read entire file. |
|
1724 >>> line = f.readline() # Read one line. |
|
1725 >>> # Read entire file appending each line into a list |
|
1726 ... lines = f.readlines() |
|
1727 >>> f.close() # close the file. |
|
1728 >>> # Writing files: |
|
1729 ... f = open('/path/to/file_name', 'w') |
|
1730 >>> f.write('hello world\n') |
|
1731 \end{lstlisting} |
|
1732 \begin{itemize} |
|
1733 \item \typ{tell()}: returns int of current position |
|
1734 \item \typ{seek(pos)}: moves current position to specified byte |
|
1735 \item Call \typ{close()} when done using a file |
|
1736 \end{itemize} |
|
1737 \end{frame} |
|
1738 |
|
1739 \begin{frame}[fragile] |
|
1740 \frametitle{Math} |
|
1741 \begin{itemize} |
|
1742 \item \typ{math} module provides basic math routines for |
|
1743 floats |
|
1744 \item \typ{cmath} module provides math routies for complex |
|
1745 numbers |
|
1746 \item \typ{random}: provides pseudo-random number generators |
|
1747 for various distributions |
|
1748 \item These are always available and part of the standard library |
|
1749 \item More serious math is provided by the NumPy/SciPy modules -- |
|
1750 these are not standard and need to be installed separately |
|
1751 \end{itemize} |
|
1752 \end{frame} |
|
1753 |
|
1754 \begin{frame}[fragile] |
|
1755 \frametitle{Timing and profiling} |
|
1756 \begin{itemize} |
|
1757 \item Timing code: use the \typ{time} module |
|
1758 \item Read up on \typ{time.time()} and \typ{time.clock()} |
|
1759 \item \typ{timeit}: is a better way of doing timing |
|
1760 \item IPython has handy \typ{time} and \typ{timeit} macros (type |
|
1761 \typ{timeit?} for help) |
|
1762 \item IPython lets you debug and profile code via the \typ{run} |
|
1763 macro (type \typ{run?} on the prompt to learn more) |
|
1764 \end{itemize} |
|
1765 \end{frame} |
|
1766 |
|
1767 \begin{frame}[fragile] |
|
1768 \frametitle{Odds and ends} |
|
1769 \begin{itemize} |
|
1770 \item \typ{dir([object])} function: attributes of given object |
|
1771 \item \typ{type(object)}: returns type information |
|
1772 \item \typ{str(), repr()}: convert object to string representation |
|
1773 \item \typ{isinstance, issubclass} |
|
1774 \item \typ{assert} statements let you do debugging assertions in |
|
1775 code |
|
1776 \item \typ{csv} module: reading and writing CSV files |
|
1777 \item \typ{pickle}: lets you save and load Python objects |
|
1778 (\alert{serialization}) |
|
1779 \item \typ{sys.argv}: command line arguments |
|
1780 \item \typ{os.path}: common path manipulations |
|
1781 \item Check out the Python Library reference: |
|
1782 \url{http://docs.python.org/lib/lib.html} |
|
1783 \end{itemize} |
|
1784 \end{frame} |
|
1785 |
|
1786 \begin{frame}[fragile] |
|
1787 \frametitle{Test driven development (TDD)} |
|
1788 \begin{itemize} |
|
1789 \item Why? |
|
1790 \begin{itemize} |
|
1791 |
|
1792 \item Forces you to write reusable code! |
|
1793 |
|
1794 \item Think about the API |
|
1795 |
|
1796 \item More robust |
|
1797 |
|
1798 \item Makes refactoring very easy |
|
1799 |
|
1800 \end{itemize} |
|
1801 \item How? Python offers three major ways of doing this |
|
1802 \begin{itemize} |
|
1803 \item doctest |
|
1804 \item unittest |
|
1805 \item nosetest (and similar like py.test) |
|
1806 \end{itemize} |
|
1807 |
|
1808 \item Test every piece of functionality you offer |
|
1809 |
|
1810 \item This isn't a formal introduction but more a practical one |
|
1811 |
|
1812 \end{itemize} |
|
1813 \end{frame} |
|
1814 |
|
1815 \begin{frame}[fragile] |
|
1816 \frametitle{Unit test} |
|
1817 \begin{lstlisting} |
|
1818 import unittest |
|
1819 |
|
1820 class MyTestCase(unittest.TestCase): |
|
1821 def setUp(self): |
|
1822 # Called *before* each test_* |
|
1823 def tearDown(self): |
|
1824 # Called *after* each test_* |
|
1825 def test_something(self): |
|
1826 "docstring" |
|
1827 # Test code. |
|
1828 self.assertEqual(x, y) |
|
1829 self.assertRaises(ValueError, func, arg1, arg2 ...) |
|
1830 |
|
1831 if __name__ == '__main__': |
|
1832 unittest.main() |
|
1833 \end{lstlisting} |
|
1834 \end{frame} |
|
1835 |
|
1836 \begin{frame}[fragile] |
|
1837 \frametitle{Nosetest} |
|
1838 \begin{lstlisting} |
|
1839 import particle |
|
1840 def test_particle(): |
|
1841 # Use asserts here. |
|
1842 p = particle.Particle(1.0) |
|
1843 assert p.property[0] == 1.0 |
|
1844 assert p.property[2] == 0.0 |
|
1845 |
|
1846 if __name__ == '__main__': |
|
1847 import nose |
|
1848 nose.main() |
|
1849 \end{lstlisting} |
|
1850 \end{frame} |
|
1851 |
|
1852 \begin{frame}[fragile] |
|
1853 \frametitle{Testing} |
|
1854 \begin{itemize} |
|
1855 \item More details: see library reference and search for nosetest |
|
1856 \end{itemize} |
|
1857 \end{frame} |
|
1858 |
|
1859 \section{Numerics \& Plotting} |
|
1860 |
|
1861 \subsection{NumPy Arrays} |
|
1862 |
|
1863 \newcommand{\num}{\texttt{numpy}} |
|
1864 |
|
1865 \begin{frame} |
|
1866 \frametitle{The \num\ module} |
|
1867 \begin{itemize} |
|
1868 \item Manipulating large Python lists for scientific computing is |
|
1869 \alert{slow} |
|
1870 \item Most complex computations can be reduced to a few standard |
|
1871 operations |
|
1872 \item The \num\ module provides: |
|
1873 \begin{itemize} |
|
1874 \item An efficient and powerful array type for various common data |
|
1875 types |
|
1876 \item Abstracts out the most commonly used standard operations on |
|
1877 arrays |
|
1878 \end{itemize} |
|
1879 \item Numeric was the first, then came \texttt{numarray}. |
|
1880 \texttt{numpy} is the latest and is the future |
|
1881 \item This course uses \num\ and only covers the absolute basics |
|
1882 \end{itemize} |
|
1883 \end{frame} |
|
1884 |
|
1885 \begin{frame} |
|
1886 \frametitle{Basic concepts} |
|
1887 \begin{itemize} |
|
1888 \item \num\ arrays are of a fixed size (\typ{arr.size}) and have the |
|
1889 same type (\typ{arr.dtype}) |
|
1890 \item \num\ arrays may have arbitrary dimensionality |
|
1891 \item The \typ{shape} of an array is the extent (length) of the |
|
1892 array along each dimension |
|
1893 \item The \typ{rank(arr)} of an array is the ``dimensionality'' of the |
|
1894 array |
|
1895 \item The \typ{arr.itemsize} is the number of bytes (8-bits) used for |
|
1896 each element of the array |
|
1897 \item \alert{Note:} The \typ{shape} and \typ{rank} may change as |
|
1898 long as the \typ{size} of the array is fixed |
|
1899 \item \alert{Note:} \typ{len(arr) != arr.size} in general |
|
1900 \item \alert{Note:} By default array operations are performed |
|
1901 \alert{elementwise} |
|
1902 \item Indices start from 0 |
|
1903 \end{itemize} |
|
1904 \end{frame} |
|
1905 |
|
1906 \begin{frame}[fragile] |
|
1907 \frametitle{Examples of \num} |
|
1908 \begin{lstlisting} |
|
1909 # Simple array math example |
|
1910 >>> from numpy import * |
|
1911 >>> a = array([1,2,3,4]) |
|
1912 >>> b = array([2,3,4,5]) |
|
1913 >>> a + b # Element wise addition! |
|
1914 array([3, 5, 7, 9]) |
|
1915 |
|
1916 >>> print pi, e # Pi and e are defined. |
|
1917 3.14159265359 2.71828182846 |
|
1918 # Create array from 0 to 10 |
|
1919 >>> x = arange(0.0, 10.0, 0.05) |
|
1920 >>> x *= 2*pi/10 # multiply array by scalar value |
|
1921 array([ 0.,0.0314,...,6.252]) |
|
1922 # apply functions to array. |
|
1923 >>> y = sin(x) |
|
1924 \end{lstlisting} |
|
1925 \end{frame} |
|
1926 |
|
1927 \begin{frame}[fragile] |
|
1928 \frametitle{More examples of \num} |
|
1929 \vspace*{-8pt} |
|
1930 \begin{lstlisting} |
|
1931 # Size, shape, rank, type etc. |
|
1932 >>> x = array([1., 2, 3, 4]) |
|
1933 >>> size(x) |
|
1934 4 |
|
1935 >>> x.dtype # or x.dtype.char |
|
1936 'd' |
|
1937 >>> x.shape |
|
1938 (4,) |
|
1939 >>> print rank(x), x.itemsize |
|
1940 1 8 |
|
1941 >>> x.tolist() |
|
1942 [1.0, 2.0, 3.0, 4.0] |
|
1943 # Array indexing |
|
1944 >>> x[0] = 10 |
|
1945 >>> print x[0], x[-1] |
|
1946 10.0 4.0 |
|
1947 \end{lstlisting} |
|
1948 \end{frame} |
|
1949 |
|
1950 \begin{frame}[fragile] |
|
1951 \frametitle{Multi-dimensional arrays} |
|
1952 \begin{lstlisting} |
|
1953 >>> a = array([[ 0, 1, 2, 3], |
|
1954 ... [10,11,12,13]]) |
|
1955 >>> a.shape # (rows, columns) |
|
1956 (2, 4) |
|
1957 # Accessing and setting values |
|
1958 >>> a[1,3] |
|
1959 13 |
|
1960 >>> a[1,3] = -1 |
|
1961 >>> a[1] # The second row |
|
1962 array([10,11,12,-1]) |
|
1963 |
|
1964 # Flatten/ravel arrays to 1D arrays |
|
1965 >>> a.flat # or ravel(a) |
|
1966 array([0,1,2,3,10,11,12,-1]) |
|
1967 # Note: flat references original memory |
|
1968 \end{lstlisting} |
|
1969 \end{frame} |
|
1970 |
|
1971 \begin{frame}[fragile] |
|
1972 \frametitle{Slicing arrays} |
|
1973 \begin{lstlisting} |
|
1974 >>> a = array([[1,2,3], [4,5,6], [7,8,9]]) |
|
1975 >>> a[0,1:3] |
|
1976 array([2, 3]) |
|
1977 >>> a[1:,1:] |
|
1978 array([[5, 6], |
|
1979 [8, 9]]) |
|
1980 >>> a[:,2] |
|
1981 array([3, 6, 9]) |
|
1982 # Striding... |
|
1983 >>> a[0::2,0::2] |
|
1984 array([[1, 3], |
|
1985 [7, 9]]) |
|
1986 # All these slices are references to the same memory! |
|
1987 \end{lstlisting} |
|
1988 \end{frame} |
|
1989 |
|
1990 % \begin{frame}[fragile] |
|
1991 % \frametitle{Array types and typecodes} |
|
1992 % \begin{tabular}[c]{|c|c|p{2.75in}|} |
|
1993 % \hline |
|
1994 % Character & Bits (bytes) & Type name \\ |
|
1995 % \hline |
|
1996 % D & 128 (16) & \typ{Complex, Complex64}\\ |
|
1997 % F & 64 (8) & \typ{Complex0, Complex8, Complex16} \\ |
|
1998 % d & 64 (8) & \typ{Float, Float64} \\ |
|
1999 % f & 32 (4) & \typ{Float0, Float8, Float16} \\ |
|
2000 % i & 32 (4) & \typ{Int32} \\ |
|
2001 % l & 32 (4) & \typ{Int} \\ |
|
2002 % O & 4 (1) & \typ{PyObject} \\ |
|
2003 % %b 8 (1) UnsignedInt8 |
|
2004 % %1 (one) 8 (1) Int8 |
|
2005 % %s 16 (2) Int16 |
|
2006 % \hline |
|
2007 % \end{tabular} |
|
2008 % \begin{lstlisting} |
|
2009 % # Examples |
|
2010 % >>> f = array([1,2,3], Float32) |
|
2011 % >>> c = array([1,2,3], Complex32) |
|
2012 % >>> print f, c |
|
2013 % [ 1. 2. 3.] [ 1.+0.j 2.+0.j 3.+0.j] |
|
2014 % \end{lstlisting} |
|
2015 % \end{frame} |
|
2016 |
|
2017 \begin{frame}[fragile] |
|
2018 \frametitle{Array creation functions} |
|
2019 \begin{itemize} |
|
2020 \item \typ{array(object, dtype=None, copy=1,order=None, subok=0,ndmin=0)} |
|
2021 \item \typ{arange(start, stop=None, step=1, dtype=None)} |
|
2022 \item \typ{linspace(start, stop, num=50, endpoint=True, retstep=False)} |
|
2023 \item \typ{ones(shape, dtype=None, order='C')} |
|
2024 \item \typ{zeros((d1,...,dn),dtype=float,order='C')} |
|
2025 \item \typ{identity(n)} |
|
2026 \item \typ{empty((d1,...,dn),dtype=float,order='C')} |
|
2027 \item \typ{ones\_like(x)}, \typ{zeros\_like(x)}, \typ{empty\_like(x)} |
|
2028 \end{itemize} |
|
2029 \end{frame} |
|
2030 |
|
2031 \begin{frame}[fragile] |
|
2032 \frametitle{Array math} |
|
2033 \begin{itemize} |
|
2034 \item Basic \alert{elementwise} math (given two arrays \typ{a, b}): |
|
2035 \begin{itemize} |
|
2036 \item \typ{a + b $\rightarrow$ add(a, b)} |
|
2037 \item \typ{a - b, $\rightarrow$ subtract(a, b)} |
|
2038 \item \typ{a * b, $\rightarrow$ multiply(a, b)} |
|
2039 \item \typ{a / b, $\rightarrow$ divide(a, b)} |
|
2040 \item \typ{a \% b, $\rightarrow$ remainder(a, b)} |
|
2041 \item \typ{a ** b, $\rightarrow$ power(a, b)} |
|
2042 \end{itemize} |
|
2043 \item Inplace operators: \typ{a += b}, or \typ{add(a, b, |
|
2044 a)} etc. |
|
2045 \item Logical operations: \typ{equal (==)}, \typ{not\_equal (!=)}, |
|
2046 \typ{less (<)}, \typ{greater (>)} etc. |
|
2047 \item Trig and other functions: \typ{sin(x), arcsin(x), sinh(x), |
|
2048 exp(x), sqrt(x)} etc. |
|
2049 \item \typ{sum(x, axis=0), product(x, axis=0)}: sum and product of array elements |
|
2050 \item \typ{dot(a, b)} |
|
2051 \end{itemize} |
|
2052 \end{frame} |
|
2053 |
|
2054 \begin{frame}[fragile] |
|
2055 \frametitle{Advanced} |
|
2056 \begin{itemize} |
|
2057 \item Only scratched the surface of \num |
|
2058 \item Ufunc methods: \typ{reduce, accumulate, outer, reduceat} |
|
2059 \item Typecasting |
|
2060 \item More functions: \typ{take, choose, where, compress, |
|
2061 concatenate} |
|
2062 \item Array broadcasting and \typ{None} |
|
2063 \end{itemize} |
|
2064 \end{frame} |
|
2065 |
|
2066 \subsection{Plotting: Matplotlib} |
|
2067 |
|
2068 \begin{frame} |
|
2069 \frametitle{About \texttt{matplotlib}} |
|
2070 \begin{itemize} |
|
2071 \item Easy to use, scriptable, ``Matlab-like'' 2D plotting |
|
2072 \item Publication quality figures and interactive capabilities |
|
2073 \item Plots, histograms, power spectra, bar charts, errorcharts, |
|
2074 scatterplots, etc. |
|
2075 \item Also does polar plots, maps, contours |
|
2076 \item Support for simple \TeX\ markup |
|
2077 \item Multiple output backends (images, EPS, SVG, wx, Agg, Tk, GTK) |
|
2078 \item Cross-platform: Linux, Win32, Mac OS X |
|
2079 \item Good idea to use via IPython: \typ{ipython -pylab} |
|
2080 \item From scripts use: \typ{import pylab} |
|
2081 \end{itemize} |
|
2082 \end{frame} |
|
2083 |
|
2084 \begin{frame} |
|
2085 \frametitle{More information} |
|
2086 \begin{itemize} |
|
2087 \item More information here: \url{http://matplotlib.sf.net} |
|
2088 \item \url{http://matplotlib.sf.net/tutorial.html} |
|
2089 \item \url{http://matplotlib.sf.net/screenshots.html} |
|
2090 \end{itemize} |
|
2091 \end{frame} |
|
2092 |
|
2093 \begin{frame}[fragile] |
|
2094 \frametitle{Basic plotting with \texttt{matplotlib}} |
|
2095 \begin{lstlisting} |
|
2096 >>> x = arange(0, 2*pi, 0.05) |
|
2097 >>> plot(x, sin(x)) # Same as plot(x, sin(x), 'b-') |
|
2098 >>> plot(x, sin(x), 'ro') |
|
2099 >>> axis([0,2*pi, -1,1]) |
|
2100 >>> xlabel(r'$\chi$', color='g') |
|
2101 >>> ylabel(r'sin($\chi$)', color='r') |
|
2102 >>> title('A simple figure', fontsize=20) |
|
2103 >>> savefig('/tmp/test.eps') |
|
2104 # Multiple plots in one figure |
|
2105 >>> t = arange(0.0, 5.2, 0.2) |
|
2106 # red dashes, blue squares and green triangles |
|
2107 >>> plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') |
|
2108 \end{lstlisting} |
|
2109 \end{frame} |
|
2110 |
|
2111 \begin{frame}[fragile] |
|
2112 \frametitle{Basic plotting \ldots} |
|
2113 \begin{lstlisting} |
|
2114 # Set properties of objects: |
|
2115 >>> plot(x, sin(x), linewidth=2.0, color='r') |
|
2116 >>> l, = plot(x, sin(x)) |
|
2117 >>> setp(l, linewidth=2.0, color='r') |
|
2118 >>> l.set_linewidth(2.0); l.set_color('r') |
|
2119 >>> draw() # Redraws current figure. |
|
2120 >>> setp(l) # Prints available properties |
|
2121 >>> close() # Closes the figure. |
|
2122 # Multiple figures: |
|
2123 >>> figure(1); plot(x, sin(x)) |
|
2124 >>> figure(2); plot(x, tanh(x)) |
|
2125 >>> figure(1); title('Easy as 1,2,3') |
|
2126 \end{lstlisting} |
|
2127 \end{frame} |
|
2128 |
|
2129 \begin{frame}[fragile] |
|
2130 \frametitle{Basic plotting \ldots} |
|
2131 \begin{lstlisting} |
|
2132 >>> figure(1) |
|
2133 >>> subplot(211) # Same as subplot(2, 1, 1) |
|
2134 >>> plot(x, cos(5*x)*exp(-x)) |
|
2135 >>> subplot(2, 1, 2) |
|
2136 >>> plot(x, cos(5*x), 'r--', label='cosine') |
|
2137 >>> plot(x, sin(5*x), 'g--', label='sine') |
|
2138 >>> legend() # Or legend(['cosine', 'sine']) |
|
2139 >>> text(1,0, '(1,0)') |
|
2140 >>> axes = gca() # Current axis |
|
2141 >>> fig = gcf() # Current figure |
|
2142 \end{lstlisting} |
|
2143 \end{frame} |
|
2144 |
|
2145 \begin{frame}[fragile] |
|
2146 \frametitle{X-Y plot} |
|
2147 \begin{columns} |
|
2148 \column{0.5\textwidth} |
|
2149 \hspace*{-0.5in} |
|
2150 \includegraphics[height=2in, interpolate=true]{data/xyplot} |
|
2151 \column{0.45\textwidth} |
|
2152 \begin{block}{Example code} |
|
2153 \tiny |
|
2154 \begin{lstlisting} |
|
2155 t1 = arange(0.0, 5.0, 0.1) |
|
2156 t2 = arange(0.0, 5.0, 0.02) |
|
2157 t3 = arange(0.0, 2.0, 0.01) |
|
2158 subplot(211) |
|
2159 plot(t1, cos(2*pi*t1)*exp(-t1), 'bo', |
|
2160 t2, cos(2*pi*t2)*exp(-t2), 'k') |
|
2161 grid(True) |
|
2162 title('A tale of 2 subplots') |
|
2163 ylabel('Damped') |
|
2164 subplot(212) |
|
2165 plot(t3, cos(2*pi*t3), 'r--') |
|
2166 grid(True) |
|
2167 xlabel('time (s)') |
|
2168 ylabel('Undamped') |
|
2169 \end{lstlisting} |
|
2170 \end{block} |
|
2171 \end{columns} |
|
2172 \end{frame} |
|
2173 |
|
2174 \begin{frame}[fragile] \frametitle{Errorbar} |
|
2175 \begin{columns} |
|
2176 \column{0.5\textwidth} |
|
2177 \hspace*{-0.5in} |
|
2178 \includegraphics[height=2in, interpolate=true]{data/errorbar} |
|
2179 \column{0.45\textwidth} |
|
2180 \begin{block}{Example code} |
|
2181 \tiny |
|
2182 \begin{lstlisting} |
|
2183 t = arange(0.1, 4, 0.1) |
|
2184 s = exp(-t) |
|
2185 e = 0.1*abs(randn(len(s))) |
|
2186 f = 0.1*abs(randn(len(s))) |
|
2187 g = 2*e |
|
2188 h = 2*f |
|
2189 errorbar(t, s, [e,g], f, fmt='o') |
|
2190 xlabel('Distance (m)') |
|
2191 ylabel('Height (m)') |
|
2192 title('Mean and standard error '\ |
|
2193 'as a function of distance') |
|
2194 \end{lstlisting} |
|
2195 \end{block} |
|
2196 \end{columns} |
|
2197 \end{frame} |
|
2198 |
|
2199 \begin{frame}[fragile] \frametitle{Semi-log and log-log plots} |
|
2200 \begin{columns} |
|
2201 \column{0.5\textwidth} |
|
2202 \hspace*{-0.5in} |
|
2203 \includegraphics[height=2in, interpolate=true]{data/log} |
|
2204 \column{0.45\textwidth} |
|
2205 \begin{block}{Example code} |
|
2206 \tiny |
|
2207 \begin{lstlisting} |
|
2208 dt = 0.01 |
|
2209 t = arange(dt, 20.0, dt) |
|
2210 subplot(311) |
|
2211 semilogy(t, exp(-t/5.0)) |
|
2212 ylabel('semilogy') |
|
2213 grid(True) |
|
2214 subplot(312) |
|
2215 semilogx(t, sin(2*pi*t)) |
|
2216 ylabel('semilogx') |
|
2217 grid(True) |
|
2218 # minor grid on too |
|
2219 gca().xaxis.grid(True, which='minor') |
|
2220 subplot(313) |
|
2221 loglog(t, 20*exp(-t/10.0), basex=4) |
|
2222 grid(True) |
|
2223 ylabel('loglog base 4 on x') |
|
2224 \end{lstlisting} |
|
2225 \end{block} |
|
2226 \end{columns} |
|
2227 \end{frame} |
|
2228 |
|
2229 \begin{frame}[fragile] \frametitle{Histogram} |
|
2230 \begin{columns} |
|
2231 \column{0.5\textwidth} |
|
2232 \hspace*{-0.5in} |
|
2233 \includegraphics[height=2in, interpolate=true]{data/histogram} |
|
2234 \column{0.45\textwidth} |
|
2235 \begin{block}{Example code} |
|
2236 \tiny |
|
2237 \begin{lstlisting} |
|
2238 mu, sigma = 100, 15 |
|
2239 x = mu + sigma*randn(10000) |
|
2240 # the histogram of the data |
|
2241 n, bins, patches = hist(x, 100, normed=1) |
|
2242 # add a 'best fit' line |
|
2243 y = normpdf( bins, mu, sigma) |
|
2244 l = plot(bins, y, 'r--', linewidth=2) |
|
2245 xlim(40, 160) |
|
2246 xlabel('Smarts') |
|
2247 ylabel('P') |
|
2248 title(r'$\rm{IQ:}\/ \mu=100,\/ \sigma=15$') |
|
2249 \end{lstlisting} |
|
2250 \end{block} |
|
2251 \end{columns} |
|
2252 \end{frame} |
|
2253 |
|
2254 \begin{frame}[fragile] \frametitle{Bar charts} |
|
2255 \begin{columns} |
|
2256 \column{0.5\textwidth} |
|
2257 \hspace*{-0.5in} |
|
2258 \includegraphics[height=2in, interpolate=true]{data/barchart} |
|
2259 \column{0.45\textwidth} |
|
2260 \begin{block}{Example code} |
|
2261 \tiny |
|
2262 \begin{lstlisting} |
|
2263 N = 5 |
|
2264 menMeans = (20, 35, 30, 35, 27) |
|
2265 menStd = ( 2, 3, 4, 1, 2) |
|
2266 # the x locations for the groups |
|
2267 ind = arange(N) |
|
2268 # the width of the bars |
|
2269 width = 0.35 |
|
2270 p1 = bar(ind, menMeans, width, |
|
2271 color='r', yerr=menStd) |
|
2272 womenMeans = (25, 32, 34, 20, 25) |
|
2273 womenStd = ( 3, 5, 2, 3, 3) |
|
2274 p2 = bar(ind+width, womenMeans, width, |
|
2275 color='y', yerr=womenStd) |
|
2276 ylabel('Scores') |
|
2277 title('Scores by group and gender') |
|
2278 xticks(ind+width, |
|
2279 ('G1', 'G2', 'G3', 'G4', 'G5')) |
|
2280 xlim(-width,len(ind)) |
|
2281 yticks(arange(0,41,10)) |
|
2282 legend((p1[0], p2[0]), |
|
2283 ('Men', 'Women'), shadow=True) |
|
2284 \end{lstlisting} |
|
2285 \end{block} |
|
2286 \end{columns} |
|
2287 \end{frame} |
|
2288 |
|
2289 \begin{frame}[fragile] \frametitle{Pie charts} |
|
2290 \begin{columns} |
|
2291 \column{0.5\textwidth} |
|
2292 \hspace*{-0.4in} |
|
2293 \includegraphics[height=2.0in, interpolate=true]{data/piechart} |
|
2294 \column{0.45\textwidth} |
|
2295 \begin{block}{Example code} |
|
2296 \tiny |
|
2297 \begin{lstlisting} |
|
2298 # make a square figure and axes |
|
2299 figure(1, figsize=(8,8)) |
|
2300 ax = axes([0.1, 0.1, 0.8, 0.8]) |
|
2301 labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' |
|
2302 fracs = [15,30,45, 10] |
|
2303 explode=(0, 0.05, 0, 0) |
|
2304 pie(fracs, explode=explode, labels=labels, |
|
2305 autopct='%1.1f%%', shadow=True) |
|
2306 title('Raining Hogs and Dogs', |
|
2307 bbox={'facecolor':'0.8', 'pad':5}) |
|
2308 \end{lstlisting} |
|
2309 \end{block} |
|
2310 \end{columns} |
|
2311 \end{frame} |
|
2312 |
|
2313 \begin{frame}[fragile] \frametitle{Scatter plots} |
|
2314 \begin{columns} |
|
2315 \column{0.5\textwidth} |
|
2316 \hspace*{-0.4in} |
|
2317 \includegraphics[height=2in, interpolate=true]{data/scatter} |
|
2318 \column{0.45\textwidth} |
|
2319 \begin{block}{Example code} |
|
2320 \tiny |
|
2321 \begin{lstlisting} |
|
2322 N = 30 |
|
2323 x = 0.9*rand(N) |
|
2324 y = 0.9*rand(N) |
|
2325 # 0 to 10 point radiuses |
|
2326 area = pi*(10 * rand(N))**2 |
|
2327 volume = 400 + rand(N)*450 |
|
2328 scatter(x,y,s=area, marker='o', c=volume, |
|
2329 alpha=0.75) |
|
2330 xlabel(r'$\Delta_i$', size='x-large') |
|
2331 ylabel(r'$\Delta_{i+1}$', size='x-large') |
|
2332 title(r'Volume and percent change') |
|
2333 grid(True) |
|
2334 colorbar() |
|
2335 savefig('scatter') |
|
2336 \end{lstlisting} |
|
2337 \end{block} |
|
2338 \end{columns} |
|
2339 \end{frame} |
|
2340 |
|
2341 \begin{frame}[fragile] \frametitle{Polar} |
|
2342 \begin{columns} |
|
2343 \column{0.5\textwidth} |
|
2344 \hspace*{-0.5in} |
|
2345 \includegraphics[height=2in, interpolate=true]{data/polar} |
|
2346 \column{0.45\textwidth} |
|
2347 \begin{block}{Example code} |
|
2348 \tiny |
|
2349 \begin{lstlisting} |
|
2350 figure(figsize=(8,8)) |
|
2351 ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, |
|
2352 axisbg='#d5de9c') |
|
2353 r = arange(0,1,0.001) |
|
2354 theta = 2*2*pi*r |
|
2355 polar(theta, r, color='#ee8d18', lw=3) |
|
2356 # the radius of the grid labels |
|
2357 setp(ax.thetagridlabels, y=1.075) |
|
2358 title(r"$\theta=4\pi r", fontsize=20) |
|
2359 \end{lstlisting} |
|
2360 \end{block} |
|
2361 \end{columns} |
|
2362 \end{frame} |
|
2363 |
|
2364 \begin{frame}[fragile] \frametitle{Contours} |
|
2365 \begin{columns} |
|
2366 \column{0.45\textwidth} |
|
2367 \hspace*{-0.5in} |
|
2368 \includegraphics[height=2in, interpolate=true]{data/contour} |
|
2369 \column{0.525\textwidth} |
|
2370 \begin{block}{Example code} |
|
2371 \tiny |
|
2372 \begin{lstlisting} |
|
2373 x = arange(-3.0, 3.0, 0.025) |
|
2374 y = arange(-2.0, 2.0, 0.025) |
|
2375 X, Y = meshgrid(x, y) |
|
2376 Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) |
|
2377 Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) |
|
2378 # difference of Gaussians |
|
2379 Z = 10.0 * (Z2 - Z1) |
|
2380 im = imshow(Z, interpolation='bilinear', |
|
2381 origin='lower', |
|
2382 cmap=cm.gray, extent=(-3,3,-2,2)) |
|
2383 levels = arange(-1.2, 1.6, 0.2) |
|
2384 # label every second level |
|
2385 clabel(CS, levels[1::2], inline=1, |
|
2386 fmt='%1.1f', fontsize=14) |
|
2387 CS = contour(Z, levels, |
|
2388 origin='lower', |
|
2389 linewidths=2, |
|
2390 extent=(-3,3,-2,2)) |
|
2391 # make a colorbar for the contour lines |
|
2392 CB = colorbar(CS, shrink=0.8, extend='both') |
|
2393 title('Lines with colorbar') |
|
2394 hot(); flag() |
|
2395 \end{lstlisting} |
|
2396 \end{block} |
|
2397 \end{columns} |
|
2398 \end{frame} |
|
2399 |
|
2400 \begin{frame}[fragile] \frametitle{Velocity vectors} |
|
2401 \begin{columns} |
|
2402 \column{0.5\textwidth} |
|
2403 \hspace*{-0.5in} |
|
2404 \includegraphics[height=2in, interpolate=true]{data/quiver} |
|
2405 \column{0.45\textwidth} |
|
2406 \begin{block}{Example code} |
|
2407 \tiny |
|
2408 \begin{lstlisting} |
|
2409 X,Y = meshgrid(arange(0,2*pi,.2), |
|
2410 arange(0,2*pi,.2) ) |
|
2411 U = cos(X) |
|
2412 V = sin(Y) |
|
2413 Q = quiver(X[::3, ::3], Y[::3, ::3], |
|
2414 U[::3, ::3], V[::3, ::3], |
|
2415 color='r', units='x', |
|
2416 linewidths=(2,), |
|
2417 edgecolors=('k'), |
|
2418 headaxislength=5 ) |
|
2419 qk = quiverkey(Q, 0.5, 0.03, 1, '1 m/s', |
|
2420 fontproperties= |
|
2421 {'weight': 'bold'}) |
|
2422 axis([-1, 7, -1, 7]) |
|
2423 title('triangular head; scale '\ |
|
2424 'with x view; black edges') |
|
2425 \end{lstlisting} |
|
2426 \end{block} |
|
2427 \end{columns} |
|
2428 \end{frame} |
|
2429 |
|
2430 \begin{frame}[fragile] \frametitle{Maps} |
|
2431 \includegraphics[height=2.5in, interpolate=true]{data/plotmap} |
|
2432 \begin{center} |
|
2433 \tiny |
|
2434 For details see \url{http://matplotlib.sourceforge.net/screenshots/plotmap.py} |
|
2435 \end{center} |
|
2436 \end{frame} |
|
2437 |
|
2438 |
|
2439 \subsection{SciPy} |
|
2440 |
|
2441 \begin{frame} |
|
2442 \frametitle{Using \texttt{SciPy}} |
|
2443 \begin{itemize} |
|
2444 \item SciPy is Open Source software for mathematics, science, and |
|
2445 engineering |
|
2446 \item \typ{import scipy} |
|
2447 \item Built on NumPy |
|
2448 \item Provides modules for statistics, optimization, integration, |
|
2449 linear algebra, Fourier transforms, signal and image processing, |
|
2450 genetic algorithms, ODE solvers, special functions, and more |
|
2451 \item Used widely by scientists world over |
|
2452 \item Details are beyond the scope of this tutorial |
|
2453 \end{itemize} |
|
2454 \end{frame} |
|
2455 |
|
2456 \section{Standard library} |
|
2457 |
|
2458 \subsection{Quick Tour} |
|
2459 |
|
2460 \begin{frame} |
|
2461 \frametitle{Standard library} |
|
2462 \begin{itemize} |
|
2463 \item Very powerful |
|
2464 \item ``Batteries included'' |
|
2465 \item Example standard modules taken from the tutorial |
|
2466 \begin{itemize} |
|
2467 \item Operating system interface: \typ{os} |
|
2468 \item System, Command line arguments: \typ{sys} |
|
2469 \item Regular expressions: \typ{re} |
|
2470 \item Math: \typ{math}, \typ{random} |
|
2471 \item Internet access: \typ{urllib2}, \typ{smtplib} |
|
2472 \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, |
|
2473 \typ{zipfile}, and \typ{tarfile} |
|
2474 \item Unit testing: \typ{doctest} and \typ{unittest} |
|
2475 \item And a whole lot more! |
|
2476 \end{itemize} |
|
2477 \item Check out the Python Library reference: |
|
2478 \url{http://docs.python.org/lib/lib.html} |
|
2479 \end{itemize} |
|
2480 \end{frame} |
|
2481 |
|
2482 \begin{frame}[fragile] |
|
2483 \frametitle{Stdlib: examples} |
|
2484 \begin{lstlisting} |
|
2485 >>> import os |
|
2486 >>> os.system('date') |
|
2487 Fri Jun 10 22:13:09 IST 2005 |
|
2488 0 |
|
2489 >>> os.getcwd() |
|
2490 '/home/prabhu' |
|
2491 >>> os.chdir('/tmp') |
|
2492 >>> import os |
|
2493 >>> dir(os) |
|
2494 <returns a list of all module functions> |
|
2495 >>> help(os) |
|
2496 <extensive manual page from module's docstrings> |
|
2497 \end{lstlisting} |
|
2498 \end{frame} |
|
2499 |
|
2500 \begin{frame}[fragile] |
|
2501 \frametitle{Stdlib: examples} |
|
2502 \begin{lstlisting} |
|
2503 >>> import sys |
|
2504 >>> # Print the list of command line args to Python |
|
2505 ... print sys.argv |
|
2506 [''] |
|
2507 >>> import re # Regular expressions |
|
2508 >>> re.findall(r'\bf[a-z]*', |
|
2509 ... 'which foot or hand fell fastest') |
|
2510 ['foot', 'fell', 'fastest'] |
|
2511 >>> re.sub(r'(\b[a-z]+) \1', r'\1', |
|
2512 ... 'cat in the the hat') |
|
2513 'cat in the hat' |
|
2514 \end{lstlisting} |
|
2515 \end{frame} |
|
2516 |
|
2517 \begin{frame}[fragile] |
|
2518 \frametitle{Stdlib: examples} |
|
2519 \begin{lstlisting} |
|
2520 >>> import math |
|
2521 >>> math.cos(math.pi / 4.0) |
|
2522 0.70710678118654757 |
|
2523 >>> math.log(1024, 2) |
|
2524 10.0 |
|
2525 >>> import random |
|
2526 >>> random.choice(['apple', 'pear', 'banana']) |
|
2527 'pear' |
|
2528 \end{lstlisting} |
|
2529 \end{frame} |
|
2530 |
|
2531 \begin{frame}[fragile] |
|
2532 \frametitle{Stdlib: examples} |
|
2533 \begin{lstlisting} |
|
2534 >>> import urllib2 |
|
2535 >>> f = urllib2.urlopen('http://www.python.org/') |
|
2536 >>> print f.read(100) |
|
2537 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
|
2538 <?xml-stylesheet href="./css/ht2html |
|
2539 \end{lstlisting} |
|
2540 \end{frame} |
|
2541 |
|
2542 \begin{frame}[fragile] |
|
2543 \frametitle{Stdlib: examples} |
|
2544 \begin{lstlisting} |
|
2545 >>> import zlib |
|
2546 >>> s = 'witch which has which witches wrist watch' |
|
2547 >>> len(s) |
|
2548 41 |
|
2549 >>> t = zlib.compress(s) |
|
2550 >>> len(t) |
|
2551 37 |
|
2552 >>> zlib.decompress(t) |
|
2553 'witch which has which witches wrist watch' |
|
2554 >>> zlib.crc32(t) |
|
2555 -1438085031 |
|
2556 \end{lstlisting} |
|
2557 \end{frame} |
|
2558 |
|
2559 \begin{frame} |
|
2560 \frametitle{Summary} |
|
2561 \begin{itemize} |
|
2562 \item Introduced Python |
|
2563 \item Basic syntax |
|
2564 \item Basic types and data structures |
|
2565 \item Control flow |
|
2566 \item Functions |
|
2567 \item Modules |
|
2568 \item Exceptions |
|
2569 \item Classes |
|
2570 \item Standard library |
|
2571 \end{itemize} |
|
2572 \end{frame} |
|
2573 |
|
2574 \end{document} |
|
2575 |
|
2576 \subsection{Basic data structures} |
|
2577 \begin{frame}{Lists} |
|
2578 \begin{itemize} |
|
2579 \item \texttt{species = [ 'humans', 'orcs', 'elves', 'dwarves' ]} |
|
2580 \item \texttt{ ids = [ 107, 109, 124, 141, 142, 144 ]} |
|
2581 \item \texttt{ oneliners = [ 'I will be back', 'Do or do not! No try!!', 42 ] } |
|
2582 \end{itemize} |
|
2583 |
|
2584 \begin{block}{List operations} |
|
2585 ids + [ 100, 102 ]\\ |
|
2586 species.append( 'unicorns')\\ |
|
2587 print oneliners[ 1 ]\\ |
|
2588 look up \alert{docs.python.org/tutorial/datastructures.html} |
|
2589 \end{block} |
|
2590 \end{frame} |
|
2591 \end{document} |
|
2592 \section{Python Tutorial} |
|
2593 \subsection{Preliminaries} |
|
2594 \begin{frame} |
|
2595 \frametitle{Using the interpreter} |
|
2596 \begin{itemize} |
|
2597 \item Starting up: \typ{python} or \typ{ipython} |
|
2598 \item Quitting: \typ{Control-D} or \typ{Control-Z} (on Win32) |
|
2599 \item Can use it like a calculator |
|
2600 \item Can execute one-liners via the \typ{-c} option: |
|
2601 \typ{python -c "print 'hello world'"} |
|
2602 \item Other options via \typ{python -h} |
|
2603 \end{itemize} |
|
2604 \end{frame} |
|
2605 |
|
2606 \begin{frame} |
|
2607 \frametitle{IPython} |
|
2608 \begin{itemize} |
|
2609 \item Recommended interpreter, IPython: |
|
2610 \url{http://ipython.scipy.org} |
|
2611 \item Better than the default Python shell |
|
2612 \item Supports tab completion by default |
|
2613 \item Easier object introspection |
|
2614 \item Shell access! |
|
2615 \item Command system to allow extending its own behavior |
|
2616 \item Supports history (across sessions) and logging |
|
2617 \item Can be embedded in your own Python code |
|
2618 \item Support for macros |
|
2619 \item A flexible framework for your own custom interpreter |
|
2620 \item Other miscellaneous conveniences |
|
2621 \item We'll get back to this later |
|
2622 \end{itemize} |
|
2623 \end{frame} |
|
2624 |
|
2625 \begin{frame}[fragile] |
|
2626 \frametitle{Basic IPython features} |
|
2627 \begin{itemize} |
|
2628 \item Startup: \verb+ipython [options] files+ |
|
2629 \begin{itemize} |
|
2630 \item \verb+ipython [-wthread|-gthread|-qthread]+: |
|
2631 Threading modes to support wxPython, pyGTK and Qt |
|
2632 \item \verb+ipython -pylab+: Support for matplotlib |
|
2633 \end{itemize} |
|
2634 \item TAB completion: |
|
2635 \begin{itemize} |
|
2636 \item Type \verb+object_name.<TAB>+ to see list of options |
|
2637 \item Also completes on file and directory names |
|
2638 \end{itemize} |
|
2639 \item \verb+object?+ shows docstring/help for any Python object |
|
2640 \item \verb+object??+ presents more docs (and source if possible) |
|
2641 \item Debugging with \verb+%pdb+ magic: pops up pdb on errors |
|
2642 \item Access history (saved over earlier sessions also) |
|
2643 \begin{itemize} |
|
2644 \item Use \texttt{<UpArrow>}: move up history |
|
2645 \item Use \texttt{<Ctrl-r> string}: search history backwards |
|
2646 \item Use \texttt{Esc >}: get back to end of history |
|
2647 \end{itemize} |
|
2648 \item \verb+%run [options] file[.py]+ lets you run Python code |
|
2649 \end{itemize} |
|
2650 \end{frame} |
|
2651 % LocalWords: BDFL Guido Rossum PSF Nokia OO Zope CMS RedHat SciPy MayaVi spam |
|
2652 % LocalWords: IPython ipython stdin TypeError dict int elif PYTHONPATH IOError |
|
2653 % LocalWords: namespace Namespaces SyntaxError ZeroDivisionError NameError str |
|
2654 % LocalWords: ValueError subclassed def |
|
2655 |
|
2656 |
|
2657 \item Types are of two kinds: \alert{mutable} and \alert{immutable} |
|
2658 \item Immutable types: numbers, strings, \typ{None} and tuples |
|
2659 \item Immutables cannot be changed ``in-place'' |
|
2660 \item Mutable types: lists, dictionaries, instances, etc. |
|
2661 \item Mutable objects can be ``changed'' |
|
2662 \end{itemize} |
|
2663 |
|
2664 |
|
2665 \begin{frame} |
|
2666 \frametitle{Important!} |
|
2667 \begin{itemize} |
|
2668 \item Assignment to an object is by reference |
|
2669 \item Essentially, \alert{names are bound to objects} |
|
2670 \end{itemize} |
|
2671 \end{frame} |
|
2672 |
|
2673 |
|
2674 \end{document} |
|
2675 \begin{frame}[fragile] |
|
2676 \frametitle{Dictionaries} |
|
2677 \begin{itemize} |
|
2678 \item Associative arrays/mappings |
|
2679 \item Indexed by ``keys'' (keys must be immutable) |
|
2680 \item \typ{dict[key] = value} |
|
2681 \item \typ{keys()} returns all keys of the dict |
|
2682 \item \typ{values()} returns the values of the dict |
|
2683 \item \verb+has_key(key)+ returns if \typ{key} is in the dict |
|
2684 \end{itemize} |
|
2685 \end{frame} |
|
2686 |
|
2687 \begin{frame}[fragile] |
|
2688 \frametitle{Dictionaries: example} |
|
2689 \begin{lstlisting} |
|
2690 >>> tel = {'jack': 4098, 'sape': 4139} |
|
2691 >>> tel['guido'] = 4127 |
|
2692 >>> tel |
|
2693 {'sape': 4139, 'guido': 4127, 'jack': 4098} |
|
2694 >>> tel['jack'] |
|
2695 4098 |
|
2696 >>> del tel['sape'] |
|
2697 >>> tel['irv'] = 4127 |
|
2698 >>> tel |
|
2699 {'guido': 4127, 'irv': 4127, 'jack': 4098} |
|
2700 >>> tel.keys() |
|
2701 ['guido', 'irv', 'jack'] |
|
2702 >>> tel.has_key('guido') |
|
2703 True |
|
2704 \end{lstlisting} |
|
2705 \end{frame} |
|
2706 |
|
2707 \subsection{Control flow, functions} |
|
2708 |
|
2709 |
|
2710 |
|
2711 \begin{frame}[fragile] |
|
2712 \frametitle{\typ{If} example} |
|
2713 \begin{lstlisting} |
|
2714 >>> a = ['cat', 'window', 'defenestrate'] |
|
2715 >>> if 'cat' in a: |
|
2716 ... print "meaw" |
|
2717 ... |
|
2718 meaw |
|
2719 >>> pets = {'cat': 1, 'dog':2, 'croc': 10} |
|
2720 >>> if 'croc' in pets: |
|
2721 ... print pets['croc'] |
|
2722 ... |
|
2723 10 |
|
2724 \end{lstlisting} |
|
2725 \end{frame} |
|
2726 |
|
2727 \begin{frame}[fragile] |
|
2728 \frametitle{\typ{for} example} |
|
2729 \begin{lstlisting} |
|
2730 >>> a = ['cat', 'window', 'defenestrate'] |
|
2731 >>> for x in a: |
|
2732 ... print x, len(x) |
|
2733 ... |
|
2734 cat 3 |
|
2735 window 6 |
|
2736 defenestrate 12 |
|
2737 >>> knights = {'gallahad': 'the pure', |
|
2738 ... 'robin': 'the brave'} |
|
2739 >>> for k, v in knights.iteritems(): |
|
2740 ... print k, v |
|
2741 ... |
|
2742 gallahad the pure |
|
2743 robin the brave |
|
2744 \end{lstlisting} |
|
2745 \end{frame} |