ComprehensiveGuidetoPythonProgramming-StudyGuide
ComprehensiveGuidetoPythonProgramming-StudyGuide
Exceptions
Exceptions: Events disrupting normal program flow.
Common Exceptions:
NameError: Accessing undeclared variable.
ZeroDivisionError: Division by zero.
SyntaxError: Invalid syntax.
IndexError: Out-of-range index.
KeyError: Non-existent dictionary key.
IOError: Input/output error.
Detecting and Handling Exceptions:
try, except, else, finally blocks.
Multiple except clauses.
Raising Exceptions: raise Exception(message).
Assertions: assert condition, message (debugging tool).
Standard Exceptions:
BaseException, Exception, StandardError, etc.
Creating Exceptions:
Create a class that inherits from Exception.
Exceptions and the sys Module:
sys.exc_info(): Returns a tuple containing exception class, instance, and traceback object.
Modules
Modules: Files containing Python code.
Modules and Files: One file equals one module.
Namespaces: Mapping of names to objects.
Built-ins, Global, Local.
Name Lookup: Local -> Global -> Built-ins.
Importing Modules:
import module1, module2, ....
Importing Module Attributes:
from module import name1, name2, ....
from module import * (imports all names).
Module Built-in Functions:
__import__(), globals(), locals(), reload().
Packages: Hierarchical directory structure containing modules.
__init__.py file indicates a package.
Import subpackages using import package.module.
from package.module import *.
Other Features of Modules:
sys.modules: Dictionary of loaded modules.
Preventing attribute import using underscore prefix (_).
Multithreaded Programming
Thread: Separate path of execution within a program.
Process: Program in execution with its own address space.
Threads are light-weight processes.
Uses of threads: Server-side programs, games, animations.
Global Interpreter Lock (GIL): Ensures only one thread runs at a time.
Exiting Threads: By completing execution, calling thread.exit(), or raising an exception.
Thread Module:
Functions: allocate_lock(), start_new_thread(), exit().
Lock Object Methods: locked(), acquire(), release().
Threading Module:
Thread class and synchronization mechanisms.
Objects: Thread, Lock, RLock, Condition, Event, Semaphore.
Creating Threads:
Without a class: t = Thread(target=function, args=(arg1, arg2)).
Creating a subclass to Thread class.
Start thread with t.start().
Queue Module: Inter-thread communication.
Queue(size): Creates a queue.
qsize(), empty(), full(), put(item), get().
Producer-Consumer Problem: Threads sharing data via a queue.
Tk Widgets:
Button: Performs a task on click. Example: b = Button(master, text='Exit',
command=top.quit).
Label: Displays a message. Example: label = Label(top, text='Welcome!').
Tk Interface Extensions (Tix):
Extends the capabilities of TCL/Tk.
Python Mega Widgets (PMW):
Extends Tkinter with high-level compound widgets.
wxWidgets and wxPython:
wxWidgets: Cross-platform toolkit.
wxPython: Python binding for wxWidgets.
GTK+ and PyGTK:
GTK+: GIMP Toolkit for creating GUIs.
PyGTK: Python wrapper for GTK+.
Related Modules:
Tkinter, Tix, EasyGUI, PMW, wxPython, PyGTK, PyQt.
Web Programming
Web Surfing: Client/Server Computing
Clients (browsers) request data from servers.
HTTP protocol.
URL (Uniform Resource Locator): Specifies the address of resources.
prot_sch://net_loc/path;params?query#frag.
prot_sch: Protocol (e.g., http, ftp).
net_loc: Network location.
path: File path.
query: Key-value pairs.
frag: Fragment identifier.
urlparse Module:
urlparse(): Parses URL into components.
urlunparse(): Merges components into a URL.
urljoin(): Joins base URL with a new URL.
urllib Module:
urlopen(): Opens a web connection.
Methods: info(), read(), geturl(), close(), readline(), readlines(), fileno().
urlretrieve(): Downloads a URL to a local file.
quote(): Encodes URL data.
unquote(): Decodes URL data.
urlencode(): Encodes a dictionary of key-value pairs.
urllib2 Module:
Handles complex URL opening, such as websites with basic authentication.
Advanced Web Clients:
Crawlers, web page caching.
CGI (Common Gateway Interface):
Interface for writing client-server applications.
Client requests, server executes a program, and returns the output.
CGI Architecture
CGI Environment Variables
CGI Redirection
Forms and Results Pages:
Generating HTML forms to collect data from users.
Processing form data and generating results pages.
Advanced CGI:
Multipart form submission for file uploading:
<FORM enctype="multipart/form-data"...>.
<INPUT type="file" name="...">.
Multi-valued fields: handling multiple values from checkboxes.
Cookies:
Small objects of information stored on the web browser system.
The server can connect requests from a particular client to previous and subsequent
requests, the server can also provide a customized interface to the client based on his/her
preferences. A cookie consists of a name and a value. It is created by some software
system on the server and included as a part of the HTTP header.
Web Servers:
Delivers content to end-users over the Internet.
Uses HTTP.
Handlers: SimpleHTTPRequestHandler, BaseHTTPRequestHandler,
CGIHTTPRequestHandler.
Insert Operation
INSERT INTO statement:
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s,
%s)".
val = ("John", 110, 25000.00, 201, "Newyork").
cur.execute(sql, val).
myconn.commit() (to save changes).
Insert Multiple Rows:
val = [("John", ...), ("David", ...), ("Nick", ...)].
cur.executemany(sql, val).
Row ID: cur.lastrowid (gets the ID of the last inserted row).
Read Operation
SELECT statement:
cur.execute("select * from Employee").
result = cur.fetchall() (fetches all rows).
fetchone(): Fetches only one row at a time.
Iterate through the result to get individual rows.