You are on page 1of 12

Python Basics

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

Some other 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

The raise statement allows the programmer to force a


specified exception to occur. For example
>>> try:
... raise NameError, 'Hi There‘
... except NameError:
... print 'An exception flew by!'
... Raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere

Page 5
Part III – Exceptions

Try-finally: Cleanup Actions


The try statement has another optional clause which is
intended to define clean-up actions that must be
executed under all circumstances. For example
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
A finally clause is executed whether or not an exception has
occurred in the try clause
The code in the finally clause is useful for releasing external
resources (such as files or network connections),
regardless of whether or not the use of the resource
was successful

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, ...

To know all the libraries in python please visit


http://docs.python.org/lib/lib.html

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

Imagination Action Joy


Page 12

You might also like