Python Basics By Guru Y Part III Tutorial
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 1
Part III – Exceptions Catching Exceptions def foo(x): return 1/x def bar(x): try: print foo(x) except Zero. Division. Error, message: print "Can’t divide by zero: ", message bar(0) 2
Part III – Exceptions Some other exceptions >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? Name. Error: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? Type. Error: 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 3
Part III – Exceptions Raising Exceptions The raise statement allows the programmer to force a specified exception to occur. For example >>> try: . . . raise Name. Error, 'Hi There‘. . . except Name. Error: . . . print 'An exception flew by!'. . . Raise. . . An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in ? Name. Error: Hi. There 4
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 5
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() 6
7
Part III – Libraries Standard Library Core: os, sys, string, getopt, String. IO, struct, pickle, . . . Regular expressions: re module Internet: socket, rfc 822, httplib, htmllib, ftplib, smtplib, . . . To know all the libraries in python please visit http: //docs. python. org/lib. html 8
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 9
QUESTIONS 10
End of PART-III 11 Imagination Action Joy
- Slides: 12