Professional Documents
Culture Documents
By
Guru. Y
Part III
Tutorial Overview
Part I
•Introduction
•Installing Python
•First steps
•Basic types: numbers, strings
•Container types: lists, dictionaries, Tuples
Part II
• Variables
•Control structures
•Functions
•Modules
Part III
•Exceptions
•Data Structures
•Files
•Standard library
Page 2
Part III – Exceptions
Catching Exceptions
def foo(x):
return 1/x
def bar(x):
try:
print foo(x)
except ZeroDivisionError, message:
print "Can’t divide by zero:", message
bar(0)
Page 3
Part III – Exceptions
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
The following link lists the built-in exceptions and their meanings
http://docs.python.org/lib/module-exceptions.html
Page 4
Part III – Exceptions
Raising Exceptions
Page 5
Part III – Exceptions
Page 6
Part III – Files
File Objects
f = open(filename [, mode])
mode can be "r", "w", "a"
default "r“
‘r+’ for read and write
‘rb’ , ‘wb’, ‘r+b’ opens the file in binary mode
methods:
read([nbytes]), readline(), readlines()
write(string), writelines(list)
seek(), tell()
close()
Page 7
Page 8
Part III – Libraries
Standard Library
Core:
os, sys, string, getopt, StringIO, struct, pickle, ...
Regular expressions:
re module
Internet:
socket, rfc822, httplib, htmllib, ftplib, smtplib, ...
Page 9
URLs
http://www.python.org
official site
http://starship.python.net
Community
http://www.python.org/psa/bookstore/
(alias for http://www.amk.ca/bookstore/)
Python Bookstore
Page 10
QUESTIONS
Page 11
End of PART-III