The UOB Python Lectures: Part 1 - Introduction to Python Hesham al-ammal University of Bahrain 18/3/2013 Twitter: @heshaaam Blog and slides: heshaaam.wordpress.com 1 1
Feel like flying? Ref: xkcd.com 2 2
History: Name Python is named based on the British comedy series Monty Python s Flying Circus Not the constricting snake 3 3
History: BDFL Guido van Rossom (Google 2012) Principal author and Benevolent dictator (BDFL), central role in deciding direction of Python Created in 1990 at CWI, Netherlands 4 Python s Logo 1990-2005 4
Interpreted vs Compiled Programming Languages Compiled Interpreted C C++ Java Python Perl Lisp Interactive vs. Batch 5 5
Interactive Python $ python Python 2.7 (#1, Feb 28 2010, 00:02:06) Type "help", "copyright", "credits" or "license" for more information. >>> >>> the_world_is_flat = 1 >>> if the_world_is_flat:... print "Be careful not to fall off!"... Be careful not to fall off! 6 6
Batch mode Edit #! /usr/bin/env python the_world_is_flat=1 if the_world_is_flat: print "Be careful not to fall off" Save file.py Debug/Run Python file.py 7 7
Python Versions We will be using version 2.7 Versions 2.2-2.7 backward compatible Version 3 is totally different fork of Python and thus not outward compatible Version 2 will continue for a while 8 8
Tutorial Outline Data Types: Numbers, Strings, Lists Control Flow: If, For, break, continue,... Data structures Modules Input and output Classes The Standard Library Ref: http://docs.python.org/2/tutorial/ 9 9
Integers Integer division: floor Power No limit to integer arithmetic except mempr (arbitrary long integers) >>> 7/3 2 >>> 2**521-1 68647976601306097149 81900799081393217269 4353001433054093944 63459185543183397656 05212255964066145455 49772963113914808580 37121987999716643812 574028291115057151L http://en.wikipedia.org/wiki/mersenne_prime 10 10
Floating Point / Complex Full support for floating point numbers and mixed arithmetic Complex numbers are also supported 11 >>> 3 * 3.75 / 1.5 7.5 >>> 7.0 / 2 3.5 >>> 1j * 1J (-1+0j) >>> 1j * complex(0,1) (-1+0j) >>> 3+1j*3 (3+3j) >>> (3+1j)*3 (9+3j) >>> (1+2j)/(1+1j) (1.5+0.5j) 11
Strings Strings can be enclosed in single quotes or double quotes Notice special characters Multiple line strings are possible >>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> "\"Yes,\" he said." '"Yes," he said.' >>> '"Isn\'t," she said.' '"Isn\'t," she said.' 12 12
Strings (cont.) Strings can be concatinated Strings can be subscripted >>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '<HelpAHelpAHelpAHelpAHelpA>' >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' 13 13
Slicing strings >>> word[:2] # The first two characters 'He' >>> word[2:] # Everything except the first two characters 'lpa' 14 14
Assigning to strings is an error >>> word[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object does not support item assignment >>> word[:1] = 'Splat' Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: object does not support slice assignment However, this is OK: creating new strings >>> 'x' + word[1:] 'xelpa' >>> 'Splat' + word[4] 'SplatA' 15 15
Negative string slicing Indices may be negative numbers, to start counting from the right. H e l p A 0 1 2 3 4 5-5 -4-3 -2-1 Imagine numbers between characters >>> word[-1] # The last character 'A' >>> word[-2] # The last-but-one character 'p' >>> word[-2:] # The last two characters 'pa' >>> word[:-2] # Everything except the last two characters 'Hel' 16 16
Lists Many compound data types in Python Most verstaile is a list Comma-separated between square brackets All slice operations return new lists >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234] >>> a[0] 'spam' >>> a[3] 1234 >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] >>> a[:2] + ['bacon', 2*2] ['spam', 'eggs', 'bacon', 4] >>> 3*a[:3] + ['Boo!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!'] >>> a[:] ['spam', 'eggs', 100, 1234] 17 17
More about lists >>> # Replace some items:... a[0:2] = [1, 12] >>> a [1, 12, 123, 1234] >>> # Remove some: like strings... a[0:2] = [] >>> a [123, 1234] >>> # Insert some:... a[1:1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> # Insert (a copy of) itself at the beginning >>> a[:0] = a >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] >>> # Clear the list: replace all items with an empty list >>> a[:] = [] >>> a [] Lists are not immutable 18 18
Even more about lists You can use len() Lists can be nested 19 >>> a = ['a', 'b', 'c', 'd'] >>> len(a) 4 >>> q = [2, 3] >>> p = [1, q, 4] >>> len(p) 3 >>> p[1] [2, 3] >>> p[1][0] 2 >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra'] 19
Our first useful program Interactive mode Indentation defines block >>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b... 1 1 2 3 5 8 Multiple assignments In other languages: temp = a a = b b = temp In Python: b, a = a, b 20 20
Our first useful program Batch mode #! /usr/bin/env python # Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while b < 10: print b a, b = b, a+b 21 21
Interlude And now for something completely different 22 22
The Zen of Python 1 Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. 23 UOB Students 23
The Zen of Python 2 In the face of ambiguity, refuse the temptation to guess. There should be one and preferably only one obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea let's do more of those! 24 24
Coding style: Readability Counts Programs must be written for people to read, and only incidentally for machines to execute. Abelson & Sussman, Structure and Interpretation of Computer Programs 25 25
Back to our regularly scheduled programming 26 26
More control statements: if >>> x = int(raw_input("please enter an integer: ")) Please enter an integer: 42 >>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'... More 27 27
for loops Unlike for loops in C++, it iterates on elements of a sequence like a list or a string. For exmaple (no pun intended): >>> # Measure some strings:... words = ['cat', 'window', 'defenestrate'] >>> for w in words:... print w, len(w)... cat 3 window 6 defenestrate 12 28 28
for loops and slicing If you need to edit the sequence make a copy of the list using slicing >>> for w in words[:]: # Loop over a slice copy of list.... if len(w) > 6:... words.insert(0, w)... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] 29 29
The range() function For iterating over a range of numbers >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)):... print i, a[i]... 0 Mary 1 had 2 a 3 little 4 lamb 30 30
Enough with control structures You just should know that there are more control structures when you need them: break continue pass 31 31
Defining Functions >>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n.""" Documentation... a, b = 0, 1 string literal... while a < n:... print a,... a, b = b, a+b... >>> # Now call the function we just defined:... fib(2000) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 32 32
Return values >>> def fib2(n): # return Fibonacci series up to n... """Return a list containing the Fibonacci series up to n."""... result = []... a, b = 0, 1... while a < n:... result.append(a)... a, b = b, a+b... return result... >>> f100 = fib2(100) # call it >>> f100 # write the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] Method append belongs to the object result Functions without return just return None 33 33
More on functions: Default Arguments def ask_ok(prompt, retries=4, complaint='yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusing user') print complaint Notice the in keyword Options only the mandatory argument: ask_ok('do you really want to quit?') one of the optional arguments: ask_ok('ok to overwrite the file?', 2) all arguments: ask_ok('ok to overwrite the file?', 2, 'Come on, only yes or no!') 34 34
Things I will not mention in functions Arbitrary argument lists Lambda forms Documentation strings 35 35
Coding Style Use 4-space indentation, and no tabs. Wrap lines so that they don t exceed 79 characters. Use blank lines to separate functions and classes, and larger blocks of code inside functions. When possible, put comments on a line of their own. Use docstrings. Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4). 36 36
Data Structures 37 37
Lists and their methods 1 list.append(x) Add an item to the end of the list; equivalent to a[len(a):] = [x]. list.extend(l) Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. list.insert(i, x) Insert an item at a given position. 38 38
Lists and their methods 2 list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item. list.pop([i]) Remove the item at the given position in the list, and return it. list.index(x) Return the index in the list of the first item whose value is x. 39 39
Lists and their methods 3 list.count(x) Return the number of times x appears in the list. list.sort() Sort the items of the list, in place. list.reverse() Reverse the elements of the list, in place. 40 40
Lists as stacks >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] 41 41
Lists as queues use collections.deque which was designed to have fast appends and pops from both ends >>> from collections import deque >>> queue = deque(["eric", "John", "Michael"]) >>> queue.append("terry") # Terry arrives >>> queue.append("graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['michael', 'Terry', 'Graham']) 42 42
Functional Programming Tools 43 43
filter(function,sequence) >>> def f(x): return x % 2!= 0 and x % 3!= 0... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] 44 44
map(function, sequence) >>> def cube(x): return x*x*x... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 45 45
reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. >>> def add(x,y): return x+y... >>> reduce(add, range(1, 11)) 55 46 46
List comprehension You can do this >>> squares = [] >>> for x in range(10):... squares.append(x**2)... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] or get the same result with this squares = [x**2 for x in range(10)] 47 47
More list comprehension >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x!= y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] is equivalent to >>> combs = [] >>> for x in [1,2,3]:... for y in [3,1,4]:... if x!= y:... combs.append((x, y))... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 48 48
Dictionaries >>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() ['guido', 'irv', 'jack'] >>> 'guido' in tel True Associative memory 49 49
What have we learned? Hopefully some basic syntax Python Phylosophy of Python All of the tools that you need, elegantly 50 50
What we haven t learnt The Python Standard Library Other useful libraries 51 51
Why Python? Python as glue: hundreds of libraries in C++, Fortran, etc. Almost no need for a second language. Quick prototyping, scripting, etc. Strong support for scientific computing. Support for web dev, mobile dev 52 52
Why Python? Open source, join the revolution Runs on all platforms Cython for high performance ipython (replace Mathematica) MatPlotLib (replace Matlab) 53 53
More Python? python.org The tutorial http://docs.python.org/2/tutorial/ Many video lectures on many topics http://pyvideo.org/ 54 54
ipython Powerful interactive shells (terminal and Qt-based). A browser-based notebook with support for code, text, mathematical expressions, inline plots and other rich media. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into your own projects. Easy to use, high performance tools for parallel computing. 55 55
56 56
Thank you for listening 57 57