Dictionary added
[linuxnijmegen-python.git] / p.tex
1 %&p
2 \begin{document}
3 \frame{\titlepage}
4
5 \section{Introduction}
6 \begin{frame}
7 \frametitle{What is Python}
8 \includegraphics[width=\linewidth]{2.png}
9 \end{frame}
10
11 \begin{frame}
12 \frametitle{What is Python}
13 \begin{itemize}
14 \item Interpreted
15 \item Duck-typing
16 \item High-level
17 \item Multi-paradigm
18 \item \ldots
19 \end{itemize}
20 \end{frame}
21
22 \begin{frame}[fragile]
23 \frametitle{How to start}
24 \framesubtitle{Interpreter}
25 \begin{minted}[breaklines=true]{pycon}
26 Python 3.5.1 (default, Dec 7 2015, 12:58:09)
27 [GCC 5.2.0] on linux
28 Type "help", "copyright", "credits" or "license" for more
29 information.
30 >>> print('Hello world!')
31 Hello world!
32 >>> i = 1972
33 >>> print(str(i/46) + ' hoi')
34 42.869565217391305 hoi
35 \end{minted}
36 \end{frame}
37
38 \begin{frame}[fragile]
39 \frametitle{How to start}
40 \framesubtitle{Source files}
41 \begin{minted}{python}
42 #!/usr/bin/env python3
43 # -*- coding: utf-8 -*-
44
45 print('hello world')
46 i = 1972
47 print(str(i/46) + ' hoi')
48 \end{minted}
49 \end{frame}
50
51 \section{Basics}
52 \begin{frame}[fragile]
53 \frametitle{Built-in types}
54 \begin{tabular}{ll}
55 \mintinline{python}{bool} & \mintinline{python}{True, False}\\
56 \mintinline{python}{int} & \mintinline{python}{1, -4, 999}\\
57 \mintinline{python}{complex} & \mintinline{python}{4j+1, j}\\
58 \mintinline{python}{float} & \mintinline{python}
59 {1.0, 4.5, 5e9, float('NaN'), float('inf')}\\
60 \mintinline{python}{str} & \mintinline{python}
61 {'hi', "hi", '"', "'", """hi"""}\\
62 \mintinline{python}{list} & \mintinline{python}
63 {[], ..., [1, 2, 3], ['a', 42], [[], [1]]}\\
64 \mintinline{python}{tuple} & \mintinline{python}
65 {(1,), (1,2), (1, 'a', True), ((4, 3), 4)}\\
66 \mintinline{python}{dict} & \mintinline{python}
67 {{1: 'a', 2: 'b'}, {"hi": 42, "test": {}}, {}}\\
68 \mintinline{python}{set} & \mintinline{python}
69 {{1, 2}, {"hi", "a"}, set()}\\
70 Others & \mintinline{python}
71 {range, bytes, bytearray, memoryview, frozenset}\\
72 Special & \mintinline{python}
73 {type, None, ..., NotImplemented}\\
74 \end{tabular}
75 \end{frame}
76
77 \begin{frame}[fragile]
78 \frametitle{Basictypes: Operators}
79 \begin{block}{operators}
80 \begin{itemize}
81 \item Numbers: \mintinline{python}{+ - / * // % @ **}
82 \item Comparison: \mintinline{python}{< <= > >= == !=}
83 \item Boolean: \mintinline{python}{and or not}
84 \item Bitwise: \mintinline{python}{& | ^ ~ << >>}
85 \item List/Dictionary: \mintinline{python}{[i] [i:j] in}
86 \item In place: \mintinline{python}{*= += ...}
87 \item Special: \mintinline{python}{is}
88 \end{itemize}
89 \end{block}
90 \end{frame}
91
92 \section{Control flow}
93 \subsection{If, then, else}
94 \begin{frame}[fragile]
95 \frametitle{Conditional execution}
96 \framesubtitle{\texttt{fizzbuzz.py}}
97 \begin{minted}{python}
98 #!/usr/bin/env python3
99
100 i = int(input('Enter a number: '))
101 if i % 3 == 0 and i % 5 == 0:
102 print('fizzbuzz')
103 elif i % 3 == 0:
104 print('buzz')
105 elif i % 5 == 0:
106 print('fizz')
107 else:
108 print(i)
109 \end{minted}
110 \end{frame}
111
112 \begin{frame}[fragile]
113 \frametitle{Conditional execution 2}
114 \framesubtitle{\texttt{fizzbuzz.py}}
115 \begin{minted}{shell-session}
116 frobnicator@frobmachine~$ python fizzbuzz.py
117 Enter a number: 42
118 buzz
119 frobnicator@frobmachine~$ python fizzbuzz.py
120 Enter a number: 15
121 fizzbuzz
122 frobnicator@frobmachine~$ python fizzbuzz.py
123 Enter a number: 43
124 43
125 frobnicator@frobmachine~$ python fizzbuzz.py
126 Enter a number: 9
127 fizz
128 \end{minted}
129 \end{frame}
130
131 \subsection{While, for}
132 \begin{frame}[fragile]
133 \frametitle{Looping}
134 \begin{minted}{python}
135 ls = ["hello", "world", "!"]
136
137 # Pythonic for loop
138 for item in ls:
139 print(ls)
140
141 # C style for loop
142 for i in range(0, len(ls)):
143 print(ls[i])
144
145 # While loop
146 i = 10
147 while i >= 0:
148 print(i);
149 print('fire!')
150 \end{minted}
151 \end{frame}
152
153 \begin{frame}[fragile]
154 \frametitle{Looping: Escape rope}
155 \begin{minted}{python}
156 # 100.000st prime, 100.001st prime, and a pseudoprime
157 numbers = [1299709, 1299721, 1299709*1299721]
158 for n in numbers:
159 for x in range(2, n):
160 if n % x == 0:
161 print(n, 'equals', x, '*', n//x)
162 break
163 else:
164 print(n, 'is a prime number')
165
166 # 1299709 is a prime number
167 # 1299721 is a prime number
168 # 1689259081189 equals 1299709 * 1299721
169
170 # pass, continue
171 \end{minted}
172 \end{frame}
173
174 \subsection{Functions}
175 \begin{frame}[fragile]
176 \frametitle{Functions}
177 \begin{minted}{python}
178 def fizzbuzzrange(n, m):
179 """Print fizzbuzz for all numbers between n and m"""
180 for i in range(n, m):
181 fizzbuzz(i)
182
183 def fizzbuzz(n):
184 """Print for number i the fizzbuzz"""
185 if i % 3 == 0 and i % 5 == 0:
186 print('fizzbuzz')
187 elif i % 3 == 0:
188 print('buzz')
189 elif i % 5 == 0:
190 print('fizz')
191 else:
192 print(i)
193
194 fizzbuzzrange(0, 1000)
195 \end{minted}
196 \end{frame}
197
198 \begin{frame}[fragile]
199 \frametitle{Functions: Advanced arguments}
200 \begin{minted}{python}
201 def function(arg1, arg2, kwarg1="hi", kwarg2=42):
202 """Docstring,
203 run help(functionname) in the interpreter
204 to see this helpstring
205 """
206 pass
207
208 def function(*args):
209 for i, a in enumerate(args):
210 print("argument: ", i, ": ", a)
211
212 def function(**kwargs):
213 for k, v in kwargs:
214 print("argumentkey: ", k, "=", v)
215
216 def function(arg1, arg2, arg3=4, *args, **kwargs):
217 pass
218 \end{minted}
219 \end{frame}
220
221 \begin{frame}[fragile]
222 \frametitle{Functions: Advanced functions}
223 \begin{minted}{python}
224 def compare(this, that, comparefunc=lambda x, y: x > y):
225 return comparefunc(this, that)
226 \end{minted}
227 \begin{minted}{pycon}
228 >>> compare(42, 2)
229 True
230 >>> compare(42, 2, lambda x, y: x < y)
231 False
232 >>> def compare_len(x, y):
233 ... return len(x) > len(y)
234 ...
235 >>> print(compare_len)
236 <function compare_list at 0x7f075cd5b730>
237 >>> compare([1, 2, 3, 4], [3, 4, 5])
238 False
239 >>> compare([1, 2, 3, 4], [3, 4, 5], compare_len)
240 True
241 \end{minted}
242 \end{frame}
243
244 \section{Datastructures}
245 \begin{frame}
246 \frametitle{Lists}
247 \begin{tabular}{ll}
248 In-situ & Copy\\
249 \mintinline{python}{lst.append(x)}\\
250 \mintinline{python}{lst.extend(x)} &
251 \mintinline{python}{lst1 + lst2}\\
252 \mintinline{python}{lst.insert(i, x)}\\
253 \mintinline{python}{lst.remove(x)}\\
254 \mintinline{python}{lst.clear(x)} &
255 \mintinline{python}{lst = []}\\
256 \mintinline{python}{lst.reverse(x)} &
257 \mintinline{python}{reversed(lst)}\\
258 \mintinline{python}{lst.sort(x)} &
259 \mintinline{python}{sorted(lst)}\\
260 \ldots
261 \end{tabular}
262 \end{frame}
263
264 \begin{frame}[fragile]
265 \frametitle{Dictionary}
266 \begin{minted}{pycon}
267 >>> tel = {'jack': 4098, 'sape': 4139}
268 >>> tel['guido'] = 4127
269 >>> tel
270 {'sape': 4139, 'guido': 4127, 'jack': 4098}
271 >>> tel['jack']
272 4098
273 >>> del tel['sape']
274 >>> tel['irv'] = 4127
275 >>> tel
276 {'guido': 4127, 'irv': 4127, 'jack': 4098}
277 >>> list(tel.keys())
278 ['irv', 'guido', 'jack']
279 >>> sorted(tel.keys())
280 ['guido', 'irv', 'jack']
281 >>> 'guido' in tel
282 True
283 >>> 'jack' not in tel
284 False
285 \end{minted}
286 \end{frame}
287
288 \begin{frame}[fragile]
289 \frametitle{Sequences}
290 \begin{block}{Tuples}
291 \begin{minted}{python}
292 # Auto unpack
293 x = (42, 43)
294 x1, x2 = x
295 \end{minted}
296 \end{block}
297
298 \begin{block}{Sequence modifiers}
299 \begin{minted}{python}
300 x = {3, 2, 1}
301 lx = list(x) # items in random order
302 sx = sorted(x) # [1, 2, 3]
303 rx = reversed(sx) # [3, 2, 1]
304 rx = enumerate(rx) # [(0, 3), (1, 2), (2, 1)]
305 \end{minted}
306 \end{block}
307 \end{frame}
308
309 \section{Input/Output}
310 \begin{frame}[fragile]
311 \frametitle{Strings}
312 \begin{minted}{pycon}
313 >>> s = 'Hello, world.'
314 >>> str(s)
315 'Hello, world.'
316 >>> repr(s)
317 "'Hello, world.'"
318 >>> str(1/7)
319 '0.14285714285714285'
320 >>> x = 10 * 3.25
321 >>> y = 200 * 200
322 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
323 >>> print(s)
324 The value of x is 32.5, and y is 40000...
325 >>> hello = 'hello, world\n'
326 >>> hellos = repr(hello)
327 >>> print(hellos)
328 'hello, world\n'
329 \end{minted}
330 \end{frame}
331
332 \begin{frame}[fragile]
333 \frametitle{String formatting}
334 \begin{minted}{python}
335 'We are the {} who say "{}!"'.format('knights', 'Ni')
336 # We are the knights who say "Ni!"
337
338 '{0} {0} {1}'.format('ekke', 'ptang')
339 # ekke ekke ptang
340
341 # Number formatting and padding
342 '{0:.3f} {1:03d} "{2:<5}" "{2:,>5}"'.format(
343 1.0/3, 42, 'hi')
344 # '0.333 042 "hi " ",,,hi"
345
346 # Other Usefull string function
347 ','.join(['a', 'b', 'c'])
348 'a,b,c'.split(',')
349 \end{minted}
350 \end{frame}
351
352 \section{And much more\ldots}
353 \begin{frame}[fragile]
354 \frametitle{Error handling}
355 \begin{minted}{python}
356 try:
357 x = 5/0
358 except ZeroDivisionError as e:
359 print(e)
360
361 try:
362 do_some_stuff()
363 except:
364 rollback()
365 raise
366 else:
367 commit()
368 finally:
369 cleanup()
370 \end{minted}
371 \end{frame}
372
373 \begin{frame}[fragile]
374 \frametitle{Libraries}
375 \mintinline{python}{import modulename}\\
376 \mintinline{python}{from modulename import name1, name2}\\
377 \begin{enumerate}
378 \item System: \mintinline{python}{os, sys, glob}
379 \item Math: \mintinline{python}{math, random, statistics}
380 \item Text: \mintinline{python}{re, locale, gettext, codecs}
381 \item Internet: \mintinline{python}{irllib, email, smtplib, poplib}
382 \item Data: \mintinline{python}{sqlite, json, csv, xml.etree}
383 \item Command line:
384 \mintinline{python}{curses, urwid, readline, getopts, argparse}
385 \item GUI: \mintinline{python}{Tkinter, PySide/PyQt, PyGobject}
386 \item \ldots
387 \end{enumerate}
388 \end{frame}
389
390 \begin{frame}[fragile]
391 \frametitle{And much more\ldots}
392 \begin{itemize}
393 \item Function annotations: \mintinline{python}{def fun(n) -> str:}
394 \item Iteration through: \mintinline{python}{yield}
395 \item List comprehension:
396 \mintinline{python}{[x**2 for x in range(0, 5)]}
397 \item Functional style: \mintinline{python}{map, filter, reduce}
398 \item Classes, inheritance: \mintinline{python}{class}
399 \item Context blocks: \mintinline{python}{with}
400 \item String templating
401 \item Coding style: \url{https://www.python.org/dev/peps/pep-0008/}
402 \end{itemize}
403 \end{frame}
404 \end{document}