Python Tutorial PDF
Python Tutorial PDF
Python Overview:
Python is a high-level, interpreted, interactive and object oriented-scripting language.
is is is is
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python's feature highlights include:
Easy-to-learn Easy-to-read Easy-to-maintain A broad standard library Interactive Mode Portable Extendable Databases GUI Programming Scalable
Getting Python:
The most up-to-date and current source code, binaries, documentation, news, etc. is available at the official website of Python: Python Official Website : http://www.python.org/ You can download the Python documentation from the following site. The documentation is available in HTML, PDF, and PostScript formats. Python Documentation Website : www.python.org/doc/
1|Page
root# python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more info. >>>
Type the following text to the right of the Python prompt and press the Enter key:
Hello, Python!
Python Identifiers:
A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Python. Here are following identifier naming convention for Python:
Class names start with an uppercase letter and all other identifiers with a lowercase letter. Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private. Starting an identifier with two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a languagedefined special name.
Reserved Words:
The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names. Keywords contain lowercase letters only. and assert break exec finally for not or pass
2|Page
if True: print "Answer" print "True" else: print "Answer" print "False"
Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:
3|Page
Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes can be used to span the string across multiple lines. For example, all the following are legal:
word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
Comments in Python:
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the physical line end are part of the comment, and the Python interpreter ignores them.
Hello, Python!
A comment may be on the same line after a statement or expression:
# # # #
This is a comment. This is a comment, too. This is a comment, too. I said that already.
Example:
if expression : suite elif expression : suite else : suite
counter = 100 miles = 1000.0 name = "John" print counter print miles print name
5|Page
Dictionary
Python Numbers:
Number objects are created when you assign a value to them. For example:
var1 = 1 var2 = 10
Python supports four different numerical types:
int (signed integers) long (long integers [can also be represented in octal and hexadecimal]) float (floating point real values) complex (complex numbers)
Here are some examples of numbers: int 10 100 -786 080 -0490 -0x260 0x69 51924361L -0x19323L 0122L 0xDEFABCECBDAECBFBAEl 535633629843L -052318172735L -4721885298529L long 0.0 15.20 -21.9 32.3+e18 -90. -32.54e100 70.2-E12 float complex 3.14j 45.j 9.322e-36j .876j -.6545+0J 3e+26J 4.53e-7j
Python Strings:
Strings in Python are identified as a contiguous set of characters in between quotation marks.
Example:
str = 'Hello World!' print print print print print print str str[0] str[2:5] str[2:] str * 2 str + "TEST" # # # # # # Prints Prints Prints Prints Prints Prints complete string first character of the string characters starting from 3rd to 6th string starting from 3rd character string two times concatenated string
6|Page
#!/usr/bin/python list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print print print print print print list # list[0] # list[1:3] # list[2:] # tinylist * 2 # list + tinylist Prints complete list Prints first element of the list Prints elements starting from 2nd to 4th Prints elements starting from 3rd element Prints list two times # Prints concatenated lists
Python Tuples:
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. Tuples can be thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 tinytuple = (123, 'john') print print print print print print tuple # tuple[0] # tuple[1:3] # tuple[2:] # tinytuple * 2 # tuple + tinytuple
Prints complete list Prints first element of the list Prints elements starting from 2nd to 4th Prints elements starting from 3rd element Prints list two times # Prints concatenated lists
Python Dictionary:
Python 's dictionaries are hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs.
tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values
7|Page
Multiplication - Multiplies values on either a * b will give 200 side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Exponent - Performs exponential (power) calculation on operators Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes b / a will give 2
b % a will give 0
**
//
==
(a == b) is not true.
!=
(a != b) is true.
<>
>
<
(a < b) is true.
>=
<=
(a <= b) is true.
8|Page
+=
c += a is equivalent to c = c + a
-=
c -= a is equivalent to c = c - a
*=
c *= a is equivalent to c = c * a
/=
c /= a is equivalent to c = c / a
%=
c %= a is equivalent to c = c % a
**=
c **= a is equivalent to c = c ** a
//=
c //= a is equivalent to c = c // a
&
9|Page
>>
and
(a and b) is true.
or
(a or b) is true.
not
in
not in
is
is not
10 | P a g e
* / % // +>> << & ^| <= < > >= <> == != = %= /= //= -= += |= &= >>= <<= *= **= is is not in not in note or and
The if statement:
The syntax of the if statement is:
if expression: statement(s)
if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
This will produce following result:
if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s)
12 | P a g e
fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print 'Current fruit :', fruits[index] print "Good bye!"
for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!"
13 | P a g e
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
#!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!"
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python:
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented.
14 | P a g e
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax:
def functionname( parameters ): "function_docstring" function_suite return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined.
Example:
Here is the simplest form of a Python function. This function takes a string as input parameter and prints it on standard screen.
def printme( str ): "This prints a passed string into this function" print str return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function, and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function:
#!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme("I'm first call to user defined function!"); printme("Again second call to the same function");
This would produce following result:
I'm first call to user defined function! Again second call to the same function
Python - Modules:
15 | P a g e
Example:
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, hello.py
Example:
To import the module hello.py, you need to put the following command at the top of the script:
#!/usr/bin/python # Import module hello import hello # Now you can call defined function that module as follows hellp.print_func("Zara")
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.
16 | P a g e
Syntax:
file object = open(file_name [, access_mode][, buffering])
Here is paramters detail:
file_name: The file_name argument is a string value that contains the name of the file that you want to access. access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r) buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. This is optional paramter.
Here is a list of the different modes of opening a file: Modes r Description Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. Opens a file for both reading and writing. The file pointer will be at the beginning of the file. Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file. Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
rb
r+
rb+
wb
w+
wb+
17 | P a g e
a+
ab+
fileObject.close();
File Positions:
The tell() method tells you the current position within the file in other words, the next read or write will occur at that many bytes from the beginning of the file: The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The fromargument specifies the reference position from where the bytes are to be moved. If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
Directories in Python:
The mkdir() Method:
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Syntax:
os.chdir("newdir")
Syntax:
19 | P a g e
Syntax:
os.rmdir('dirname')
Handling an exception:
If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:
try: Do you operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
Here are few important points above the above mentioned syntax:
A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection.
try: Do you operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block.
20 | P a g e
try: Do you operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block.
Standard Exceptions:
Here is a list standard Exceptions available in Python: Standard Exceptions
try: Do you operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
Argument of an Exception:
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows:
try: Do you operations here; ...................... except ExceptionType, Argument: You can print value of Argument here...
Raising an exceptions:
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement.
Syntax:
raise [Exception [, args [, traceback]]]
21 | P a g e
Creating Classes:
The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows:
The class has a documentation string which can be access via ClassName.__doc__. The class_suite consists of all the component statements, defining class members, data attributes, and functions.
"This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000)
Accessing attributes:
You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows:
emp1.displayEmployee()
22 | P a g e
__dict__ : Dictionary containing the class's namespace. __doc__ : Class documentation string, or None if undefined. __name__: Class name. __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode. __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
Class Inheritance:
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name: The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.
Syntax:
Derived classes are declared much like their parent class; however, a list of base classes to inherit from are given after the class name:
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
Overriding Methods:
You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.
23 | P a g e
Overloading Operators:
Suppose you've created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you. You could, however, define the __add__ method in your class to perform vector addition, and then the plus operator would behave as per expectation:
24 | P a g e
Data Hiding:
An object's attributes may or may not be visible outside the class definition. For these cases, you can name attributes with a double underscore prefix, and those attributes will not be directly visible to outsiders:
#!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.__secretCount
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. We would cover two important functions which would be used to handle regular expressions. But a small thing first: There are various characters which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions we would use Raw Strings as r'expression'.
25 | P a g e
The re.match function returns a match object on success, None on failure. We would use group(num) or groups() function of match object to get matched expression. Match Object Methods group(num=0) groups() Description This methods returns entire match (or specific subgroup num) This method return all matching subgroups in a tuple (empty if there weren't any)
The re.search function returns a match object on success, None on failure. We would use group(num) or groups() function of match object to get matched expression. Match Object Methods group(num=0) Description This methods returns entire match (or specific subgroup num)
26 | P a g e
Matching vs Searching:
Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).
Syntax:
sub(pattern, repl, string, max=0)
This method replace all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method would return modified string.
re.M
re.S re.U
re.X
Regular-expression patterns:
27 | P a g e
[...] [^...] re* re+ re{ n} re{ n,} re{ n, m} a| b (re) (?imx)
(?-imx)
28 | P a g e
\z \G \b
Regular-expression Examples:
Literal characters:
Example Description
29 | P a g e
Character classes:
Example [Pp]ython rub[ye] [aeiou] [0-9] [a-z] [A-Z] [a-zA-Z0-9] [^aeiou] [^0-9] Match "Python" or "python" Match "ruby" or "rube" Match any one lowercase vowel Match any digit; same as [0123456789] Match any lowercase ASCII letter Match any uppercase ASCII letter Match any of the above Match anything other than a lowercase vowel Match anything other than a digit Description
Repetition Cases:
30 | P a g e
Nongreedy repetition:
This matches the smallest number of repetitions: Example <.*> <.*?> Description Greedy repetition: matches "<python>perl>" Nongreedy: matches "<python>" in "<python>perl>"
Backreferences:
This matches a previously matched group again: Example ([Pp])ython&\1ails (['"])[^\1]*\1 Description Match python&rails or Python&Rails Single or double-quoted string. \1 matches whatever the 1st group
31 | P a g e
Alternatives:
Example python|perl rub(y|le)) Python(!+|\?) Match "python" or "perl" Match "ruby" or "ruble" "Python" followed by one or more ! or one ? Description
Anchors:
This need to specify match position Example ^Python Python$ \APython Python\Z \bPython\b \brub\B Description Match "Python" at the start of a string or internal line Match "Python" at the end of a string or line Match "Python" at the start of a string Match "Python" at the end of a string Match "Python" at a word boundary \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone Match "Python", if followed by an exclamation point Match "Python", if not followed by an exclamation point
Python(?=!) Python(?!!)
32 | P a g e
GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase
Importing the api module. Acquiring a connection with the database. Issuing SQL statements and stored procedures. Closing the connection
We would learn all the concepts using MySQL so let's talk about MySQLdb module only.
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0, and is built on top of the MySQL C API.
#!/usr/bin/python
33 | P a g e
Traceback (most recent call last): File "test.py", line 3, in <module> import MySQLdb ImportError: No module named MySQLdb
To install MySQLdb module, download it from MySQLdb Download page and proceed as follows:
$ $ $ $ $
gunzip MySQL-python-1.2.2.tar.gz tar -xvf MySQL-python-1.2.2.tar cd MySQL-python-1.2.2 python setup.py build python setup.py install
Note: Make sure you have root privilege to install above module.
Database Connection:
Before connecting to a MySQL database make sure followings:
You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB Python module MySQLdb is installed properly on your machine. You have gone through MySQL tutorial to understand MySQL Basics.
Example:
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print "Database version : %s " % data # disconnect from server
34 | P a g e
Example:
First let's create Database table EMPLOYEE:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Drop table if it already exist using execute() method. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql) # disconnect from server db.close()
INSERT Operation:
INSERT operation is required when you want to create your records into a database table.
Example:
35 | P a g e
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
Above example can be written as follows to create SQL queries dynamically:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
Example:
36 | P a g e
.................................. user_id = "test123" password = "password" con.execute('insert into Login values("%s", "%s")' % \ (user_id, password)) ..................................
READ Operation:
READ Operation on any databasse means to fetch some useful information from the database. Once our database connection is established, we are ready to make a query into this database. We can use either fetchone() method to fetch single record or fetchall method to fetech multiple values from a database table.
fetchone(): This method fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table. fetchall(): This method fetches all the rows in a result set. If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set. rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.
Example:
Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # Now print fetched result print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
37 | P a g e
Update Operation:
UPDATE Operation on any databasse means to update one or more records which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year.
Example:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to UPDATE required records sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
DELETE Operation:
DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20.
Example:
#!/usr/bin/python import MySQLdb # Open database connection
38 | P a g e
Performing Transactions:
Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:
Atomicity: Either a transaction completes or nothing happens at all. Consistency: A transaction must start in a consistent state and leave the system is a consistent state. Isolation: Intermediate results of a transaction are not visible outside the current transaction. Durability: Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example:
You already have seen how we have implemented transations. Here is again similar example:
# Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback()
COMMIT Operation:
Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted back. Here is a simple example to call commit method.
39 | P a g e
ROLLBACK Operation:
If you are not satisfied with one or more of the changes and you want to revert back those changes completely then use rollback method. Here is a simple example to call rollback metho.
db.rollback()
Disconnecting Database:
To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.
Handling Errors:
There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle. The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions. Exception Warning Error InterfaceError Description Used for non-fatal issues. Must subclass StandardError. Base class for errors. Must subclass StandardError. Used for errors in the database module, not the database itself. Must subclass Error. Used for errors in the database. Must subclass Error. Subclass of DatabaseError that refers to errors in the data. Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
40 | P a g e
InternalError
ProgrammingError
Your Python scripts should handle these errors but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.
host: This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com. This is optional argument. port: If you are providing host argument then you need to specifiy a port where SMTP server is listening. Usually this port would be 25. local_hostname: If your SMTP server is running on your local machine then you can specify just localhost as of this option.
An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters:
The sender - A string with the address of the sender. The receivers - A list of strings, one for each recipient. The message - A message as a string formatted as specified in the various RFCs.
Example:
Here is a simple way to send one email using Python script. Try it once:
41 | P a g e
smtplib.SMTP('mail.your-domain.com', 25)
Example:
Following is the example to send HTML content as an email. Try it once:
#!/usr/bin/python import smtplib message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com>
42 | P a g e
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A final boundary denoting the email's final section must also end with two hyphens. Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.
Example:
Following is the example which will send a file /tmp/test.txt as an attachment. Try it once:
#!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) sender = 'webmaster@tutorialpoint.com' reciever = 'amrood.admin@gmail.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. """ # Define the main headers. part1 = """From: From Person <me@fromdomain.net> To: To Person <amrood.admin@gmail.com> Subject: Sending Attachement MIME-Version: 1.0
# base64
43 | P a g e
Multithreaded Programming
Running several threads is similar to running several different programs concurrently, but with the following benefits:
Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. Threads sometimes called light-weight processes and they do not require much memory overhead; theycare cheaper than processes.
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context it is currently running.
It can be pre-empted (interrupted) It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding.
44 | P a g e
Example:
#!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # Create two threads as follows try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass
This would produce following result:
Thread-1: Thread-1: Thread-2: Thread-1: Thread-2: Thread-1: Thread-1: Thread-2: Thread-2: Thread-2:
Thu Thu Thu Thu Thu Thu Thu Thu Thu Thu
Jan Jan Jan Jan Jan Jan Jan Jan Jan Jan
22 22 22 22 22 22 22 22 22 22
15:42:17 15:42:19 15:42:19 15:42:21 15:42:23 15:42:23 15:42:25 15:42:27 15:42:31 15:42:35
2009 2009 2009 2009 2009 2009 2009 2009 2009 2009
Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module.
threading.activeCount(): Returns the number of thread objects that are active. threading.currentThread(): Returns the number of thread objects in the caller's thread control.
45 | P a g e
threading.enumerate(): Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows:
run(): The run() method is the entry point for a thread. start(): The start() method starts a thread by calling the run method. join([time]): The join() waits for threads to terminate. isAlive(): The isAlive() method checks whether a thread is still executing. getName(): The getName() method returns the name of a thread. setName(): The setName() method sets the name of a thread.
Define a new subclass of the Thread class. Override the __init__(self [,args]) method to add additional arguments. Then override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start() or run() methods.
Example:
#!/usr/bin/python import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): self.threadID = threadID self.name = name self.counter = counter threading.Thread.__init__(self) def run(self): print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start()
46 | P a g e
Starting Thread-2 Starting Thread-1 Thread-1: Thu Jan 22 Thread-2: Thu Jan 22 Thread-1: Thu Jan 22 Thread-1: Thu Jan 22 Thread-2: Thu Jan 22 Thread-1: Thu Jan 22 Thread-1: Thu Jan 22 Exiting Thread-1 Thread-2: Thu Jan 22 Thread-2: Thu Jan 22 Thread-2: Thu Jan 22 Exiting Thread-2 Exiting Main Thread
Synchronizing Threads:
The threading module provided with Python includes a simple-to-implement locking mechanism that will allow you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method the new lock object would be used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread will wait to acquire the lock. If blocking is set to 0, the thread will return immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread will block and wait for the lock to be released. The release() method of the the new lock object would be used to release the lock when it is no longer required.
Example:
#!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): self.threadID = threadID self.name = name self.counter = counter threading.Thread.__init__(self) def run(self):
47 | P a g e
Starting Thread-1 Starting Thread-2 Thread01: Thu Jan 22 Thread01: Thu Jan 22 Thread01: Thu Jan 22 Thread02: Thu Jan 22 Thread02: Thu Jan 22 Thread02: Thu Jan 22 Exiting Main Thread
get(): The get() removes and returns an item from the queue. put(): The put adds item to a queue. qsize() : The qsize() returns the number of items that are currently in the queue. empty(): The empty( ) returns True if queue is empty; otherwise, False. full(): the full() returns True if queue is full; otherwise, False.
Example:
48 | P a g e
49 | P a g e
Starting Thread-2 Starting Thread-1 Starting Thread-3 Thread-2 processing Thread-1 processing Thread-3 processing Thread-2 processing Thread-1 processing Exiting Thread-3 Exiting Thread-2 Exiting Thread-1 Exiting Main Thread
Learn JSP Learn Servlets Learn log4j Learn iBATIS Learn Java Learn JDBC Java Examples Learn Best Practices Learn Python Learn Ruby Learn Ruby on Rails Learn SQL Learn MySQL Learn AJAX Learn C Programming Learn C++ Programming Learn CGI with PERL Learn DLL Learn ebXML Learn Euphoria Learn GDB Debugger Learn Makefile Learn Parrot Learn Perl Script Learn PHP Script
Learn ASP.Net Learn HTML Learn HTML5 Learn XHTML Learn CSS Learn HTTP Learn JavaScript Learn jQuery Learn Prototype Learn script.aculo.us Web Developer's Guide Learn RADIUS Learn RSS Learn SEO Techniques Learn SOAP Learn UDDI Learn Unix Sockets Learn Web Services Learn XML-RPC Learn UML Learn UNIX Learn WSDL Learn i-Mode Learn GPRS Learn GSM
50 | P a g e
Learn Six Sigma Learn SEI CMMI Learn WiMAX Learn Telecom Billing
webmaster@TutorialsPoint.com
51 | P a g e