• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Python Tutorial
 

Python Tutorial

on

  • 663 views

Python Learning .

Python Learning .

Statistics

Views

Total Views
663
Views on SlideShare
663
Embed Views
0

Actions

Likes
1
Downloads
15
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Python Tutorial Python Tutorial Document Transcript

    • Tutorials Point, Simply Easy Learning Python Tutorial Tutorialspoint.comPython is a general purpose interpreted, interactive, object-oriented and high-levelprogramming language.Python was created by Guido van Rossum in the late eighties and early nineties. LikePerl, Python source code is now available under the GNU General Public License(GPL). This tutorial gives an initial push to start you with Python. For more detailkindly check tutorialspoint.com/pythonPython Overview:Python is a high-level, interpreted, interactive and object oriented-scripting language.  Python is Interpreted  Python is Interactive  Python is Object-Oriented  Python is Beginners LanguagePython was developed by Guido van Rossum in the late eighties and early nineties at theNational Research Institute for Mathematics and Computer Science in the Netherlands.Pythons feature highlights include:  Easy-to-learn  Easy-to-read  Easy-to-maintain  A broad standard library  Interactive Mode  Portable  Extendable  Databases  GUI Programming  ScalableGetting Python:The most up-to-date and current source code, binaries, documentation, news, etc. is availableat the official website of Python:Python Official Website : http://www.python.org/You can download the Python documentation from the following site. The documentation isavailable in HTML, PDF, and PostScript formats.Python Documentation Website : www.python.org/doc/First Python Program:Interactive Mode Programming:1|Page
    • Tutorials Point, Simply Easy LearningInvoking the interpreter without passing a script file as a parameter brings up the followingprompt:root# pythonPython 2.5 (r25:51908, Nov 6 2007, 16:54:01)[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2Type "help", "copyright", "credits" or "license" for more info.>>>Type the following text to the right of the Python prompt and press the Enter key:>>> print "Hello, Python!";This will produce following result:Hello, Python!Python Identifiers:A Python identifier is a name used to identify a variable, function, class, module, or otherobject. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero ormore letters, underscores, and digits (0 to 9).Python does not allow punctuation characters such as @, $, and % within identifiers. Python is acase sensitive programming language. Thus Manpower and manpower are two differentidentifiers 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 language- defined special name.Reserved Words:The following list shows the reserved words in Python. These reserved words may not be usedas constant or variable or any other identifier names.Keywords contain lowercase letters only.and exec notassert finally orbreak for pass2|Page
    • Tutorials Point, Simply Easy Learningclass from printcontinue global raisedef if returndel import tryelif in whileelse is withexcept lambda yieldLines and Indentation:One of the first caveats programmers encounter when learning Python is the fact that there areno braces to indicate blocks of code for class and function definitions or flow control. Blocks ofcode are denoted by line indentation, which is rigidly enforced.The number of spaces in the indentation is variable, but all statements within the block must beindented the same amount. Both blocks in this example are fine:if True: print "True"else: print "False"However, the second block in this example will generate an error: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 theline continuation character () to denote that the line should continue. For example:total = item_one + item_two + item_threeStatements contained within the [], {}, or () brackets do not need to use the line continuationcharacter. For example:3|Page
    • Tutorials Point, Simply Easy Learningdays = [Monday, Tuesday, Wednesday, Thursday, Friday]Quotation in Python:Python accepts single (), double (") and triple ( or """) quotes to denote string literals, as longas 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 thefollowing are legal:word = wordsentence = "This is a sentence."paragraph = """This is a paragraph. It ismade 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 ignoresthem.#!/usr/bin/python# First commentprint "Hello, Python!"; # second commentThis will produce following result:Hello, Python!A comment may be on the same line after a statement or expression:name = "Madisetti" # This is again commentYou can comment multiple lines as follows:# This is a comment.# This is a comment, too.# This is a comment, too.# I said that already.Using Blank Lines:A line containing only whitespace, possibly with a comment, is known as a blank line, andPython totally ignores it.In an interactive interpreter session, you must enter an empty physical line to terminate amultiline statement.Multiple Statements on a Single Line:4|Page
    • Tutorials Point, Simply Easy LearningThe semicolon ( ; ) allows multiple statements on the single line given that neither statementstarts a new code block. Here is a sample snip using the semicolon:import sys; x = foo; sys.stdout.write(x + n)Multiple Statement Groups as Suites:Groups of individual statements making up a single code block are called suites in Python.Compound or complex statements, such as if, while, def, and class, are those which require aheader line and a suite.Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and arefollowed by one or more lines which make up the suite.Example:if expression : suiteelif expression : suiteelse : suitePython - Variable Types:Variables are nothing but reserved memory locations to store values. This means that when youcreate a variable you reserve some space in memory.Based on the data type of a variable, the interpreter allocates memory and decides what can bestored in the reserved memory. Therefore, by assigning different data types to variables, youcan store integers, decimals, or characters in these variables.Assigning Values to Variables:The operand to the left of the = operator is the name of the variable, and the operand to theright of the = operator is the value stored in the variable. For example:counter = 100 # An integer assignmentmiles = 1000.0 # A floating pointname = "John" # A stringprint counterprint milesprint nameStandard Data Types:Python has five standard data types:  Numbers  String  List  Tuple5|Page
    • Tutorials Point, Simply Easy Learning  DictionaryPython Numbers:Number objects are created when you assign a value to them. For example:var1 = 1var2 = 10Python 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 long float complex10 51924361L 0.0 3.14j100 -0x19323L 15.20 45.j-786 0122L -21.9 9.322e-36j080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j-0490 535633629843L -90. -.6545+0J-0x260 -052318172735L -32.54e100 3e+26J0x69 -4721885298529L 70.2-E12 4.53e-7jPython Strings:Strings in Python are identified as a contiguous set of characters in between quotation marks.Example:str = Hello World!print str # Prints complete stringprint str[0] # Prints first character of the stringprint str[2:5] # Prints characters starting from 3rd to 6thprint str[2:] # Prints string starting from 3rd characterprint str * 2 # Prints string two timesprint str + "TEST" # Prints concatenated string6|Page
    • Tutorials Point, Simply Easy LearningPython Lists:Lists are the most versatile of Pythons compound data types. A list contains items separated bycommas and enclosed within square brackets ([]).#!/usr/bin/pythonlist = [ abcd, 786 , 2.23, john, 70.2 ]tinylist = [123, john]print list # Prints complete listprint list[0] # Prints first element of the listprint list[1:3] # Prints elements starting from 2nd to 4thprint list[2:] # Prints elements starting from 3rd elementprint tinylist * 2 # Prints list two timesprint list + tinylist # Prints concatenated listsPython Tuples:A tuple is another sequence data type that is similar to the list. A tuple consists of a number ofvalues 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 tuple # Prints complete listprint tuple[0] # Prints first element of the listprint tuple[1:3] # Prints elements starting from 2nd to 4thprint tuple[2:] # Prints elements starting from 3rd elementprint tinytuple * 2 # Prints list two timesprint tuple + tinytuple # Prints concatenated listsPython Dictionary:Python s dictionaries are hash table type. They work like associative arrays or hashes found inPerl and consist of key-value pairs.tinydict = {name: john,code:6734, dept: sales}print dict[one] # Prints value for one keyprint dict[2] # Prints value for 2 keyprint tinydict # Prints complete dictionaryprint tinydict.keys() # Prints all the keysprint tinydict.values() # Prints all the valuesPython - Basic Operators:Operator Description Example+ Addition - Adds values on either side of a + b will give 30 the operator7|Page
    • Tutorials Point, Simply Easy Learning- Subtraction - Subtracts right hand a - b will give -10 operand from left hand operand* Multiplication - Multiplies values on either a * b will give 200 side of the operator/ Division - Divides left hand operand by b / a will give 2 right hand operand% Modulus - Divides left hand operand by b % a will give 0 right hand operand and returns remainder** Exponent - Performs exponential (power) a**b will give 10 to the power 20 calculation on operators// Floor Division - The division of operands 9//2 is equal to 4 and 9.0//2.0 is equal where the result is the quotient in which to 4.0 the digits after the decimal point are removed.== Checks if the value of two operands are (a == b) is not true. equal or not, if yes then condition becomes true.!= Checks if the value of two operands are (a != b) is true. equal or not, if values are not equal then condition becomes true.<> Checks if the value of two operands are (a <> b) is true. This is similar to != equal or not, if values are not equal then operator. condition becomes true.> Checks if the value of left operand is (a > b) is not true. greater than the value of right operand, if yes then condition becomes true.< Checks if the value of left operand is less (a < b) is true. than the value of right operand, if yes then condition becomes true.>= Checks if the value of left operand is (a >= b) is not true. 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 (a <= b) is true. than or equal to the value of right operand, if yes then condition becomes8|Page
    • Tutorials Point, Simply Easy Learning true.= Simple assignment operator, Assigns c = a + b will assigne value of a + b into values from right side operands to left c side operand+= Add AND assignment operator, It adds c += a is equivalent to c = c + a right operand to the left operand and assign the result to left operand-= Subtract AND assignment operator, It c -= a is equivalent to c = c - a subtracts right operand from the left operand and assign the result to left operand*= Multiply AND assignment operator, It c *= a is equivalent to c = c * a multiplies right operand with the left operand and assign the result to left operand/= Divide AND assignment operator, It c /= a is equivalent to c = c / a divides left operand with the right operand and assign the result to left operand%= Modulus AND assignment operator, It c %= a is equivalent to c = c % a takes modulus using two operands and assign the result to left operand**= Exponent AND assignment operator, c **= a is equivalent to c = c ** a Performs exponential (power) calculation on operators and assign value to the left operand//= Floor Dividion and assigns a value, c //= a is equivalent to c = c // a Performs floor division on operators and assign value to the left operand& Binary AND Operator copies a bit to the (a & b) will give 12 which is 0000 1100 result if it exists in both operands.| Binary OR Operator copies a bit if it (a | b) will give 61 which is 0011 1101 exists in eather operand.^ Binary XOR Operator copies the bit if it is (a ^ b) will give 49 which is 0011 0001 set in one operand but not both.~ Binary Ones Complement Operator is (~a ) will give -60 which is 1100 00119|Page
    • Tutorials Point, Simply Easy Learning unary and has the efect of flipping bits.<< Binary Left Shift Operator. The left a << 2 will give 240 which is 1111 0000 operands value is moved left by the number of bits specified by the right operand.>> Binary Right Shift Operator. The left a >> 2 will give 15 which is 0000 1111 operands value is moved right by the number of bits specified by the right operand.and Called Logical AND operator. If both the (a and b) is true. operands are true then then condition becomes true.or Called Logical OR Operator. If any of the (a or b) is true. two operands are non zero then then condition becomes true.not Called Logical NOT Operator. Use to not(a && b) is false. reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.in Evaluates to true if it finds a variable in x in y, here in results in a 1 if x is a the specified sequence and false member of sequence y. otherwise.not in Evaluates to true if it finds a variable in x not in y, here not in results in a 1 if x the specified sequence and false is a member of sequence y. otherwise.is Evaluates to true if the variables on x is y, here is results in 1 if id(x) equals either side of the operator point to the id(y). same object and false otherwise.is not Evaluates to false if the variables on x is not y, here is not results in 1 if id(x) either side of the operator point to the is not equal to id(y). same object and true otherwise.Python Operators PrecedenceThe following table lists all operators from highest precedence to lowest. Operator Description10 | P a g e
    • Tutorials Point, Simply Easy Learning** Exponentiation (raise to the power)~+- Ccomplement, unary plus and minus (method names for the last two are +@ and -@)* / % // Multiply, divide, modulo and floor division+- Addition and subtraction>> << Right and left bitwise shift& Bitwise AND^| Bitwise exclusive `OR and regular `OR<= < > >= Comparison operators<> == != Equality operators= %= /= //= -= += |= &= >>= Assignment operators<<= *= **=is is not Identity operatorsin not in Membership operatorsnote or and Logical operatorsThe if statement:The syntax of the if statement is:if expression: statement(s)The else Statement:The syntax of the if...else statement is:if expression: statement(s)else: statement(s)The elif Statement11 | P a g e
    • Tutorials Point, Simply Easy LearningThe syntax of the if...elif statement is:if expression1: statement(s)elif expression2: statement(s)elif expression3: statement(s)else: statement(s)This will produce following result:3 - Got a true expression value100Good bye!The Nested if...elif...else ConstructThe syntax of the nested if...elif...else construct may be:if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s)elif expression4: statement(s)else: statement(s)The while Loop:The syntax of the while look is:while expression: statement(s)The Infinite Loops:You must use caution when using while loops because of the possibility that this condition neverresolves to a false value. This results in a loop that never ends. Such a loop is called an infiniteloop.An infinite loop might be useful in client/server programming where the server needs to runcontinuously so that client programs can communicate with it as and when required.Single Statement Suites:12 | P a g e
    • Tutorials Point, Simply Easy LearningSimilar to the if statement syntax, if your while clause consists only of a single statement, itmay be placed on the same line as the while header.Here is an example of a one-line while clause:while expression : statementThe for Loop:The syntax of the loop look is:for iterating_var in sequence: statements(s)Iterating by Sequence Index:An alternative way of iterating through each item is by index offset into the sequence itself:fruits = [banana, apple, mango]for index in range(len(fruits)): print Current fruit :, fruits[index]print "Good bye!"The break Statement:The break statement in Python terminates the current loop and resumes execution at the nextstatement, just like the traditional break found in C.The most common use for break is when some external condition is triggered requiring a hastyexit from a loop. The break statement can be used in both while and for loops.for letter in Python: # First Example if letter == h: break print Current Letter :, lettervar = 10 # Second Examplewhile var > 0: print Current variable value :, var var = var -1 if var == 5: breakprint "Good bye!"The continue Statement:The continue statement in Python returns the control to the beginning of the while loop. Thecontinue statement rejects all the remaining statements in the current iteration of the loop andmoves the control back to the top of the loop.The continue statement can be used in both while and for loops.13 | P a g e
    • Tutorials Point, Simply Easy Learningfor letter in Python: # First Example if letter == h: continue print Current Letter :, lettervar = 10 # Second Examplewhile var > 0: print Current variable value :, var var = var -1 if var == 5: continueprint "Good bye!"The else Statement Used with LoopsPython supports to have an else statement associated with a loop statements.  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.The pass Statement:The pass statement in Python is used when a statement is required syntactically but you do notwant any command or code to execute.The pass statement is a null operation; nothing happens when it executes. The pass is alsouseful in places where your code will eventually go, but has not been written yet (e.g., in stubsfor example):#!/usr/bin/pythonfor letter in Python: if letter == h: pass print This is pass block print Current Letter :, letterprint "Good bye!"Defining a FunctionYou can define functions to provide the required functionality. Here are simple rules to define afunction 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
    • Tutorials Point, Simply Easy Learning  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 sameorder that they were defined.Example:Here is the simplest form of a Python function. This function takes a string as input parameterand prints it on standard screen.def printme( str ): "This prints a passed string into this function" print str returnCalling a FunctionDefining a function only gives it a name, specifies the parameters that are to be included in thefunction, and structures the blocks of code.Once the basic structure of a function is finalized, you can execute it by calling it from anotherfunction or directly from the Python prompt.Following is the example to call printme() function:#!/usr/bin/python# Function definition is heredef printme( str ): "This prints a passed string into this function" print str; return;# Now you can call printme functionprintme("Im first call to user defined function!");printme("Again second call to the same function");This would produce following result:Im first call to user defined function!Again second call to the same functionPython - Modules:15 | P a g e
    • Tutorials Point, Simply Easy LearningA module allows you to logically organize your Python code. Grouping related code into amodule makes the code easier to understand and use.A module is a Python object with arbitrarily named attributes that you can bind and reference.Simply, a module is a file consisting of Python code. A module can define functions, classes, andvariables. A module can also include runnable code.Example:The Python code for a module named aname normally resides in a file named aname.py. Heresan example of a simple module, hello.pydef print_func( par ): print "Hello : ", par returnThe import Statement:You can use any Python source file as a module by executing an import statement in some otherPython source file. import has the following syntax:import module1[, module2[,... moduleN]When the interpreter encounters an import statement, it imports the module if the module ispresent in the search path. Asearch path is a list of directories that the interpreter searchesbefore importing a module.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 helloimport hello# Now you can call defined function that module as followshellp.print_func("Zara")This would produce following result:Hello : ZaraA module is loaded only once, regardless of the number of times it is imported. This preventsthe module execution from happening over and over again if multiple imports occur.Opening and Closing Files:The open Function:16 | P a g e
    • Tutorials Point, Simply Easy LearningBefore you can read or write a file, you have to open it using Pythons built-in open() function.This function creates a file object which would be utilized to call other support methodsassociated with it.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 Descriptionr Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.rb 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.r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file.rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.w 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.wb 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.w+ 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.wb+ 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.a 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 for17 | P a g e
    • Tutorials Point, Simply Easy Learning writing.ab Opens a file for appending in binary format. 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 writing.a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.The file object atrributes:Once a file is opened and you have one file object, you can get various information related tothat file.Here is a list of all attributes related to file object: Attribute Descriptionfile.closed Returns true if file is closed, false otherwise.file.mode Returns access mode with which file was opened.file.name Returns name of the file.file.softspace Returns false if space explicitly required with print, true otherwise.The close() Method:The close() method of a file object flushes any unwritten information and closes the file object,after which no more writing can be done.fileObject.close();Reading and Writing Files:The write() Method:Syntax:fileObject.write(string);The read() Method:Syntax:18 | P a g e
    • Tutorials Point, Simply Easy LearningfileObject.read([count]);File Positions:The tell() method tells you the current position within the file in other words, the next read orwrite 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 indicatesthe number of bytes to be moved. The fromargument specifies the reference position fromwhere 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 meansuse the current position as the reference position and if it is set to 2 then the end of the filewould be taken as the reference position.Renaming and Deleting Files:Syntax:os.rename(current_file_name, new_file_name)The remove() Method:Syntax:os.delete(file_name)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 becreated.Syntax:os.mkdir("newdir")The chdir() Method:You can use the chdir() method to change the current directory. The chdir() method takes anargument, which is the name of the directory that you want to make the current directory.Syntax:os.chdir("newdir")The getcwd() Method:The getcwd() method displays the current working directory.Syntax:19 | P a g e
    • Tutorials Point, Simply Easy Learningos.getcwd()The rmdir() Method:The rmdir() method deletes the directory, which is passed as an argument in the method.Before removing a directory, all the contents in it should be removed.Syntax:os.rmdir(dirname)Handling an exception:If you have some suspicious code that may raise an exception, you can defend your program byplacing 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: blocks protection.The except clause with no exceptions:You can also use the except statement with no exceptions defined as follows: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
    • Tutorials Point, Simply Easy LearningThe except clause with multiple exceptions:You can also use the same except statement to handle multiple exceptions as follows: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 ExceptionsThe try-finally clause:You can use a finally: block along with a try: block. The finally block is a place to put any codethat must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this: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 theproblem. The contents of the argument vary by exception. You capture an exceptions argumentby 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 forthe raise statement.Syntax:raise [Exception [, args [, traceback]]]21 | P a g e
    • Tutorials Point, Simply Easy LearningUser-Defined Exceptions:Python also allows you to create your own exceptions by deriving classes from the standardbuilt-in exceptions.Here is an example related to RuntimeError. Here a class is created that is subclassed fromRuntimeError. This is useful when you need to display more specific information when anexception is caught.In the try block, the user-defined exception is raised and caught in the except block. Thevariable e is used to create an instance of the class Networkerror.class Networkerror(RuntimeError): def __init__(self, arg): self.args = argSo once you defined above class, you can raise your exception as follows:try: raise Networkerror("Bad hostname")except Networkerror,e: print e.argsCreating Classes:The class statement creates a new class definition. The name of the class immediately followsthe keyword class followed by a colon as follows:class ClassName: Optional class documentation string class_suite  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.Creating instance objects:To create instances of a class, you call the class using class name and pass in whateverarguments its __init__ method accepts."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 objects attributes using the dot operator with object. Class variable would beaccessed using class name as follows:emp1.displayEmployee()22 | P a g e
    • Tutorials Point, Simply Easy Learningemp2.displayEmployee()print "Total Employee %d" % Employee.empCountBuilt-In Class Attributes:Every Python class keeps following built-in attributes and they can be accessed using dotoperator like any other attribute:  __dict__ : Dictionary containing the classs 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.Destroying Objects (Garbage Collection):Python deletes unneeded objects (built-in types or class instances) automatically to freememory space. The process by which Python periodically reclaims blocks of memory that nolonger are in use is termed garbage collection.Pythons garbage collector runs during program execution and is triggered when an objectsreference count reaches zero. An objects reference count changes as the number of aliases thatpoint to it changes:An objects reference count increases when its assigned a new name or placed in a container(list, tuple, or dictionary). The objects reference count decreases when its deleted with del, itsreference is reassigned, or its reference goes out of scope. When an objects reference countreaches zero, Python collects it automatically.Class Inheritance:Instead of starting from scratch, you can create a class by deriving it from a preexisting class bylisting 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 ifthey were defined in the child class. A child class can also override data members and methodsfrom the parent.Syntax:Derived classes are declared much like their parent class; however, a list of base classes toinherit from are given after the class name:class SubClassName (ParentClass1[, ParentClass2, ...]): Optional class documentation string class_suiteOverriding Methods:You can always override your parent class methods. One reason for overriding parents methodsis because you may want special or different functionality in your subclass.23 | P a g e
    • Tutorials Point, Simply Easy Learningclass Parent: # define parent class def myMethod(self): print Calling parent methodclass Child(Parent): # define child class def myMethod(self): print Calling child methodc = Child() # instance of childc.myMethod() # child calls overridden methodBase Overloading Methods:Following table lists some generic functionality that you can override in your own classes: SN Method, Description & Sample Call1 __init__ ( self [,args...] ) Constructor (with any optional arguments) Sample Call : obj = className(args)2 __del__( self ) Destructor, deletes an object Sample Call : dell obj3 __repr__( self ) Evaluatable string representation Sample Call : repr(obj)4 __str__( self ) Printable string representation Sample Call : str(obj)5 __cmp__ ( self, x ) Object comparison Sample Call : cmp(obj, x)Overloading Operators:Suppose youve created a Vector class to represent two-dimensional vectors. What happenswhen 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, andthen the plus operator would behave as per expectation:#!/usr/bin/pythonclass Vector: def __init__(self, a, b): self.a = a self.b = b24 | P a g e
    • Tutorials Point, Simply Easy Learning def __str__(self): return Vector (%d, %d) % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b)v1 = Vector(2,10)v2 = Vector(5,-2)print v1 + v2Data Hiding:An objects 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 bedirectly visible to outsiders:#!/usr/bin/pythonclass JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCountcounter = JustCounter()counter.count()counter.count()print counter.__secretCountA regular expression is a special sequence of characters that helps you match or find otherstrings or sets of strings, using a specialized syntax held in a pattern. Regular expressions arewidely used in UNIX world.The module re provides full support for Perl-like regular expressions in Python. The re moduleraises 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 whenthey are used in regular expression. To avoid any confusion while dealing with regularexpressions we would use Raw Strings as rexpression.The match FunctionThis function attempts to match RE pattern to string with optional flags.Here is the syntax for this function:re.match(pattern, string, flags=0)Here is the description of the parameters: Parameter Description25 | P a g e
    • Tutorials Point, Simply Easy Learningpattern This is the regular expression to be matched.string This is the string which would be searched to match the patternflags You can specifiy different flags using exclusive OR (|). These are modifiers which are listed in the table below.The re.match function returns a match object on success, None on failure. We would usegroup(num) or groups() function of match object to get matched expression. Match Object Methods Descriptiongroup(num=0) This methods returns entire match (or specific subgroup num)groups() This method return all matching subgroups in a tuple (empty if there werent any)The search FunctionThis function search for first occurrence of RE pattern within string with optional flags.Here is the syntax for this function:re.string(pattern, string, flags=0)Here is the description of the parameters: Parameter Descriptionpattern This is the regular expression to be matched.string This is the string which would be searched to match the patternflags You can specifiy different flags using exclusive OR (|). These are modifiers which are listed in the table below.The re.search function returns a match object on success, None on failure. We would usegroup(num) or groups() function of match object to get matched expression. Match Object Methods Descriptiongroup(num=0) This methods returns entire match (or specific subgroup num)26 | P a g e
    • Tutorials Point, Simply Easy Learninggroups() This method return all matching subgroups in a tuple (empty if there werent any)Matching vs Searching:Python offers two different primitive operations based on regular expressions: match checks fora match only at the beginning of the string, while search checks for a match anywhere in thestring (this is what Perl does by default).Search and Replace:Some of the most important re methods that use regular expressions is sub.Syntax:sub(pattern, repl, string, max=0)This method replace all occurrences of the RE pattern in string with repl, substituting alloccurrences unless max provided. This method would return modified string.Regular-expression Modifiers - Option FlagsRegular expression literals may include an optional modifier to control various aspects ofmatching. The modifier are specified as an optional flag. You can provide multiple modifiedusing exclusive OR (|), as shown previously and may be represented by one of these: Modifier Descriptionre.I Performs case-insensitive matching.re.L Interprets words according to the current locale.This interpretation affects the alphabetic group (w and W), as well as word boundary behavior (b and B).re.M Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).re.S Makes a period (dot) match any character, including a newline.re.U Interprets letters according to the Unicode character set. This flag affects the behavior of w, W, b, B.re.X Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash), and treats unescaped # as a comment marker.Regular-expression patterns:27 | P a g e
    • Tutorials Point, Simply Easy LearningExcept for control characters, (+ ? . * ^ $ ( ) [ ] { } | ), all characters match themselves.You can escape a control character by preceding it with a backslash.Following table lists the regular expression syntax that is available in Python. Pattern Description^ Matches beginning of line.$ Matches end of line.. Matches any single character except newline. Using m option allows it to match newline as well.[...] Matches any single character in brackets.[^...] Matches any single character not in bracketsre* Matches 0 or more occurrences of preceding expression.re+ Matches 0 or 1 occurrence of preceding expression.re{ n} Matches exactly n number of occurrences of preceding expression.re{ n,} Matches n or more occurrences of preceding expression.re{ n, m} Matches at least n and at most m occurrences of preceding expression.a| b Matches either a or b.(re) Groups regular expressions and remembers matched text.(?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.(?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.(?: re) Groups regular expressions without remembering matched text.(?imx: re) Temporarily toggles on i, m, or x options within parentheses.(?-imx: re) Temporarily toggles off i, m, or x options within parentheses.(?#...) Comment.28 | P a g e
    • Tutorials Point, Simply Easy Learning(?= re) Specifies position using a pattern. Doesnt have a range.(?! re) Specifies position using pattern negation. Doesnt have a range.(?> re) Matches independent pattern without backtracking.w Matches word characters.W Matches nonword characters.s Matches whitespace. Equivalent to [tnrf].S Matches nonwhitespace.d Matches digits. Equivalent to [0-9].D Matches nondigits.A Matches beginning of string.Z Matches end of string. If a newline exists, it matches just before newline.z Matches end of string.G Matches point where last match finished.b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.B Matches nonword boundaries.n, t, etc. Matches newlines, carriage returns, tabs, etc.1...9 Matches nth grouped subexpression.10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.Regular-expression Examples:Literal characters: Example Description29 | P a g e
    • Tutorials Point, Simply Easy Learningpython Match "python".Character classes: Example Description[Pp]ython Match "Python" or "python"rub[ye] Match "ruby" or "rube"[aeiou] Match any one lowercase vowel[0-9] Match any digit; same as [0123456789][a-z] Match any lowercase ASCII letter[A-Z] Match any uppercase ASCII letter[a-zA-Z0-9] Match any of the above[^aeiou] Match anything other than a lowercase vowel[^0-9] Match anything other than a digitSpecial Character Classes: Example Description. Match any character except newlined Match a digit: [0-9]D Match a nondigit: [^0-9]s Match a whitespace character: [ trnf]S Match nonwhitespace: [^ trnf]w Match a single word character: [A-Za-z0-9_]W Match a nonword character: [^A-Za-z0-9_]Repetition Cases:30 | P a g e
    • Tutorials Point, Simply Easy Learning Example Descriptionruby? Match "rub" or "ruby": the y is optionalruby* Match "rub" plus 0 or more ysruby+ Match "rub" plus 1 or more ysd{3} Match exactly 3 digitsd{3,} Match 3 or more digitsd{3,5} Match 3, 4, or 5 digitsNongreedy repetition:This matches the smallest number of repetitions: Example Description<.*> Greedy repetition: matches "<python>perl>"<.*?> Nongreedy: matches "<python>" in "<python>perl>"Grouping with parentheses: Example DescriptionDd+ No group: + repeats d(Dd)+ Grouped: + repeats Dd pair([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc.Backreferences:This matches a previously matched group again: Example Description([Pp])ython&1ails Match python&rails or Python&Rails(["])[^1]*1 Single or double-quoted string. 1 matches whatever the 1st group31 | P a g e
    • Tutorials Point, Simply Easy Learning matched . 2 matches whatever the 2nd group matched, etc.Alternatives: Example Descriptionpython|perl Match "python" or "perl"rub(y|le)) Match "ruby" or "ruble"Python(!+|?) "Python" followed by one or more ! or one ?Anchors:This need to specify match position Example Description^Python Match "Python" at the start of a string or internal linePython$ Match "Python" at the end of a string or lineAPython Match "Python" at the start of a stringPythonZ Match "Python" at the end of a stringbPythonb Match "Python" at a word boundarybrubB B is nonword boundary: match "rub" in "rube" and "ruby" but not alonePython(?=!) Match "Python", if followed by an exclamation pointPython(?!!) Match "Python", if not followed by an exclamation pointSpecial syntax with parentheses: Example DescriptionR(?#comment) Matches "R". All the rest is a commentR(?i)uby Case-insensitive while matching "uby"32 | P a g e
    • Tutorials Point, Simply Easy LearningR(?i:uby) Same as aboverub(?:y|le)) Group only without creating 1 backreferenceMySQL Database AccessThe Python standard for database interfaces is the Python DB-API. Most Python databaseinterfaces adhere to this standard.You can choose the right database for your application. Python Database API supports a widerange of database servers:  GadFly  mSQL  MySQL  PostgreSQL  Microsoft SQL Server 2000  Informix  Interbase  Oracle  SybaseHere is the list of available Python databases interfaces:Python Database Interfaces and APIsYou must download a separate DB API module for each database you need to access. Forexample, if you need to access an Oracle database as well as a MySQL database, you mustdownload both the Oracle and the MySQL database modules.The DB API provides a minimal standard for working with databases, using Python structuresand syntax wherever possible. This API includes the following:  Importing the api module.  Acquiring a connection with the database.  Issuing SQL statements and stored procedures.  Closing the connectionWe would learn all the concepts using MySQL so lets talk about MySQLdb module only.What is MySQLdb?MySQLdb is an interface for connecting to a MySQL database server from Python. It implementsthe Python Database API v2.0, and is built on top of the MySQL C API.How do I install the MySQLdb?Before proceeding you make sure you have MySQLdb installed on your machine. Just type thefollowing in your Python script and execute it:#!/usr/bin/python33 | P a g e
    • Tutorials Point, Simply Easy Learningimport MySQLdbIf it produces following result then it means MySQLdb module is not installed:Traceback (most recent call last): File "test.py", line 3, in <module> import MySQLdbImportError: No module named MySQLdbTo 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 installNote: 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/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = 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 server34 | P a g e
    • Tutorials Point, Simply Easy Learningdb.close()While running this script, its producing following result at my Linux machine.Database version : 5.0.45If a connection is established with the datasource then a Connection Object is returned andsaved into db for further use otherwise db is set to None. Next db object is used to create acursor object which in turn is used to execute SQL queries.Finally before coming out it ensures that database connection is closed and resources arereleased.Creating Database Table:Once a database connection is established, we are ready to create tables or records into thedatabase tables using execute method of the created cursor.Example:First lets create Database table EMPLOYEE:#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = db.cursor()# Drop table if it already exist using execute() method.cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")# Create table as per requirementsql = """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 serverdb.close()INSERT Operation:INSERT operation is required when you want to create your records into a database table.Example:35 | P a g e
    • Tutorials Point, Simply Easy LearningFollowing is the example which executes SQL INSERT statement to create a record intoEMPLOYEE table.#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = 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 serverdb.close()Above example can be written as follows to create SQL queries dynamically:#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = 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 serverdb.close()Example:36 | P a g e
    • Tutorials Point, Simply Easy LearningFollowing code segment is another form of execute where you can pass parameters directly:..................................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 fetechmultiple 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 morethan 1000.#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = 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
    • Tutorials Point, Simply Easy Learning (fname, lname, age, sex, income )except: print "Error: unable to fecth data"# disconnect from serverdb.close()This will produce following result:fname=Mac, lname=Mohan, age=20, sex=M, income=2000Update Operation:UPDATE Operation on any databasse means to update one or more records which are alreadyavailable 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/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = db.cursor()# Prepare SQL query to UPDATE required recordssql = "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 serverdb.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/pythonimport MySQLdb# Open database connection38 | P a g e
    • Tutorials Point, Simply Easy Learningdb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = db.cursor()# Prepare SQL query to DELETE required recordssql = "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()# disconnect from serverdb.close()Performing Transactions:Transactions are a mechanism that ensures data consistency. Transactions should have thefollowing 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 recordssql = "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 afterthis operation no change can be reverted back.Here is a simple example to call commit method.39 | P a g e
    • Tutorials Point, Simply Easy Learning db.commit()ROLLBACK Operation:If you are not satisfied with one or more of the changes and you want to revert back thosechanges 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 outstandingtransactions are rolled back by the DB. However, instead of depending on any of DB lower levelimplementation 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 SQLstatement, a connection failure, or calling the fetch method for an already canceled or finishedstatement handle.The DB API defines a number of errors that must exist in each database module. The followingtable lists these exceptions. Exception DescriptionWarning Used for non-fatal issues. Must subclass StandardError.Error Base class for errors. Must subclass StandardError.InterfaceError Used for errors in the database module, not the database itself. Must subclass Error.DatabaseError Used for errors in the database. Must subclass Error.DataError Subclass of DatabaseError that refers to errors in the data.OperationalError 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
    • Tutorials Point, Simply Easy LearningIntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality.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 aboutthem by reading the DB API 2.0 specification.Sending Email using SMTPSimple Mail Transfer Protocol (SMTP) is a protocol which handles sending e-mail and routing e-mail between mail servers.Python provides smtplib module which defines an SMTP client session object that can be usedto send mail to any Internet machine with an SMTP or ESMTP listener daemon.Here is a simple syntax to create one SMTP object which can later be used to send an email:import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )Here is the detail of the parameters:  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 thework 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
    • Tutorials Point, Simply Easy Learning#!/usr/bin/pythonimport smtplibsender = from@fromdomain.comreceivers = [to@todomain.com]message = """From: From Person <from@fromdomain.com>To: To Person <to@todomain.com>Subject: SMTP e-mail testThis is a test e-mail message."""try: smtpObj = smtplib.SMTP(localhost) smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"Here you have placed a basic e-mail in message, using a triple quote, taking care to format theheaders correctly. An e-mails requires a From, To, and Subject header, separated from thebody of the e-mail with a blank line.To send the mail you use smtpObj to connect to the SMTP server on the local machine and thenuse the sendmail method along with the message, the from address, and the destinationaddress as parameters (even though the from and to addresses are within the e-mail itself,these arent always used to route mail).If youre not running an SMTP server on your local machine, you can use smtplib client tocommunicate with a remote SMTP server. Unless youre using a webmail service (such asHotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail serverdetails that you can supply them, as follows:smtplib.SMTP(mail.your-domain.com, 25)Sending an HTML email using Python:When you send a text message using Python then all the content will be treated as simple text.Even if you will include HTML tags in a text message, it will be displayed as simple text andHTML tags will not be formatted according to HTML syntax. But Python provides option to sendan HTML message as actual HTML message.While sending an email message you can specify a Mime version, content type and character setto send an HTML email.Example:Following is the example to send HTML content as an email. Try it once:#!/usr/bin/pythonimport smtplibmessage = """From: From Person <from@fromdomain.com>To: To Person <to@todomain.com>42 | P a g e
    • Tutorials Point, Simply Easy LearningMIME-Version: 1.0Content-type: text/htmlSubject: SMTP HTML e-mail testThis is an e-mail message to be sent in HTML format<b>This is HTML message.</b><h1>This is headline.</h1>"""try: smtpObj = smtplib.SMTP(localhost) smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"Sending Attachements as an e-mail:To send an email with mixed content requires to set Content-type header tomultipart/mixed. Then text and attachment sections can be specified within boundaries.A boundary is started with two hyphens followed by a unique number which can not appear inthe message part of the email. A final boundary denoting the emails final section must also endwith two hyphens.Attached files should be encoded with the pack("m") function to have base64 encoding beforetransmission.Example:Following is the example which will send a file /tmp/test.txt as an attachment. Try it once:#!/usr/bin/pythonimport smtplibimport base64filename = "/tmp/test.txt"# Read a file and encode it into base64 formatfo = open(filename, "rb")filecontent = fo.read()encodedcontent = base64.b64encode(filecontent) # base64sender = webmaster@tutorialpoint.comreciever = amrood.admin@gmail.commarker = "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 AttachementMIME-Version: 1.043 | P a g e
    • Tutorials Point, Simply Easy LearningContent-Type: multipart/mixed; boundary=%s--%s""" % (marker, marker)# Define the message actionpart2 = """Content-Type: text/plainContent-Transfer-Encoding:8bit%s--%s""" % (body,marker)# Define the attachment sectionpart3 = """Content-Type: multipart/mixed; name="%s"Content-Transfer-Encoding:base64Content-Disposition: attachment; filename=%s%s--%s--""" %(filename, filename, encodedcontent, marker)message = part1 + part2 + part3try: smtpObj = smtplib.SMTP(localhost) smtpObj.sendmail(sender, reciever, message) print "Successfully sent email"except Exception: print "Error: unable to send email"Multithreaded ProgrammingRunning several threads is similar to running several different programs concurrently, but withthe 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 pointerthat 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.Starting a New Thread:To spawn another thread, you need to call following method available in thread module:thread.start_new_thread ( function, args[, kwargs] )This method call enables a fast and efficient way to create new threads in both Linux andWindows.44 | P a g e
    • Tutorials Point, Simply Easy LearningThe method call returns immediately and the child thread starts and calls function with thepassed list of agrs. When function returns, the thread terminates.Here args is a tuple of arguments; use an empty tuple to call function without passing anyarguments. kwargs is an optional dictionary of keyword arguments.Example:#!/usr/bin/pythonimport threadimport time# Define a function for the threaddef 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 followstry: 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: passThis would produce following result:Thread-1: Thu Jan 22 15:42:17 2009Thread-1: Thu Jan 22 15:42:19 2009Thread-2: Thu Jan 22 15:42:19 2009Thread-1: Thu Jan 22 15:42:21 2009Thread-2: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:25 2009Thread-2: Thu Jan 22 15:42:27 2009Thread-2: Thu Jan 22 15:42:31 2009Thread-2: Thu Jan 22 15:42:35 2009Although it is very effective for low-level threading, but the thread module is very limitedcompared to the newer threading module.The Threading Module:The newer threading module included with Python 2.4 provides much more powerful, high-levelsupport for threads than the thread module discussed in the previous section.The threading module exposes all the methods of the thread module and provides someadditional methods:  threading.activeCount(): Returns the number of thread objects that are active.  threading.currentThread(): Returns the number of thread objects in the callers thread control.45 | P a g e
    • Tutorials Point, Simply Easy Learning  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 implementsthreading. 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.Creating Thread using Threading Module:To implement a new thread using the threading module, you have to do the following:  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 starta new thread by invoking the start() or run() methods.Example:#!/usr/bin/pythonimport threadingimport timeexitFlag = 0class 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.namedef 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 threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()46 | P a g e
    • Tutorials Point, Simply Easy Learningthread2.run()while thread2.isAlive(): if not thread1.isAlive(): exitFlag = 1 passprint "Exiting Main Thread"This would produce following result:Starting Thread-2Starting Thread-1Thread-1: Thu Jan 22 15:53:05 2009Thread-2: Thu Jan 22 15:53:06 2009Thread-1: Thu Jan 22 15:53:06 2009Thread-1: Thu Jan 22 15:53:07 2009Thread-2: Thu Jan 22 15:53:08 2009Thread-1: Thu Jan 22 15:53:08 2009Thread-1: Thu Jan 22 15:53:09 2009Exiting Thread-1Thread-2: Thu Jan 22 15:53:10 2009Thread-2: Thu Jan 22 15:53:12 2009Thread-2: Thu Jan 22 15:53:14 2009Exiting Thread-2Exiting Main ThreadSynchronizing Threads:The threading module provided with Python includes a simple-to-implement locking mechanismthat 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 runsynchronously. The optional blocking parameter enables you to control whether the thread willwait to acquire the lock.If blocking is set to 0, the thread will return immediately with a 0 value if the lock cannot beacquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread will block andwait 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 nolonger required.Example:#!/usr/bin/pythonimport threadingimport timeclass 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
    • Tutorials Point, Simply Easy Learning print "Starting " + self.name # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release()def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1threadLock = threading.Lock()threads = []# Create new threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.start()# Add threads to thread listthreads.append(thread1)threads.append(thread2)# Wait for all threads to completefor t in threads: t.join()print "Exiting Main Thread"This would produce following result:Starting Thread-1Starting Thread-2Thread01: Thu Jan 22 16:04:38 2009Thread01: Thu Jan 22 16:04:39 2009Thread01: Thu Jan 22 16:04:40 2009Thread02: Thu Jan 22 16:04:42 2009Thread02: Thu Jan 22 16:04:44 2009Thread02: Thu Jan 22 16:04:46 2009Exiting Main ThreadMultithreaded Priority Queue:The Queue module allows you to create a new queue object that can hold a specific number ofitems. There are following methods to control the Queue:  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
    • Tutorials Point, Simply Easy Learning#!/usr/bin/pythonimport Queueimport threadingimport timeexitFlag = 0class myThread (threading.Thread): def __init__(self, threadID, name, q): self.threadID = threadID self.name = name self.q = q threading.Thread.__init__(self) def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + self.namedef process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print "%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3"]nameList = ["One", "Two", "Three", "Four", "Five"]queueLock = threading.Lock()workQueue = Queue.Queue(10)threads = []threadID = 1# Create new threadsfor tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1# Fill the queuequeueLock.acquire()for word in nameList: workQueue.put(word)queueLock.release()# Wait for queue to emptywhile not workQueue.empty(): pass# Notify threads its time to exitexitFlag = 1# Wait for all threads to completefor t in threads: t.join()print "Exiting Main Thread"49 | P a g e
    • Tutorials Point, Simply Easy LearningThis would produce following result:Starting Thread-2Starting Thread-1Starting Thread-3Thread-2 processing OneThread-1 processing TwoThread-3 processing ThreeThread-2 processing FourThread-1 processing FiveExiting Thread-3Exiting Thread-2Exiting Thread-1Exiting Main ThreadFurther Detail:Refer to the link http://www.tutorialspoint.com/python List of Tutorials from TutorialsPoint.com  Learn JSP  Learn ASP.Net  Learn Servlets  Learn HTML  Learn log4j  Learn HTML5  Learn iBATIS  Learn XHTML  Learn Java  Learn CSS  Learn JDBC  Learn HTTP  Java Examples  Learn JavaScript  Learn Best Practices  Learn jQuery  Learn Python  Learn Prototype  Learn Ruby  Learn script.aculo.us  Learn Ruby on Rails  Web Developers Guide  Learn SQL  Learn RADIUS  Learn MySQL  Learn RSS  Learn AJAX  Learn SEO Techniques  Learn C Programming  Learn SOAP  Learn C++ Programming  Learn UDDI  Learn CGI with PERL  Learn Unix Sockets  Learn DLL  Learn Web Services  Learn ebXML  Learn XML-RPC  Learn Euphoria  Learn UML  Learn GDB Debugger  Learn UNIX  Learn Makefile  Learn WSDL  Learn Parrot  Learn i-Mode  Learn Perl Script  Learn GPRS  Learn PHP Script  Learn GSM50 | P a g e
    • Tutorials Point, Simply Easy Learning  Learn Six Sigma  Learn WAP  Learn SEI CMMI  Learn WML  Learn WiMAX  Learn Wi-Fi  Learn Telecom Billing webmaster@TutorialsPoint.com51 | P a g e