The UOB Python Lectures:Part 1 - Introduction to
PythonHesham al-Ammal
University of Bahrain18/3/2013
Twitter: @heshaaamBlog and slides: heshaaam.wordpress.com
11Sunday, March 17, 13
Feel like flying?
Ref: xkcd.com2
2Sunday, March 17, 13
History: Name
Python is named based on the British comedy series Monty Python’s Flying Circus
Not the constricting snake
33Sunday, March 17, 13
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
Python’s Logo 1990-20054
4Sunday, March 17, 13
Interpreted vs CompiledProgramming Languages
Compiled Interpreted
C C++ Java Python Perl Lisp
Interactive vs. Batch
55Sunday, March 17, 13
Interactive Python$ pythonPython 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!
66Sunday, March 17, 13
Batch mode
#! /usr/bin/env python the_world_is_flat=1if the_world_is_flat: print "Be careful not to fall off"
Edit
Save Debug/RunPython file.pyfile.py
77Sunday, March 17, 13
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
88Sunday, March 17, 13
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
9Sunday, March 17, 13
Integers
Integer division: floor
Power
No limit to integer arithmetic except mempr (arbitrary long integers)
>>> 7/32>>> 2**521 -16864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151Lhttp://en.wikipedia.org/wiki/Mersenne_prime10
10Sunday, March 17, 13
Floating Point / Complex
Full support for floating point numbers and mixed arithmetic
Complex numbers are also supported
>>> 3 * 3.75 / 1.57.5>>> 7.0 / 23.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)
1111Sunday, March 17, 13
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.'
1212Sunday, March 17, 13
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'
1313Sunday, March 17, 13
Slicing strings
>>> word[:2] # The first two characters'He'>>> word[2:] # Everything except the first two characters'lpA'
1414Sunday, March 17, 13
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
>>> 'x' + word[1:]'xelpA'>>> 'Splat' + word[4]'SplatA'
However, this is OK: creating new strings
1515Sunday, March 17, 13
Negative string slicing
Indices may be negative numbers, to start counting from the right.
>>> 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'
0 1 2 3 4 5-5 -4 -3 -2 -1
H e l p A
Imagine numbers between characters
1616Sunday, March 17, 13
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
17Sunday, March 17, 13
More about lists>>> # Replace some items:... a[0:2] = [1, 12]>>> a[1, 12, 123, 1234]>>> # Remove some:... 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 like strings
1818Sunday, March 17, 13
Even more about lists
You can use len()
Lists can be nested
>>> 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']
1919Sunday, March 17, 13
Our first useful program
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1>>> while b < 10:... print b... a, b = b, a+b...112358
Multiple assignments
Indentation defines block
Interactive mode
In other languages:
temp = aa = bb = temp
In Python:
b, a = a, b
2020Sunday, March 17, 13
Our first useful program
#! /usr/bin/env python
# Fibonacci series:# the sum of two elements defines the nexta, b = 0, 1while b < 10: print b a, b = b, a+b
Batch mode
2121Sunday, March 17, 13
Interlude
And now for something completely different
2222Sunday, March 17, 13
The Zen of Python 1Beautiful 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.
UOB Students
2323Sunday, March 17, 13
The Zen of Python 2In 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!
2424Sunday, March 17, 13
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
2525Sunday, March 17, 13
Back to our regularly scheduled programming
2626Sunday, March 17, 13
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
2727Sunday, March 17, 13
for loops
>>> # Measure some strings:... words = ['cat', 'window', 'defenestrate']>>> for w in words:... print w, len(w)...cat 3window 6defenestrate 12
Unlike for loops in C++, it iterates on elements of a sequence like a list or a string. For exmaple (no pun intended):
2828Sunday, March 17, 13
for loops and slicing
If you need to edit the sequencemake 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']
2929Sunday, March 17, 13
The range() functionFor 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 Mary1 had2 a3 little4 lamb
3030Sunday, March 17, 13
Enough with control structures
You just should know that there are more control structures when you need them:
break
continue
pass
3131Sunday, March 17, 13
Defining Functions
>>> def fib(n): # write Fibonacci series up to n... """Print a Fibonacci series up to n."""... a, b = 0, 1... 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
Documentation string literal
3232Sunday, March 17, 13
Return values
33
>>> 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]
Functions without return just return
None
Method append belongs to the object result
33Sunday, March 17, 13
More on functions: Default Arguments
34
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
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!')
Notice the in keyword
34Sunday, March 17, 13
Things I will not mention in functions
Arbitrary argument lists
Lambda forms
Documentation strings
3535Sunday, March 17, 13
Coding StyleUse 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).
3636Sunday, March 17, 13
Data Structures
3737Sunday, March 17, 13
Lists and their methods 1
38
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.
38Sunday, March 17, 13
Lists and their methods 2
39
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.
39Sunday, March 17, 13
Lists and their methods 3
40
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.
40Sunday, March 17, 13
Lists as stacks
41
>>> 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]
41Sunday, March 17, 13
Lists as queues
42
>>> 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 arrivaldeque(['Michael', 'Terry', 'Graham'])
use collections.deque which was designed to have fast appends and pops from both ends
42Sunday, March 17, 13
Functional Programming Tools
4343Sunday, March 17, 13
filter(function,sequence)
44
>>> def f(x): return x % 2 != 0 and x % 3 != 0...>>> filter(f, range(2, 25))[5, 7, 11, 13, 17, 19, 23]
44Sunday, March 17, 13
map(function, sequence)
45
>>> def cube(x): return x*x*x...>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
45Sunday, March 17, 13
reduce(function, sequence)
46
>>> def add(x,y): return x+y...>>> reduce(add, range(1, 11))55
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.
46Sunday, March 17, 13
List comprehension
47
>>> squares = []>>> for x in range(10):... squares.append(x**2)...>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)]
You can do this
or get the same result with this
47Sunday, March 17, 13
More list comprehension
48
>>> [(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)]
>>> 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)]
is equivalent to
48Sunday, March 17, 13
Dictionaries
49
>>> 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 telTrue
Associative memory
49Sunday, March 17, 13
What have we learned?
Hopefully some
basic syntax Python
Phylosophy of Python
All of the tools that you need, elegantly
5050Sunday, March 17, 13
What we haven’t learnt
The Python Standard Library
Other useful libraries
5151Sunday, March 17, 13
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
5252Sunday, March 17, 13
Why Python?
Open source, join the revolution
Runs on all platforms
Cython for high performance
iPython (replace Mathematica)
MatPlotLib (replace Matlab)
5353Sunday, March 17, 13
More Python?
python.org
The tutorial
http://docs.python.org/2/tutorial/
Many video lectures on many topics
http://pyvideo.org/
5454Sunday, March 17, 13
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.
5555Sunday, March 17, 13
5656Sunday, March 17, 13
57
Thank you for listening
57Sunday, March 17, 13