introduction to python modified from chen lin chen lin guido van rossum guido van rossum mark...
TRANSCRIPT
Introduction to Python
Modified from Modified from •Chen LinChen Lin•Guido van RossumGuido van Rossum•Mark HammondMark Hammond•John ZelleJohn Zelle
What Is Python?What Is Python?
Created in 1990 by Guido van RossumCreated in 1990 by Guido van RossumWhile at CWI, AmsterdamWhile at CWI, AmsterdamNow hosted by centre for national research Now hosted by centre for national research
initiatives, Reston, VA, USAinitiatives, Reston, VA, USAFree, open sourceFree, open source
And with an amazing communityAnd with an amazing communityObject oriented languageObject oriented language
““Everything is an object”Everything is an object”
Why Python?Why Python?Designed to be easy to learn and masterDesigned to be easy to learn and master
Clean, clear syntaxClean, clear syntaxVery few keywordsVery few keywords
Highly portableHighly portableRuns almost anywhere - high end servers and Runs almost anywhere - high end servers and
workstations, down to windows CEworkstations, down to windows CEUses machine independent byte-codesUses machine independent byte-codes
ExtensibleExtensibleDesigned to be extensible using C/C++, allowing Designed to be extensible using C/C++, allowing
access to many external librariesaccess to many external libraries
Most obvious and notorious Most obvious and notorious featuresfeatures
Clean syntax plus high-level data typesClean syntax plus high-level data typesLeads to fast codingLeads to fast coding
Uses white-space to delimit blocksUses white-space to delimit blocksHumans generally do, so why not the Humans generally do, so why not the
language?language?Variables do not need declarationVariables do not need declaration
Although not a type-less languageAlthough not a type-less language
4 Major Versions of Python4 Major Versions of Python
“Python” or “CPython” is written in C/C++Version 2.7Version 3.3
“Jython” is written in Java for the JVM
“IronPython” is written in C# for the .Net environment
Pydev with EclipsePydev with Eclipse
Python Interactive ShellPython Interactive Shell% python% pythonPython 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)[GCC 4.2.1 (Apple Inc. build 5646)] on darwin[GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.Type "help", "copyright", "credits" or "license" for more information.>>>>>>
You can type things directly into a running Python sessionYou can type things directly into a running Python session>>> 2+3*4>>> 2+3*41414>>> name = "Andrew">>> name = "Andrew">>> name>>> name'Andrew''Andrew'>>> print "Hello", name>>> print "Hello", nameHello AndrewHello Andrew>>>>>>
BackgroundBackgroundData Types/StructureData Types/StructureControl flowControl flowFile I/OFile I/OModulesModules
““Hello World” in Python Hello World” in Python
print "hello World!"print "hello World!"
BlocksBlocks
Blocks are delimited by indentationBlocks are delimited by indentationColon used to start a blockColon used to start a blockTabs or spaces may be usedTabs or spaces may be usedMaxing tabs and spaces works, but is discouragedMaxing tabs and spaces works, but is discouraged
>>> if 1:>>> if 1:... ... print "True"print "True"... ... TrueTrue>>>>>>
Python Build-in typesPython Build-in types
Numbers Numbers 3.1415 3.1415Strings Strings “Hello World” “Hello World”Lists Lists [1,2,3,4] [1,2,3,4]Dictionaries {‘test’: ‘yum’}Dictionaries {‘test’: ‘yum’}Files input=open(‘file.txt’, ‘r’)Files input=open(‘file.txt’, ‘r’)
Variables and TypesVariables and Types
Objects always have a typeObjects always have a type>>> a = 1>>> a = 1>>> type(a)>>> type(a)<type 'int'> <type 'int'> >>> a = "Hello">>> a = "Hello">>> type(a)>>> type(a)<type 'string'><type 'string'>>>> type(1.0)>>> type(1.0)<type 'float'><type 'float'>
Number in ActionNumber in Action
>>> a=3 #Name Created>>> a=3 #Name Created
>>> b=4>>> b=4
>>> a+1, a-1 # (3+1), (3-1)>>> a+1, a-1 # (3+1), (3-1)
(4,2)(4,2)
>>> b*3, b/2>>> b*3, b/2
(12,2)(12,2)
Simple Data TypesSimple Data Types Integer objects implemented using C Integer objects implemented using C
longslongsLike C, integer division returns the floorLike C, integer division returns the floor>>> 5/2>>> 5/222
Float types implemented using C doublesFloat types implemented using C doublesNo point in having single precision since No point in having single precision since
execution overhead is large anywayexecution overhead is large anyway
Simple Data TypesSimple Data Types
Long Integers have unlimited sizeLong Integers have unlimited sizeLimited only by available memoryLimited only by available memory>>> long = 1L << 64>>> long = 1L << 64>>> long ** 5>>> long ** 5213598703592091008239502170616955211460270452221359870359209100823950217061695521146027045223566527699470416078222197257806405500229620869356652769947041607822219725780640550022962086936576L36576L
High Level Data TypesHigh Level Data Types
Tuples are similar to listsTuples are similar to listsSequence of itemsSequence of itemsKey difference is they are immutableKey difference is they are immutableOften used in place of simple structuresOften used in place of simple structures
Automatic unpackingAutomatic unpacking>>> point = 2,3>>> point = 2,3>>> x, y = point>>> x, y = point>>> x>>> x22
Reference SemanticsReference Semantics
Assignment manipulates referencesAssignment manipulates referencesx = y x = y does not make a copydoes not make a copy of y of yx = y makes x x = y makes x referencereference the object y references the object y references
Very useful; but beware!Very useful; but beware! Example:Example:
>>> a = [1, 2, 3]>>> a = [1, 2, 3]
>>> b = a>>> b = a
>>> a.append(4)>>> a.append(4)
>>> print b>>> print b
[1, 2, 3, 4][1, 2, 3, 4]
a
1 2 3
b
a
1 2 3
b
4
a = [1, 2, 3]
a.append(4)
b = a
a 1 2 3
Changing a Shared ListChanging a Shared List
a
1
b
a
1b
a = 1
a = a+1
b = a
a 1
2
Changing an IntegerChanging an Integer
old reference deletedby assignment (a=...)
new int object createdby add operator (1+1)
StringsStrings
The next major build-in type is the Python The next major build-in type is the Python STRING --- an STRING --- an orderedordered collection of characters collection of characters to to storestore and and representrepresent text-based information text-based information
Python strings are categorized as Python strings are categorized as immutable immutable sequences sequences --- meaning they have a --- meaning they have a left-to-right left-to-right orderorder (sequence) and cannot be changed in (sequence) and cannot be changed in place (immutable)place (immutable)
Single- and Double-QuotedSingle- and Double-Quoted
Single- and Double-Quoted strings are the Single- and Double-Quoted strings are the samesame
>>> ‘Hello World’ , “Hello World” >>> ‘Hello World’ , “Hello World”
The reason for including both is that it The reason for including both is that it allows you to embed a quote character of allows you to embed a quote character of the other inside a stringthe other inside a string
>>> “knight’s” , ‘knight”s’>>> “knight’s” , ‘knight”s’
len()len()
The len build-in function returns the length The len build-in function returns the length of stringsof strings
>>> len(‘abc’)>>> len(‘abc’)
>>> a=‘abc’>>> a=‘abc’
>>> len(a)>>> len(a)
++ Adding two string objects creates a new string Adding two string objects creates a new string
objectobject
>>> ‘abc’ + ‘def’>>> ‘abc’ + ‘def’
>>> a=‘Hello’>>> a=‘Hello’>>> b=‘World’>>> b=‘World’>>> a + b>>> a + b>>> a+ ‘ ’ +b>>> a+ ‘ ’ +b
**
Repetition may seem a bit obscure at first, Repetition may seem a bit obscure at first, but it comes in handy in a surprising but it comes in handy in a surprising number of contextsnumber of contexts
For example, to print a line of 80 dashesFor example, to print a line of 80 dashes
>>> print ‘-’ * 80>>> print ‘-’ * 80
2525
Strings and Secret CodesStrings and Secret Codes
In the early days of computers, each In the early days of computers, each manufacturer used their own encoding of manufacturer used their own encoding of numbers for characters.numbers for characters.
ASCII system (American Standard Code ASCII system (American Standard Code for Information Interchange) uses 127 bit for Information Interchange) uses 127 bit codescodes
Python supports Unicode (100,000+ Python supports Unicode (100,000+ characters)characters)
2626
Strings and Secret CodesStrings and Secret Codes
The The ordord function returns the numeric (ordinal) function returns the numeric (ordinal) code of a single character.code of a single character.
The The chrchr function converts a numeric code to the function converts a numeric code to the corresponding character.corresponding character.
>>> ord("A")>>> ord("A")6565>>> ord("a")>>> ord("a")9797>>> chr(97)>>> chr(97)'a''a'>>> chr(65)>>> chr(65)'A''A'
ListsLists
Lists are Python’s Lists are Python’s most flexiblemost flexible ordered ordered collection object typecollection object type
Lists can contain any sort of object: Lists can contain any sort of object: numbers, strings and even other listsnumbers, strings and even other lists
Ordered collections of arbitrary objectsOrdered collections of arbitrary objectsAccessed by offsetAccessed by offsetVariable length, heterogeneous, Variable length, heterogeneous,
arbitrary nestablearbitrary nestable
ListList
A compound data type:A compound data type:[0][0][2.3, 4.5][2.3, 4.5][5, "Hello", "there", 9.8][5, "Hello", "there", 9.8][][]Use len() to get the length of a listUse len() to get the length of a list>>> names = [“Ben", “Chen", “Yaqin"]>>> names = [“Ben", “Chen", “Yaqin"]>>> len(names)>>> len(names)33
Use [ ] to index items in the listUse [ ] to index items in the list>>> names[0]>>> names[0]‘‘Ben'Ben'>>> names[1]>>> names[1]‘‘Chen'Chen'>>> names[2]>>> names[2]‘‘Yaqin'Yaqin'>>> names[3]>>> names[3]Traceback (most recent call last):Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <module>IndexError: list index out of rangeIndexError: list index out of range>>> names[-1]>>> names[-1]‘‘Yaqin'Yaqin'>>> names[-2]>>> names[-2]‘‘Chen'Chen'>>> names[-3]>>> names[-3]‘‘Ben'Ben'
[0] is the first item.[1] is the second item...
Out of range valuesraise an exception
Negative valuesgo backwards fromthe last element.
Strings share many features with listsStrings share many features with lists
>>> smiles = "C(=N)(N)N.C(=O)(O)O">>> smiles = "C(=N)(N)N.C(=O)(O)O">>> smiles[0]>>> smiles[0]'C''C'>>> smiles[1]>>> smiles[1]'(''('>>> smiles[-1]>>> smiles[-1]'O''O'>>> smiles[1:5]>>> smiles[1:5]'(=N)''(=N)'>>> smiles[10:-4]>>> smiles[10:-4]'C(=O)''C(=O)'
Use “slice” notation toget a substring
String Methods: find, splitString Methods: find, split
smiles = "C(=N)(N)N.C(=O)(O)O"smiles = "C(=N)(N)N.C(=O)(O)O">>> smiles.find("(O)")>>> smiles.find("(O)")1515>>> smiles.find(".")>>> smiles.find(".")99>>> smiles.find(".", 10)>>> smiles.find(".", 10)-1-1>>> smiles.split(".")>>> smiles.split(".")['C(=N)(N)N', 'C(=O)(O)O']['C(=N)(N)N', 'C(=O)(O)O']>>>>>>
Use “find” to find thestart of a substring.
Start looking at position 10.
Find returns -1 if it couldn’tfind a match.
Split the string into partswith “.” as the delimiter
String operators: in, not inString operators: in, not in
if "Br" in “Brother”:if "Br" in “Brother”:
print "contains brother“print "contains brother“
email_address = “clin”email_address = “clin”
if "@" not in email_address:if "@" not in email_address:
email_address += "@brandeis.edu“email_address += "@brandeis.edu“
String Method: “strip”, “rstrip”, “lstrip” are ways toString Method: “strip”, “rstrip”, “lstrip” are ways toremove whitespace or selected charactersremove whitespace or selected characters
>>> line = " # This is a comment line \n">>> line = " # This is a comment line \n">>> line.strip()>>> line.strip()'# This is a comment line''# This is a comment line'>>> line.rstrip()>>> line.rstrip()' # This is a comment line'' # This is a comment line'>>> line.rstrip("\n")>>> line.rstrip("\n")' # This is a comment line '' # This is a comment line '>>>>>>
More String methodsMore String methods
email.startswith(“c") endswith(“u”)email.startswith(“c") endswith(“u”)True/FalseTrue/False
>>> "%[email protected]" % "clin">>> "%[email protected]" % "clin"'[email protected]''[email protected]'
>>> names = [“Ben", “Chen", “Yaqin"]>>> names = [“Ben", “Chen", “Yaqin"]>>> ", ".join(names)>>> ", ".join(names)‘‘Ben, Chen, Yaqin‘Ben, Chen, Yaqin‘
>>> “chen".upper()>>> “chen".upper()‘‘CHEN'CHEN'
Unexpected things about stringsUnexpected things about strings
>>> s = "andrew">>> s = "andrew">>> s[0] = "A">>> s[0] = "A"Traceback (most recent call last):Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item TypeError: 'str' object does not support item
assignmentassignment>>> s = "A" + s[1:]>>> s = "A" + s[1:]>>> s>>> s'Andrew‘'Andrew‘
Strings are read only
““\” is for special characters\” is for special characters
\n -> newline\n -> newline
\t -> tab\t -> tab
\\ -> backslash\\ -> backslash
......
But Windows uses backslash for directories!filename = "M:\nickel_project\reactive.smi" # DANGER!
filename = "M:\\nickel_project\\reactive.smi" # Better!
filename = "M:/nickel_project/reactive.smi" # Usually works
Lists are mutable - some useful Lists are mutable - some useful methodsmethods
>>> ids = ["9pti", "2plv", "1crn"]>>> ids = ["9pti", "2plv", "1crn"]>>> ids.append("1alm")>>> ids.append("1alm")>>> ids>>> ids['9pti', '2plv', '1crn', '1alm']['9pti', '2plv', '1crn', '1alm']>>>ids.extend(L)>>>ids.extend(L) Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.>>> del ids[0]>>> del ids[0]>>> ids>>> ids['2plv', '1crn', '1alm']['2plv', '1crn', '1alm']>>> ids.sort()>>> ids.sort()>>> ids>>> ids['1alm', '1crn', '2plv']['1alm', '1crn', '2plv']>>> ids.reverse()>>> ids.reverse()>>> ids>>> ids['2plv', '1crn', '1alm']['2plv', '1crn', '1alm']>>> ids.insert(0, "9pti")>>> ids.insert(0, "9pti")>>> ids>>> ids['9pti', '2plv', '1crn', '1alm']['9pti', '2plv', '1crn', '1alm']
append an element
remove an element
sort by default order
reverse the elements in a list
insert an element at somespecified position.(Slower than .append())
Tuples: Tuples: sort of an immutable list
>>> yellow = (255, 255, 0) # r, g, b>>> yellow = (255, 255, 0) # r, g, b>>> one = (1,)>>> one = (1,)>>> yellow[0]>>> yellow[0]>>> yellow[1:]>>> yellow[1:](255, 0)(255, 0)>>> yellow[0] = 0>>> yellow[0] = 0Traceback (most recent call last):Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignmentTypeError: 'tuple' object does not support item assignment
Very common in string interpolation:>>> "%s lives in %s at latitude %.1f" % ("Andrew", "Sweden", 57.7056)'Andrew lives in Sweden at latitude 57.7'
zipping lists togetherzipping lists together
>>> names>>> names['ben', 'chen', 'yaqin']['ben', 'chen', 'yaqin']
>>> gender =>>> gender = [0, 0, 1] [0, 0, 1]
>>> zip(names, gender)>>> zip(names, gender)[('ben', 0), ('chen', 0), ('yaqin', 1)][('ben', 0), ('chen', 0), ('yaqin', 1)]
High Level Data TypesHigh Level Data Types
Dictionaries hold key-value pairsDictionaries hold key-value pairsOften called maps or hashes. Implemented Often called maps or hashes. Implemented
using hash-tablesusing hash-tablesKeys may be any immutable object, values Keys may be any immutable object, values
may be any objectmay be any objectDeclared using bracesDeclared using braces
>>> d={}>>> d={}>>> d[0] = "Hi there">>> d[0] = "Hi there">>> d["foo"] = 1>>> d["foo"] = 1
DictionariesDictionaries Dictionaries are lookup tables. They map from a “key” to a “value”.
symbol_to_name = {"H": "hydrogen","He": "helium","Li": "lithium","C": "carbon","O": "oxygen","N": "nitrogen"
} Duplicate keys are not allowed Duplicate values are just fine
Keys can be any immutable valueKeys can be any immutable valuenumbers, strings, tuples, frozensetnumbers, strings, tuples, frozenset, ,
not list, dictionary, set, ...not list, dictionary, set, ...atomic_number_to_name = {atomic_number_to_name = {1: "hydrogen"1: "hydrogen"6: "carbon",6: "carbon",7: "nitrogen"7: "nitrogen"8: "oxygen",8: "oxygen",}}nobel_prize_winners = {nobel_prize_winners = {(1979, "physics"): ["Glashow", "Salam", "Weinberg"],(1979, "physics"): ["Glashow", "Salam", "Weinberg"],(1962, "chemistry"): ["Hodgkin"],(1962, "chemistry"): ["Hodgkin"],(1984, "biology"): ["McClintock"],(1984, "biology"): ["McClintock"],}}
A set is an unordered collection with no duplicate elements.
DictionaryDictionary
>>> symbol_to_name["C"]>>> symbol_to_name["C"]'carbon''carbon'>>> "O" in symbol_to_name, "U" in symbol_to_name>>> "O" in symbol_to_name, "U" in symbol_to_name(True, False)(True, False)>>> "oxygen" in symbol_to_name>>> "oxygen" in symbol_to_nameFalseFalse>>> symbol_to_name["P"]>>> symbol_to_name["P"]Traceback (most recent call last):Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <module>KeyError: 'P'KeyError: 'P'>>> symbol_to_name.get("P", "unknown")>>> symbol_to_name.get("P", "unknown")'unknown''unknown'>>> symbol_to_name.get("C", "unknown")>>> symbol_to_name.get("C", "unknown")'carbon''carbon'
Get the value for a given key
Test if the key exists(“in” only checks the keys,not the values.)
[] lookup failures raise an exception.Use “.get()” if you wantto return a default value.
Some useful dictionary methodsSome useful dictionary methods
>>> symbol_to_name.keys()>>> symbol_to_name.keys()['C', 'H', 'O', 'N', 'Li', 'He']['C', 'H', 'O', 'N', 'Li', 'He']
>>> symbol_to_name.values()>>> symbol_to_name.values()['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium']['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium']
>>> symbol_to_name.update( {"P": "phosphorous", "S": "sulfur"} )>>> symbol_to_name.update( {"P": "phosphorous", "S": "sulfur"} )>>> symbol_to_name.items()>>> symbol_to_name.items()[('C', 'carbon'), ('H', 'hydrogen'), ('O', 'oxygen'), ('N', 'nitrogen'), ('P', [('C', 'carbon'), ('H', 'hydrogen'), ('O', 'oxygen'), ('N', 'nitrogen'), ('P',
'phosphorous'), ('S', 'sulfur'), ('Li', 'lithium'), ('He', 'helium')]'phosphorous'), ('S', 'sulfur'), ('Li', 'lithium'), ('He', 'helium')]
>>> del symbol_to_name['C']>>> del symbol_to_name['C']>>> symbol_to_name>>> symbol_to_name{'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': 'helium'}{'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': 'helium'}
BackgroundBackgroundData Types/StructureData Types/Structure
list, string, tuple, dictionarylist, string, tuple, dictionaryControl flowControl flowFile I/OFile I/OModulesModules
Control FlowControl Flow
Things that are FalseThings that are False The boolean value False The numbers 0 (integer), 0.0 (float) and 0j (complex). The empty string "". The empty list [], empty dictionary {} and empty set set().
Things that are TrueThings that are True The boolean value TrueThe boolean value True All non-zero numbers.All non-zero numbers. Any string containing at least one character.Any string containing at least one character. A non-empty data structure.A non-empty data structure.
IfIf
>>> smiles = "BrC1=CC=C(C=C1)NN.Cl">>> smiles = "BrC1=CC=C(C=C1)NN.Cl">>> bool(smiles)>>> bool(smiles)TrueTrue>>> not bool(smiles)>>> not bool(smiles)FalseFalse>>> if not smiles>>> if not smiles::... print "The SMILES string is empty"... print "The SMILES string is empty"...... The “else” case is always optional
Use “elif” to chain subsequent testsUse “elif” to chain subsequent tests
>>> mode = "absolute">>> mode = "absolute">>> if mode == "canonical":>>> if mode == "canonical":... ... smiles = "canonical"smiles = "canonical"... elif mode == "isomeric":... elif mode == "isomeric":... ... smiles = "isomeric”smiles = "isomeric”... ... elif mode == "absolute": elif mode == "absolute":... ... smiles = "absolute"smiles = "absolute"... else:... else:... ... raise TypeError("unknown mode")raise TypeError("unknown mode")......>>> smiles>>> smiles' absolute '' absolute '>>>>>>
“raise” is the Python way to raise exceptions
Boolean logicBoolean logic
Python expressions can have “and”s and Python expressions can have “and”s and “or”s:“or”s:
if (ben if (ben <=<= 5 and chen 5 and chen >=>= 10 or 10 or
chen chen ==== 500 and ben 500 and ben !=!= 5): 5):
print “Ben and Chen“print “Ben and Chen“
Range TestRange Test
if (3 if (3 <= Time <=<= Time <= 5): 5):
print “Office Hour"print “Office Hour"
LoopingLooping
The The forfor statement loops over sequences statement loops over sequences>>> for ch in "Hello":>>> for ch in "Hello":... ... print chprint ch... ... HHeelllloo>>> >>>
ForFor
>>> names = [“Ben", “Chen", “Yaqin"]>>> names = [“Ben", “Chen", “Yaqin"]
>>> for name in names:>>> for name in names:
... ... print smilesprint smiles
......
BenBen
ChenChen
YaqinYaqin
Tuple assignment in for loopsTuple assignment in for loops
data = [ ("C20H20O3", 308.371),data = [ ("C20H20O3", 308.371),("C22H20O2", 316.393),("C22H20O2", 316.393),("C24H40N4O2", 416.6),("C24H40N4O2", 416.6),("C14H25N5O3", 311.38),("C14H25N5O3", 311.38),("C15H20O2", 232.3181)]("C15H20O2", 232.3181)]
for for (formula, mw)(formula, mw) in data: in data:print "The molecular weight of %s is %s" % (formula, mw)print "The molecular weight of %s is %s" % (formula, mw)
The molecular weight of C20H20O3 is 308.371The molecular weight of C20H20O3 is 308.371The molecular weight of C22H20O2 is 316.393The molecular weight of C22H20O2 is 316.393The molecular weight of C24H40N4O2 is 416.6The molecular weight of C24H40N4O2 is 416.6The molecular weight of C14H25N5O3 is 311.38The molecular weight of C14H25N5O3 is 311.38The molecular weight of C15H20O2 is 232.3181The molecular weight of C15H20O2 is 232.3181
Break, continueBreak, continue
>>> for value in [3, 1, 4, 1, 5, 9, 2]:>>> for value in [3, 1, 4, 1, 5, 9, 2]:... ... print "Checking", value print "Checking", value... ... if value > 8: if value > 8:... ... print "Exiting for loop"print "Exiting for loop"... ... breakbreak... ... elif value < 3: elif value < 3:... ... print "Ignoring"print "Ignoring"... ... continuecontinue... ... print "The square is", value**2 print "The square is", value**2......
Use “break” to stopUse “break” to stopthe for loopthe for loop
Use “continue” to stopUse “continue” to stopprocessing the current itemprocessing the current item
Checking 3Checking 3The square is 9The square is 9Checking 1Checking 1IgnoringIgnoringChecking 4Checking 4The square is 16The square is 16Checking 1Checking 1IgnoringIgnoringChecking 5Checking 5The square is 25The square is 25Checking 9Checking 9Exiting for loopExiting for loop>>>>>>
Range()Range() ““range” creates a list of numbers in a specified rangerange” creates a list of numbers in a specified range range([start,] stop[, step]) -> list of integersrange([start,] stop[, step]) -> list of integers When step is given, it specifies the increment (or decrement).When step is given, it specifies the increment (or decrement).>>> range(5)>>> range(5)[0, 1, 2, 3, 4][0, 1, 2, 3, 4]>>> range(5, 10)>>> range(5, 10)[5, 6, 7, 8, 9][5, 6, 7, 8, 9]>>> range(0, 10, 2)>>> range(0, 10, 2)[0, 2, 4, 6, 8][0, 2, 4, 6, 8]
How to get every second element in a list?for i in range(0, len(data), 2):
print data[i]
FunctionsFunctions
Functions are defined with the Functions are defined with the defdef statement:statement:
>>> def foo(bar):>>> def foo(bar):... return bar... return bar>>> >>>
This defines a trivial function named This defines a trivial function named foofoo that takes a single parameter that takes a single parameter barbar
FunctionsFunctions
A function definition simply places a A function definition simply places a function object in the namespacefunction object in the namespace
>>> foo>>> foo<function foo at fac680><function foo at fac680>
>>>>>> And the function object can obviously be And the function object can obviously be
called:called: >>> foo(3)>>> foo(3)33>>>>>>
Functions, ProceduresFunctions, Procedures
def def namename((arg1arg1, , arg2arg2, ...):, ...):
""""""documentationdocumentation""""""# optional doc string# optional doc string
statementsstatements
returnreturn # from procedure# from procedure
return return expressionexpression # from function# from function
Example FunctionExample Function
def gcd(a, b):def gcd(a, b):
"greatest common divisor""greatest common divisor"
while a != 0:while a != 0:
a, b = b%a, a # parallel assignmenta, b = b%a, a # parallel assignment
return breturn b
>>> gcd.__doc__>>> gcd.__doc__
'greatest common divisor''greatest common divisor'
>>> gcd(12, 20)>>> gcd(12, 20)
44
ClassesClasses
Classes are defined using the Classes are defined using the classclass statementstatement
>>> class Foo:>>> class Foo:... def __init__(self):... def __init__(self):... self.member = 1... self.member = 1... def GetMember(self):... def GetMember(self):... return self.member... return self.member... ... >>> >>>
ClassesClasses
A few things are worth pointing out in the A few things are worth pointing out in the previous example:previous example:The constructor has a special name The constructor has a special name __init____init__, while a destructor (not shown) uses , while a destructor (not shown) uses __del____del__
The The selfself parameter is the instance (ie, the parameter is the instance (ie, the thisthis in C++). In Python, the self parameter is in C++). In Python, the self parameter is explicit (c.f. C++, where it is implicit) explicit (c.f. C++, where it is implicit)
The name The name selfself is not required - simply a is not required - simply a conventionconvention
ClassesClasses
Like functions, a class statement simply Like functions, a class statement simply adds a class object to the namespaceadds a class object to the namespace
>>> Foo>>> Foo<class __main__.Foo at 1000960><class __main__.Foo at 1000960>>>>>>>
Classes are instantiated using call syntaxClasses are instantiated using call syntax >>> f=Foo()>>> f=Foo()>>> f.GetMember()>>> f.GetMember()11
Example classExample class
class Stack:class Stack:
"A well-known data structure…""A well-known data structure…"
def __init__(self):def __init__(self): # constructor# constructor
self.items = []self.items = []
def push(self, x):def push(self, x):
self.items.append(x)self.items.append(x) # the sky is the limit# the sky is the limit
def pop(self):def pop(self):
x = self.items[-1]x = self.items[-1] # what happens if it’s empty?# what happens if it’s empty?
del self.items[-1]del self.items[-1]
return xreturn x
def empty(self):def empty(self):
return len(self.items) == 0return len(self.items) == 0 # Boolean result# Boolean result
Using classesUsing classes To create an instance, simply call the class object:To create an instance, simply call the class object:
x = Stack()x = Stack() # no 'new' operator!# no 'new' operator!
To use methods of the instance, call using dot notation:To use methods of the instance, call using dot notation:x.empty()x.empty() # -> 1# -> 1
x.push(1)x.push(1) # [1]# [1]
x.empty()x.empty() # -> 0# -> 0
x.push("hello")x.push("hello") # [1, "hello"]# [1, "hello"]
x.pop()x.pop() # -> "hello"# -> "hello" # [1]# [1]
To inspect instance variables, use dot notation:To inspect instance variables, use dot notation:x.itemsx.items # -> [1]# -> [1]
SubclassingSubclassing
class FancyStack(Stack):class FancyStack(Stack):
"stack with added ability to inspect inferior stack items""stack with added ability to inspect inferior stack items"
def peek(self, n):def peek(self, n):
"peek(0) returns top; peek(-1) returns item below that; etc.""peek(0) returns top; peek(-1) returns item below that; etc."
size = len(self.items)size = len(self.items)
assert 0 <= n < sizeassert 0 <= n < size # test precondition# test precondition
return self.items[size-1-n]return self.items[size-1-n]
Subclassing (2)Subclassing (2)
class LimitedStack(FancyStack):class LimitedStack(FancyStack):
"fancy stack with limit on stack size""fancy stack with limit on stack size"
def __init__(self, limit):def __init__(self, limit):
self.limit = limitself.limit = limit
FancyStack.__init__(self)FancyStack.__init__(self) # base class constructor# base class constructor
def push(self, x):def push(self, x):
assert len(self.items) < self.limitassert len(self.items) < self.limit
FancyStack.push(self, x)FancyStack.push(self, x) # "super" method call# "super" method call
Class & instance variablesClass & instance variables
class Connection:class Connection:
verbose = 0verbose = 0 # class variable# class variable
def __init__(self, host):def __init__(self, host):
self.host = hostself.host = host # instance variable# instance variable
def debug(self, v):def debug(self, v):
self.verbose = vself.verbose = v # make instance variable!# make instance variable!
def connect(self):def connect(self):
if if self.verboseself.verbose:: # class or instance variable?# class or instance variable?
print "connecting to", self.hostprint "connecting to", self.host
Instance variable rulesInstance variable rules
On use via instance (self.x), search order:On use via instance (self.x), search order: (1) instance, (2) class, (3) base classes(1) instance, (2) class, (3) base classes this also works for method lookupthis also works for method lookup
On assigment via instance (self.x = ...):On assigment via instance (self.x = ...):always makes an instance variablealways makes an instance variable
Class variables "default" for instance variablesClass variables "default" for instance variables But...!But...!
mutable mutable classclass variable: one copy variable: one copy sharedshared by all by allmutable mutable instanceinstance variable: each instance its own variable: each instance its own
ExceptionsExceptions
Python uses exceptions for errorsPython uses exceptions for errorstrytry / / exceptexcept block can handle exceptions block can handle exceptions
>>> try:>>> try:... 1/0... 1/0... except ZeroDivisionError:... except ZeroDivisionError:... print "Eeek"... print "Eeek"... ... EeekEeek>>> >>>
ExceptionsExceptions
trytry / / finallyfinally block can guarantee block can guarantee execute of code even in the face of execute of code even in the face of exceptionsexceptions
>>> try:>>> try:... 1/0... 1/0... finally:... finally:... print "Doing this anyway"... print "Doing this anyway"... ... Doing this anywayDoing this anywayTraceback (innermost last): File "<interactive input>", line 2, in ?Traceback (innermost last): File "<interactive input>", line 2, in ?ZeroDivisionError: integer division or moduloZeroDivisionError: integer division or modulo>>>>>>
More on exceptionsMore on exceptions User-defined exceptionsUser-defined exceptions
subclass Exception or any other standard exceptionsubclass Exception or any other standard exception Old Python: exceptions can be stringsOld Python: exceptions can be strings
WATCH OUT: compared by object identity, not ==WATCH OUT: compared by object identity, not == Last caught exception info:Last caught exception info:
sys.exc_info() == (exc_type, exc_value, exc_traceback)sys.exc_info() == (exc_type, exc_value, exc_traceback)
Last uncaught exception (traceback printed):Last uncaught exception (traceback printed): sys.last_type, sys.last_value, sys.last_tracebacksys.last_type, sys.last_value, sys.last_traceback
Printing exceptions: traceback modulePrinting exceptions: traceback module
BackgroundBackgroundData Types/StructureData Types/StructureControl flowControl flowFile I/OFile I/OModulesModules
A A filefile is a sequence of data that is stored is a sequence of data that is stored in secondary memory (disk drive).in secondary memory (disk drive).
Files can contain any data type, but the Files can contain any data type, but the easiest to work with are text.easiest to work with are text.
A file usually contains more than one line A file usually contains more than one line of text. of text.
Python uses the standard newline Python uses the standard newline character (\n) to mark line breaks.character (\n) to mark line breaks.
Files: Multi-line StringsFiles: Multi-line Strings
File ProcessingFile Processing
Reading a file into a word processorReading a file into a word processorFile openedFile openedContents read into RAMContents read into RAMFile closedFile closedChanges to the file are made to the copy Changes to the file are made to the copy
stored in memory, not on the diskstored in memory, not on the diskIt has to be flushedIt has to be flushed
File ObjectsFile Objects f = open(f = open(filenamefilename[, [, modemode[, [, buffersizebuffersize])])
mode can be "r", "w", "a" (like C stdio); default "r"mode can be "r", "w", "a" (like C stdio); default "r" append "b" for text translation modeappend "b" for text translation mode append "+" for read/write openappend "+" for read/write open buffersize: 0=unbuffered; 1=line-buffered; bufferedbuffersize: 0=unbuffered; 1=line-buffered; buffered
methods:methods: read([read([nbytesnbytes]), readline()]), readline(),, readlines() readlines() write(write(stringstring), writelines(), writelines(listlist)) seek(seek(pospos[, [, howhow]), tell()]), tell() flush(), close()flush(), close() fileno()fileno()
Reading filesReading files
>>> f = open(“names.txt")>>> f = open(“names.txt")
>>> f.readline()>>> f.readline()
'Yaqin\n''Yaqin\n'
File ProcessingFile Processing
readline can be used to read the next line readline can be used to read the next line from a file, including the trailing newline from a file, including the trailing newline charactercharacter
infile = open(someFile, infile = open(someFile, ""rr""))for i in range(5):for i in range(5):
line = infile.readline()line = infile.readline()print line[:-1]print line[:-1]
This reads the first 5 lines of a fileThis reads the first 5 lines of a fileSlicing is used to strip out the newline Slicing is used to strip out the newline
characters at the ends of the linescharacters at the ends of the lines
File ProcessingFile Processing
Another way to loop through the contents Another way to loop through the contents of a file is to read it in with readlines and of a file is to read it in with readlines and then loop through the resulting list.then loop through the resulting list.
infile = open(someFile, infile = open(someFile, ""rr""))for line in infile.readlines():for line in infile.readlines():
# Line processing here# Line processing hereinfile.close()infile.close()
File ProcessingFile Processing
Python treats the file itself as a sequence Python treats the file itself as a sequence of lines!of lines!
Infile = open(someFile, Infile = open(someFile, ""rr""))for line in infile:for line in infile:
# process the line here# process the line hereinfile.close()infile.close()
Quick WayQuick Way
>>> lst= [ x for x in open("text.txt","r").readlines() ]>>> lst= [ x for x in open("text.txt","r").readlines() ]>>> lst>>> lst['Chen Lin\n', '[email protected]\n', 'Volen 110\n', 'Office ['Chen Lin\n', '[email protected]\n', 'Volen 110\n', 'Office
Hour: Thurs. 3-5\n', '\n', 'Yaqin Yang\n', Hour: Thurs. 3-5\n', '\n', 'Yaqin Yang\n', '[email protected]\n', 'Volen 110\n', 'Offiche Hour: '[email protected]\n', 'Volen 110\n', 'Offiche Hour: Tues. 3-5\n']Tues. 3-5\n']
Ignore the header?Ignore the header?for (i,line) in enumerate(open(‘text.txt’,"r").readlines()):for (i,line) in enumerate(open(‘text.txt’,"r").readlines()): if i == 0: continueif i == 0: continue print lineprint line
Using dictionaries to count Using dictionaries to count occurrencesoccurrences
>>> for line in open('names.txt'):>>> for line in open('names.txt'):... ... name = line.strip()name = line.strip()... ... name_count[name] = name_count.get(name,0)+ name_count[name] = name_count.get(name,0)+
11... ... >>> for (name, count) in name_count.items():>>> for (name, count) in name_count.items():... ... print name, countprint name, count... ... Chen 3Chen 3Ben 3Ben 3Yaqin 3Yaqin 3
File ProcessingFile Processing
Opening a file for writing prepares the file Opening a file for writing prepares the file to receive datato receive data
If you open an existing file for writing, you If you open an existing file for writing, you wipe out the filewipe out the file’’s contents. If the named s contents. If the named file does not exist, a new one is created.file does not exist, a new one is created.
Outfile = open(Outfile = open(""mydata.outmydata.out"", , ""ww""))print(<expressions>, file=Outfile)print(<expressions>, file=Outfile)
File OutputFile Output
input_file = open(“in.txt")input_file = open(“in.txt")
output_file = open(“out.txt", "w")output_file = open(“out.txt", "w")
for line in input_file:for line in input_file:
output_file.write(line)output_file.write(line)“w” = “write mode”“a” = “append mode”“wb” = “write in binary”“r” = “read mode” (default)“rb” = “read in binary”“U” = “read files with Unixor Windows line endings”
BackgroundBackgroundData Types/StructureData Types/StructureControl flowControl flowFile I/OFile I/OModulesModules
ModulesModules
When a Python program starts it only has access to a basic functions and classes.
(“int”, “dict”, “len”, “sum”, “range”, ...) “Modules” contain additional functionality. Modules can be implemented either in Modules can be implemented either in
Python, or in C/C++Python, or in C/C++Use “import” to tell Python to load a module.
>>> import math
import the math moduleimport the math module>>> import math>>> import math>>> math.pi>>> math.pi3.14159265358979313.1415926535897931>>> math.cos(0)>>> math.cos(0)1.01.0>>> math.cos(math.pi)>>> math.cos(math.pi)-1.0-1.0>>> dir(math)>>> dir(math)['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh',['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh','asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos','asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos','cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod','cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod','frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10','frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10','log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan','log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan','tanh', 'trunc']'tanh', 'trunc']>>> help(math)>>> help(math)>>> help(math.cos)>>> help(math.cos)
““import” and “from ... import ...”import” and “from ... import ...”
>>> import math>>> import math
math.cosmath.cos
>>> from math import cos, pi
cos
>>> from math import *
Standard LibraryStandard Library
Python comes standard with a set of Python comes standard with a set of modules, known as the “standard library”modules, known as the “standard library”
Rich and diverse functionality available from Rich and diverse functionality available from the standard librarythe standard libraryAll common internet protocols, sockets, CGI, All common internet protocols, sockets, CGI,
OS services, GUI services (via Tcl/Tk), OS services, GUI services (via Tcl/Tk), database, Berkeley style databases, calendar, database, Berkeley style databases, calendar, Python parser, file globbing/searching, Python parser, file globbing/searching, debugger, profiler, threading and debugger, profiler, threading and synchronisation, persistency, etcsynchronisation, persistency, etc
External libraryExternal library
Many modules are available externally Many modules are available externally covering almost every piece of covering almost every piece of functionality you could ever desirefunctionality you could ever desire Imaging, numerical analysis, OS specific Imaging, numerical analysis, OS specific
functionality, SQL databases, Fortran functionality, SQL databases, Fortran interfaces, XML, Corba, COM, Win32 API, etc interfaces, XML, Corba, COM, Win32 API, etc
For More Information?
http://python.org/ - documentation, tutorials, beginners guide, core
distribution, ...Books include: Learning Python by Mark Lutz Python Essential Reference by David Beazley Python Cookbook, ed. by Martelli, Ravenscroft and
Ascher (online at
http://code.activestate.com/recipes/langs/python/) http://wiki.python.org/moin/PythonBooks
Python VideosPython Videos
http://showmedo.com/videotutorials/python“5 Minute Overview (What Does Python
Look Like?)”“Introducing the PyDev IDE for Eclipse”“Linear Algebra with Numpy”And many more