140 likes | 172 Views
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
E N D
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
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)
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
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
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
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()
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
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
End of PART-III Action Joy Imagination