Title: Introduction to Python
1Introduction to Python
Materials based on contents from the course
Programming with Python by Chad Haynes
2Outline
- Overview
- Built-in objects
- Functions and scopes
- Object-oriented programming
- Functional programming
- Exercise
3Python At First Glance
import math def showArea(shape) print "Area
d" shape.area() def widthOfSquare(area)
return math.sqrt(area) class Rectangle(object)
def __init__(self, width, height) self.width
width self.height height def
area(self) return self.width
self.height Main Program r
Rectangle(10, 20) showArea(r)
4Why use Python?
- Simple, clean syntax
- Portable
- Flexible
- Large standard library
- Short development time
- Lots of 3rd-party tools/add-ons
- Many good implementations
- CPython, PyPy, IronPython, Jython
- Strong support from open-source community
5Similarities to Java
- Everything inherits from "object"
- Also numbers, functions, classes,
- Everything is first-class
- Vast, powerful standard library
- Garbage collection
- Introspection, serialization, threads, net,
6Similarities to C
- Multi-paradigm
- OOP, procedural, generic, functional (a little)
- Multiple inheritance
- Operator overloading
7Python vs. Java/C/C
- Typing strong, but dynamic
- Names have no type
- Objects have types
- No declarations
- Sparse syntax
- No for blocks, just indentation
- No ( ) for if/while conditions
- Interactive interpreter
- for comments
8Getting Started
- Python already included in most Linux
distributions - Windows users can download from
- http//python.org/download
- Add python to PATH to run scripts from command
line
9Hello, World!
using System class Hello static void
Main() Console.WriteLine("Hello,
World")
print "Hello, World!"
10Variables
gtgtgt x 23 gtgtgt print x 23 gtgtgt x 'foo' gtgtgt print
x foo gtgtgt del x gtgtgt print x Traceback (most
recent call last) File "ltstdingt", line 1, in
ltmodulegt NameError name 'x' is not defined gtgtgt
name x means 23
now it means 'foo'
x becomes undefined
11Variables
- Reference Model
- Variables refer to an object
- More than one variable can refer to the same
object
Var1
Var1_copy
Var2
12Numeric Types
- Integers
- Generally 32 signed bits
- Long Integers
- Unlimited size
- Format ltnumbergtL
- Example 4294967296L
- Float
- Platform dependant double precision
- Complex
- Format ltrealgtltimaggtj
- Example 63j
13Strings
- A sequence of characters enclosed with quotes
- 3 quoting styles
- 'Single Quotes'
- "Double Quotes"
- """Triple Quotes"""
- Examples
- gtgtgt print 'This may contain a "'
- This may contain a "
- gtgtgt print "A ' is allowed"
- A ' is allowed
- gtgtgt print """Either " or ' are OK"""
- Either " or ' are OK
14Built-in Function raw_input
- Syntax raw_input(prompt)
- Use prompt to ask user to input a string
- Example
gtgtgt info raw_input('-gt ') -gt Here is info gtgtgt
print info Here is info
15Basic Operations
- Arithmetic
- - // / abs
- Example
- gtgtgt 5 3 Addition
- 8
- gtgtgt 2 8 Exponentiation
- 256
- gtgtgt 13 / 4 Integer (Truncating)
Division - 3
- gtgtgt float(13) / 4 Float Division
- 3.25
- gtgtgt 13 4 Remainder
- 1
- gtgtgt abs(-3.5) Absolute Value
- 3.5
Becomes float division in version 3.x
16Basic Operations
- Comparison
- lt lt gt gt ! ltgt
- Results in 1 (true) or 0 (false)
- Example
- gtgtgt 4 gt 1.5
- 1
- gtgtgt 'this' ! 'that'
- 1
- gtgtgt 43j 4-2j
- 0
- gtgtgt '5' 5
- 0
- gtgtgt 0 lt 10 lt 20
- 1
17Basic Operations
- Boolean
- and or not
- Based on Boolean Algebra
i1
i2
i1 and i2
i1 or i2
1
1
1
1
1
0
0
1
0
1
0
1
0
0
0
0
18Basic Operations
- Boolean
- Example
- gtgtgt 1 1 and 2 gt 3
- 0
- gtgtgt 1 1 or 2 gt 3
- 1
- gtgtgt not 5.3 ! 2.2 same as not (5.3 !
2.2) - 0
- gtgtgt 2 and '23' gt '11' or 0
- 1
19Strings - Operations
- Concatenation ()
- Syntax string1 string2
- Example
- gtgtgt 'Rockefeller' 'University'
- 'RockefellerUniversity'
- Repetition ()
- Syntax string number
- Example
- gtgtgt 'dog' 5
- 'dogdogdogdogdog'
20Strings - Formatting
- C-Style formatting (extended printf)
- Examples
- gtgtgt "i s in the basket" (2, "eggs")
- '2 eggs in the basket'
- gtgtgt "f to 2 decimal places .2f" (2.0/9.0,
2.0/9.0) - '0.222222 to 2 decimal places 0.22'
- gtgtgt length 5
- gtgtgt obj "fence"
- gtgtgt "Length of the (obj)s is (length)i"
vars() - 'Length of the fence is 5'
21Built-in Function type
- Syntax type(object)
- Used to determine the type of an object
- Example
- gtgtgt type(2.45)
- lttype 'float'gt
- gtgtgt type('x')
- lttype 'str'gt
- gtgtgt type(234)
- lttype 'long'gt
- gtgtgt type(32j)
- lttype 'complex'gt
22Type Conversions
- Use built-in functions to convert between types
- str() int() float() long() complex() bool()
- Example
- gtgtgt str(42.3)
- '42.3'
- gtgtgt float('-1.32e-3')
- -0.00132
- gtgtgt int('0243')
- 243
- gtgtgt int(234)
- Traceback (most recent call last)
- File "ltpyshell12gt", line 1, in ?
- int(234)
- OverflowError long int too large to convert to
int - gtgtgt long(234)
- 17179869184L
23Data Structures
24Lists
- Construction
- Syntax elem1, elem2,
- Heterogeneous, ordered sequence
- Mutable
- Example
- gtgtgt list1 1, 'hello', 42j, 123.12
- gtgtgt list1
- 1, 'hello', (42j), 123.12
- gtgtgt list10 'a'
- gtgtgt list1
- 'a', 'hello', (42j), 123.12
25Lists - Operations
- Concatenation ()
- Syntax list1 list2
- Example
- gtgtgt 1, 'a', 'b' 3, 4, 5
- 1, 'a', 'b', 3, 4, 5
- Repetition ()
- Syntax list number
- Example
- gtgtgt 23, 'x' 4
- 23, 'x', 23, 'x', 23, 'x', 23, 'x'
26Indexing
- Indexing operator
- Positive indices count from the left
- Negative indices count from the right
0 1 2 3 4 5 6
a b c d e f g
-7 -6 -5 -4 -3 -2 -1
sequence0 a sequence-7 a sequence6
g sequence-1 g sequence2 c sequence-5
c
27List Slicing
- Two indices separated by a colon
- Available for both strings and lists
- Example
- gtgtgt sequence 0, 1, 2, 3, 4, 5, 6, 7
- gtgtgt sequence14
- 1, 2, 3
- gtgtgt sequence2-1
- 2, 3, 4, 5, 6
- Missing Index implies end point
- gtgtgt sequence2
- 0, 1
- gtgtgt sequence3
- 3, 4, 5, 6, 7
28Tuples
- Immutable version of list
- Syntax (elem1, elem2, )
- Items in tuple can not be altered
- Example
- gtgtgt tuple1 (1, 5, 10)
- gtgtgt tuple12 2
- Traceback (most recent call last)
- File "ltpyshell136gt", line 1, in ?
- tuple12 2
- TypeError object doesn't support item
assignment
29Built-in Function len
- Syntax len(object)
- Return the length of object
- Example
- gtgtgt list1 1, 2, 3, 4, 5
- gtgtgt len(list1)
- 5
- gtgtgt string1 "length of a string"
- gtgtgt len(string1)
- 18
30Dictionaries
- Mapping
- Associate a key with a value
- Each key must be unique
-
keys
10
2
(3,8)
'hello'
values
31Dictionaries
- Construction
- Syntax key1 value1, key2 value2
- Unordered map
- Example
- gtgtgt dict1 'a' 1, 'b' 2
- gtgtgt dict1
- 'a' 1, 'b' 2
- gtgtgt dict1'a'
- 1
- gtgtgt dict1'b'
- 2
32Control Flow
Examples
if condition body elif condition body else b
ody
if x2 0 y y x else y y - x
while i lt 0 count count 1
while condition body
for x in 1,2,3 sum sum x
for name in iterable body
33Built-in Function range
- Syntax range(start, stop, step)
- Generate a list of numbers from start to stop
stepping every step - start defaults to 0, step defaults to 1
- Example
- gtgtgt range(5)
- 0, 1, 2, 3, 4
- gtgtgt range(1, 9)
- 1, 2, 3, 4, 5, 6, 7, 8
- gtgtgt range(2, 20, 5)
- 2, 7, 12, 17
34Controlling Flow
- Using range with for
- Generate list used by for with range
- Example
- gtgtgt for i in range(4)
- print i
- 0
- 1
- 2
- 3
35Controlling Flow
- The continue statement
- Continue to next iteration of loop, skipping
remainder of body - Example
- gtgtgt for x in range(8)
- if x2 0
- continue
- print x
-
1
3
5
7
36Controlling Flow
- The break statement
- Break out of inner most loop
- Example
- gtgtgt for number in range(10)
- if number 4
- print 'Breaking'
- break
- else
- print number
- 0
- 1
- 2
- 3
- Breaking
37Using Data Structures
- Data structures also have methods
- Use built-in function dir to list all available
methods - Example
- gtgtgt lst 1, 3, 2
- gtgtgt dir(lst)
- '__add__', '__class__', '__contains__',
'__delattr__', '__delitem__', '__delslice__',
'__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__',
'__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__repr__',
'__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__str__', 'append', 'count',
'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort'
38Strings - Methods
- split
- Syntax string.split(sep)
- Returns a list of strings
- Example
- gtgtgt text "1 2 4 5 1"
- gtgtgt text.split()
- '1', '2', '4', '5', '1'
- gtgtgt test "a, b, c, d, e"
- gtgtgt test.split(',')
- 'a', ' b', ' c', ' d', ' e'
39Strings - Methods
- strip
- Syntax string.strip()
- Remove leading and trailing white space (tabs,
new lines, etc) - Example
- gtgtgt padded " stuff "
- gtgtgt padded.strip()
- 'stuff'
- gtgtgt padded
- ' stuff '
- gtgtgt unpadded padded.strip()
- gtgtgt unpadded
- 'stuff'
40Lists - Methods
- append
- Syntax list.append(element)
- Add element to end of list
- Example
- gtgtgt list1 3, '10', 2
- gtgtgt list1.append('new')
- gtgtgt list1
- 3, '10', 2, 'new'
41Lists - Methods
- pop
- Syntax list.pop(index)
- Remove and return item at position index from
list - Default is to remove last item
- Example
- gtgtgt list1 3, '10', 2, 9, 11
- gtgtgt list1.pop()
- 11
- gtgtgt list1
- 3, '10', 2, 9
42Lists - Methods
- insert
- Syntax list.insert(index, element)
- Insert element into list at position index
- Example
- gtgtgt list2 0, 1, 2, 3, 4, 5
- gtgtgt list2.insert(3, 'new')
- gtgtgt list2
- 0, 1, 2, 'new', 3, 4, 5
43Lists - Methods
- remove
- Syntax list.remove(element)
- Removes the first occurrence of element in list
- Example
- gtgtgt list2 0, 1, 3, 4, 3, 5
- gtgtgt list2.remove(3)
- gtgtgt list2
- 0, 1, 4, 3, 5
44Lists - Methods
- sort
- Syntax list.sort(cmpfunc)
- Sort list in place
- Example
- gtgtgt list3 4, 12, 3, 9
- gtgtgt list3.sort()
- gtgtgt list3
- 3, 4, 9, 12
45Lists - Methods
- reverse
- Syntax list.reverse()
- Reverse elements of list in place
- Example
- gtgtgt list3 4, 12, 3, 9
- gtgtgt list3.reverse()
- gtgtgt list3
- 9, 3, 12, 4
46Dictionaries - Methods
- keys
- Syntax dict.keys()
- Return a list of all the keys in dict
- Example
- gtgtgt dict1 1 'a', 9 'cat', 2 2, 1
- gtgtgt dict1.keys()
- 1, 2, 9
47Dictionaries - Methods
- has_key
- Syntax dict.has_key(key)
- Determines if key is in dict
- Example
- gtgtgt dict1 'x' 1, 'y' 2
- gtgtgt dict1.has_key('x')
- 1
- gtgtgt dict1.has_key('w')
- 0
48Dictionaries - Methods
- values
- Syntax dict.values()
- Returns a list of all values in dict
- Example
- gtgtgt dict1 (1,2) 'a', (3,4) 'b', (9,8,7)
'c' - gtgtgt dict1.values()
- 'a', 'c', 'b'
49Getting Help
- For interactive use, calling help function will
invoke the built-in help system - Call help() without argument for interactive mode
gtgtgt help(str) Help on class str in module
__builtin__ class str(basestring)
str(object) -gt string Return a nice
string representation of the object. If the
argument is a string, the return value is the
same object. Method resolution order
str basestring object
Methods defined here __add__(...)
x.__add__(y) ltgt xy
__contains__(...) x.__contains__(y) ltgt
y in x
50Functions and Scopes
51Defining Functions
- Syntax def func(arg1, )
- body
- Body of function must be indented
- If no value is returned explicitly, function will
return None - Example
- gtgtgt def average(num1, num2, num3)
- sum num1 num2 num3
- avg sum / 3.0
- return avg
-
52Functions
- Parameters
- Parameters can be any type
- A function can take any number of parameters (or
none at all) - Example
- gtgtgt def usage(programName, version)
- print s Version i' (programName, version)
- print 'Usage s arg1 arg2 (programName)
- gtgtgt usage('Test', 1.0)
- Test Version 1.0
- Usage Test arg1 arg2
53Functions
- Default Parameters
- One or more parameters can be given a default
value - The function can be called with fewer arguments
than there are parameters - All non-default (required) parameters must
precede default parameters - Example
- gtgtgt def printName(last, first, mi"")
- print "s, s s" (last, first, mi)
- gtgtgt printName("Smith", "John")
- Smith, John
- gtgtgt printName("Smith", "John", "Q")
- Smith, John Q
-
54Functions
- Calling functions
- Syntax func(arg1, arg2, argn)
- Order of arguments must match order of declared
parameters - No type checking is done
- Example
- gtgtgt def display(arg1, arg2, arg3)
- print arg1
- print arg2
- print arg3
- gtgtgt display(1, 'x', 4.3)
- 1
- x
- 4.3
55Functions
- Keyword arguments
- Functions can be called using the keyword of the
argument - Syntax func(keywordvalue, )
- The order of the values passed by keyword does
not matter - Example
- def keywords(key1"X", key2"X",
key3"X",key4"X") - print key1, key2, key3, key4
- gtgtgt keywords(key3"O", key2"O")
- X O O X
- gtgtgt keywords()
- X X X X
56Functions
- Functions as variables
- Functions can be assigned
- Example
- def sub(a, b)
- return a-b
-
- gtgtgt op sub
- gtgtgt print op(3, 5)
- -2
- gtgtgt type(op)
- lttype 'function'gt
57Functions
- Functions as parameters
- Functions can be passed to other functions
- Example
- def convert(data, convertFunc)
- for i in range(len(data))
- datai convertFunc(datai)
- return data
- gtgtgt convert('1', '5', '10', '53', int)
- 1, 5, 10, 53
- gtgtgt convert('1', '5', '10', '53', float)
- 1.0, 5.0, 10.0, 53.0
- gtgtgt convert('1', '5', '10', '53', complex)
- (10j), (50j), (100j), (530j)
58Functions
- Returning multiple values
- Return a tuple containing the values to return
- Example
- def separate(text, size3)
- start textsize
- end text-size
- return (start, end)
- gtgtgt separate('sample text')
- ('sam', 'ext')
- gtgtgt start, end separate('sample text')
- gtgtgt print start
- sam
- gtgtgt print end
- ext
59Generators
- Generators are functions that generate sequence
of items - Generated sequence can be infinite
def fibonacci() i j 1 while True r, i,
j i, j, ij yield r for rabbits in
fibbonacci() print rabbits if rabbits gt 100
break
1 1 2 3 5 8 13 21 34 55 89 144
60Namespaces and Scopes
- Namespace
- A mapping from names to objects
- (Currently) implemented as Python dictionaries
- Scope
- A region of program where a namespace is directly
accessible - Name references search at most 3 scopes local,
global, built-in - Assignments create or change local names by
default - Can force arguments to be global with global
command
61Scope Example
x 99 def func(Y) Z XY X is not assigned,
so it's global return Z func(1)
62Modules
- A file containing Python definitions and
statements - Modules can be imported
- Module file name must end in .py
- Used to divide code between files
math.py
string.py
import math import string
63import Statement
- Syntax 1 import ltmodule namegt
- Module name is the file name without the .py
extension - You must use the module name to call the
functions - Example
- gtgtgt import math
- gtgtgt dir(math)
- '__doc__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot',
'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'sin', 'sinh', 'sqrt', 'tan', 'tanh' - gtgtgt print math.e
- 2.71828182846
- gtgtgt print math.sqrt(2.3)
- 1.51657508881
64import Statement
- Syntax 2 from ltmodulegt import ltnamegt
- Import only a specific name from a module into
global namespace - Module name is not required to access imported
name - Example
- gtgtgt from math import sqrt
- gtgtgt sqrt(16)
- 4
- gtgtgt dir(math)
- Traceback (most recent call last)
- File "ltstdingt", line 1, in ltmodulegt
- NameError name 'math' is not defined
65import Statement
- Syntax 2a from ltmodulegt import
- Import everything from a module into global
namespace - Example
- gtgtgt dir()
- '__builtins__', '__doc__', '__name__'
- gtgtgt from time import
- gtgtgt dir()
- '__builtins__', '__doc__', '__name__',
'accept2dyear', 'altzone', 'asctime', 'clock',
'ctime', 'daylight', 'gmtime', 'localtime',
'mktime', 'sleep', 'strftime', 'struct_time',
'time', 'timezone', 'tzname' - gtgtgt time()
- 1054004638.75
66Python Standard Libraries
- Some examples
- sys - System-specific parameters and functions
- time - Time access and conversions
- thread - Multiple threads of control
- re - Regular expression operations
- email - Email and MIME handling package
- httplib - HTTP protocol client
- Tkinter - GUI package based on Tcl/Tk
- See http//docs.python.org/library/index.html
67File Objects
- Opening a file
- Syntax open(fileName, mode)
- Mode is one of
- 'r' Read
- 'w' Write
- 'a' Append
- If a file opened for writing does not exist it
will be created - Example
- gtgtgt inFile open('input.txt', 'r')
- gtgtgt type(infile)
- lttype 'file'gt
68File Objects - Methods
- read(size)
- Read at most size bytes and return text as a
string - readlines(size)
- Read the lines of the file into a list of
strings. - Use size as an approximate bound on the number of
bytes returned
69File Objects - Methods
- write(text)
- Write text to the file
- writelines(string_sequence)
- Write each string in the sequence to the file
- New lines are not added to the end of the strings
70Exceptions
- Definition
- Errors detected during execution
- Basic Example
- Divide by zero
- gtgtgt 1 / 0
- Traceback (most recent call last)
- File "ltpyshell0gt", line 1, in ?
- 1 / 0
- ZeroDivisionError integer division or modulo by
zero
71Exceptions
- Motivation
- Move error handling code away from main code
block - Deal with exceptional cases separately
- How it works
- Exceptions are thrown (or raised) and caught
- Control exits the current code block when the
exception is thrown - An exception can then be caught by a catching
code block
72Exceptions
- Throwing
- Many common operations may throw an exception
- List index out of bounds
- Invalid type conversions
- Exceptions can be thrown manually using the raise
keyword - gtgtgt raise ValueError, "Bad Value
- Catching
- Thrown exceptions must be caught
- If the exception is never caught the progam will
terminate
73Exceptions
- Handling Syntax
- try
- lttry code blockgt
- except ltException Listgt
- ltexception code blockgt
- except ltException Listgt
- ltexception code blockgt
- except
- ltexception code blockgt
- else
- ltelse codegt
74Exceptions
- Example
- try
- x 1 / 0
- except ZeroDivisionError
- print 'Divide by zero error'
- Divide by zero error
75Exceptions
- Example
- try
- x 1 / 0
- except IOError
- print 'Input/Output error'
- except
- print 'Unknown error'
-
- Unknown error
76Exceptions
- Types of Exceptions
- There is a hierarchy of exceptions
- All built-in exceptions are derived from
Exception - An exception will be caught by any type higher up
in the hierarchy -
Exception
StandardError
ArithmeticError
ZeroDivisionError
SystemExit
ValueError
OverflowError
StopIteration
LookupError
IndexError
KeyError
77Exceptions
- Example
- try
- x 1 / 0
- except Exception
- print 'Exception caught'
-
- Exception caught
78Exceptions
- Propagation
- If no proper except block can be found in the
current block, the exception propagates back to
the calling function - def func1()
- try
- a 1 / 0
-
- except ValueError
- print 'first'
- def func2()
- try
- func1()
- except
- print 'second'
- gtgtgt func2()
- second
79Exceptions
- Example
- try
- x 1 / 0
- except Exception
- print 'Exception caught'
-
- Exception caught
80OO Programming
81Defining a Class
- Syntax
- Creating a class with no superclass
- Basically, classes are simply namespaces
class name(base) body
class MyClass(object) myvar 30 gtgtgt
MyClass.myvar 30
82Class Example
- All instance methods must explicitly take an
instance as the first parameter - self is a commonly used name
class Rectangle(object) def __init__(self,
width, height) self.width width self.height
height def area(self) return self.width
self.height
Constructor
gtgtgt r Rectangle(10, 20) gtgtgt Rectangle.area(r) 20
0 gtgtgt r.area() 200
83Inheritance
- Subclass must invoke parent's constructor
explicitly
class Square(Rectangle) def __init__(self,
width) Rectangle.__init__(self, width, width)
gtgtgt s Square(100) gtgtgt s.area() 10000
84Polymorphism
import math class Circle(object) def
__init__(self, radius) self.radius
radius def area(self) return
math.piself.radiusself.radius
gtgtgt shapes Square(5), Rectangle(2,8),
Circle(3) gtgtgt for x in shapes ... print
x.area() ... 25 16 28.2743338823
85Python Object Hooks
- Objects can support built-in operators by
implementing certain special methods - The usual operators , -, , /, , , , , !
- Indexing (like sequences) objidx
- Calling (like functions) obj(args,...)
- Iteration and containment tests
- for item in obj...
- if item in obj...
86Functional Programming
87Functional Approaches
- Taken from functional languages
- Lisp/Scheme
- Haskell
- Added to Python as built-in functions
- map()
- filter()
- reduce()
- zip()
88Built-in function map
- Perform an operation on each element of a list
- A function is applied to each element
- The results of each function call are used to
generate a new list - The resulting list is always the same length as
the original list - The original list is not altered
89Built-in function map
func
y1
90Built-in function map
func
y2
y1
91Built-in function map
func
y3
y1
y2
92Built-in function map
func
y4
y1
y2
y3
93Built-in function map
func
y5
y1
y2
y3
y4
94Built-in function map
func
y6
y1
y2
y3
y4
y5
95Built-in function map
func
y7
y1
y2
y3
y4
y5
y6
96Built-in function map
func
y8
y1
y2
y3
y4
y5
y6
y7
97Built-in function map
- Syntax 1 map(func, list)
- Example Convert a list of integers to strings
- gtgtgt lst1 1, 2, 3, 4
- gtgtgt lst2 map(str, lst1)
- gtgtgt print lst2
- '1', '2', '3', '4'
- The function (str) takes one argument
- The result (lst2) is the same length as the
original (lst1)
98Built-in function map
- What if the function requires more than one
argument? - Multiple lists can be passed to the map function
- Syntax 2 map(func, list1, , listn)
- All lists must be of same length
- The function must take n parameters
99Built-in function map
- Example adding numbers
- def add2(a, b)
- return ab
- gtgtgt lst1 0, 1, 2, 3
- gtgtgt lst2 4, 5, 6, 7
- gtgtgt print map(add2, lst1, lst2)
- 4, 6, 8, 10
100Code Comparison
lst1 1, 2, 3, 4 lst2 for element in
lst1 lst2.append(str(element))
lst1 1, 2, 3, 4 lst2 map(str, lst1)
101Code Comparison
lst1 0, 1, 2, 3 lst2 4, 5, 6, 7 lst3
for index in range(len(lst1)) lst3.append(add
2(lst1index, lst2index))
lst1 0, 1, 2, 3 lst2 4, 5, 6, 7 lst2
map(add2, lst1, lst2)
102Benefits
- The map function can be used like an expression
- Can be used as a parameter to a function
- Example
- gtgtgt lst1 1, 2, 3, 4
- gtgtgt string.join(lst1) Error because lst1
contains ints -
- TypeError sequence item 0 expected string, int
found - gtgtgt string.join( map(str, lst1) ) Correct
- '1 2 3 4'
103Built-in function filter
- Remove elements of a list based on a condition
- Each element of a list is tested, those that fail
are removed - The resulting list is the same length or shorter
than the original - The original list is not altered
104Built-in function filter
- Syntax filter(func, list)
- Example Remove all negative numbers
- def removeNegative(number)
- return number gt 0
- gtgtgt lst1 1, 2, -3, 4
- gtgtgt lst2 filter(removeNegative, lst1)
- gtgtgt print lst2
- 1, 2, 4
- The function (str) takes one argument and returns
0 or 1 - The result (lst2) is shorter than the original
(lst1)
105Code Comparison
lst1 1, 2, -3, 4 lst2 for element in
lst1 if removeNegative(element) lst2.append(e
lement)
lst1 1, 2, -3, 4 lst2 filter(removeNegative,
lst1)
106Built-in function reduce
- Apply a function cumulatively to a sequence
- The function must take 2 parameters
- Function is applied to parameters from left to
right - The list is reduced to a single value
- The original list is not altered
107Built-in function reduce
y1
y2
y3
y4
func
t1
func
t2
func
t3
108Example Reduce by Adding
1
10
20
30
110
11
1120
31
3130
61
109Built-in function reduce
- Syntax 1 reduce(func, list)
- Example Find the sum of a list of integers
- gtgtgt lst1 1, 2, 3, 4
- gtgtgt sum reduce(operator.add, lst1)
- gtgtgt print sum
- 10
- The function (operator.add) takes two arguments
- The result is a single value
110Built-in function reduce
- Syntax 2 reduce(func, list, initialValue)
- The initialValue is applied to func with the
first value in the list - If the list is empty, the initialValue is
returned - Example Concatenating lists
- gtgtgt lst1 2, 4, 5, 9, 1, 7
- gtgtgt result reduce(operator.add, lst1, 100)
- gtgtgt print result
- 100, 2, 4, 5, 9, 1, 7
111Code Comparison
lst1 1, 2, 3, 4 sum operator.add(lst10,
lst11) for element in lst12 sum
operator.add(sum, element)
lst1 1, 2, 3, 4 sum reduce(operator.add,
lst1)
112Code Comparison
lst1 2, 4, 5, 9, 1, 7 result
operator.add(100, lst10) for element in
lst11 result operator.add(sum, element)
lst1 2, 4, 5, 9, 1, 7 result
reduce(operator.add, lst1, 100)
113Built-in function zip
- Combine multiple lists into one
- Elements are paired by index
- The resulting list is the same length as the
shortest list supplied - Each element of resulting list contains a tuple
- The original lists are not altered
114Built-in function zip
y1
y2
y3
y4
x1
x2
x3
x4
(x1, y1)
(x2, y2)
(x4, y4)
(x3, y3)
115Built-in function zip
- Syntax zip(list1, , listn)
- Example Combine two lists
- gtgtgt lst1 1, 2, 3, 4
- gtgtgt lst2 'a', 'b', 'c', 'd', 'e'
- gtgtgt result zip(lst1, lst2)
- gtgtgt print result
- (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')
- The e element was truncated since lst1 only has
4 elements - The result is a list of tuples
116Code Comparison
lst1 1, 2, 3, 4 lst2 'a', 'b', 'c', 'd',
'e' lst3 for index in range(min(len(lst1),
len(lst2)) lst3.append( (lst1index,
lst2index) )
lst1 1, 2, 3, 4 lst2 'a', 'b', 'c', 'd',
'e' lst3 zip(lst1, lst2)
117Uses for zip
- Iterate over two lists simultaneously
- gtgtgt produce 'apples', 'oranges', 'pears'
- gtgtgt prices 0.50, 0.45, 0.55
- gtgtgt for fruit, cost in zip(produce, prices)
- print 's cost .2f'(fruit, cost)
- apples cost 0.50
- oranges cost 0.45
- pears cost 0.55
118Uses for zip
- Create a dictionary using dict()
- gtgtgt produce 'apples', 'oranges', 'pears'
- gtgtgt prices 0.50, 0.45, 0.55
- gtgtgt priceDict dict(zip(produce, prices))
- gtgtgt print priceDict
- 'pears' 0.55, 'apples' 0.5, 'oranges' 0.45
119List Comprehensions
- Generate new lists from old ones
- Can simultaneously map and filter
- More flexible than the built-in functions
120Basic List Comprehensions
- Basic Syntax ltexpgt for ltvargt in ltlistgt
- The resulting list is the result of exp evaluated
for each var in list - Example Increase each element by 1
- gtgtgt x1 for x in range(5)
- 1, 2, 3, 4, 5
- Example Convert each element to a string
- gtgtgt str(x) for x in range(5)
- '0', '1', '2', '3', '4'
121More List Comprehensions
- Syntax ltex1gt for ltvargt in ltlistgt if ltex2gt
- ex1 is only evaluated if ex2 is true
- Example Remove smallest element
- gtgtgt lst1 5, 10, 3, 9
- gtgtgt x for x in lst1 if x ! min(lst1)
- 5, 10, 9
- Example Sum all lists of size greater than 2
- gtgtgt lst1 1, 2, 4, 3, 1, 5, 9, 10, 11
- gtgtgt reduce(operator.add, x) for x in lst1 if
len(x) gt 2 - 7, 35
122More List Comprehensions
- Multiple for loops can be included
- The loops will be nested
- Example Generate all possible combinations of
letters a, c, g, t - gtgtgt nucleo 'a', 'g', 'c', 't'
- gtgtgt ab for a in nucleo for b in nucleo
- 'aa', 'ag', 'ac', 'at', 'ga', 'gg', 'gc',
'gt', 'ca', 'cg', 'cc', 'ct', 'ta', 'tg', 'tc',
'tt'
123Code Comparison
- nucleo 'a', 'g', 'c', 't'
- results
- for a in nucleo
- for b in nucleo
- results.append(ab)
nucleo 'a', 'g', 'c', 't' results ab for
a in nucleo for b in nucleo
124Lambda Functions
- Anonymous functions
- Body can consist of only a single expression
- Execute slightly slower than normal functions
- Can take any number of parameters
- In general, lambda functions should be avoided
125Lambda Functions
- Syntax lambda p1,,pn ltexpgt
- Expression should not use return
- Example adding two numbers
- gtgtgt add2 lambda a,b ab
- gtgtgt print add2(1, 5)
- 6
- Example simple factorial
- gtgtgt fac lambda x reduce(lambda a,b ab,
range(1, x1)) - gtgtgt print fac(5)
- 120
126References
- Python Documentation
- ? http//docs.python.org
- Python for Programmers by Alex Martelli
- Advanced Python (Understanding Python) by Thomas
Wouters
127Exercise
- Write a Python program freq.py to
- Fetch a text file from the web
- Then report the most 10 frequently used words
python freq.py http//www.cpe.ku.ac.th/cpj/gpl.
txt 345 the 221 of 192 to 184 a
151 or 128 you 102 license 98 and
97 work 91 that
128Exercise Hints
- Accessing command-line arguments
- Reading a webpage
- Extracting all English words from text
import sys url sys.argv1
import urllib contents urllib.urlopen(url).read(
)
import re words re.findall('A-Za-z', text)