Python Tutorial

June 25, 2018 | Author: sreekantth | Category: Python (Programming Language), Parameter (Computer Programming), Control Flow, Scope (Computer Science), Subroutine
Report this link


Description

Financial Accounting TutorialPython About the Tutorial Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language. Audience This tutorial is designed for software programmers who need to learn Python programming language from scratch. Prerequisites You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus. Disclaimer & Copyright  Copyright 2017 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at [email protected]. i Python Table of Contents About the Tutorial .......................................................................................................................................... i Audience ........................................................................................................................................................ i Prerequisites .................................................................................................................................................. i Disclaimer & Copyright................................................................................................................................... i Table of Contents .......................................................................................................................................... ii 1. PYTHON ─ OVERVIEW ............................................................................................................... 1 History of Python .......................................................................................................................................... 1 Python Features ............................................................................................................................................ 1 2. PYTHON ─ ENVIRONMENT........................................................................................................ 3 Local Environment Setup............................................................................................................................... 3 Getting Python .............................................................................................................................................. 3 Installing Python ........................................................................................................................................... 4 Setting up PATH ............................................................................................................................................ 5 Setting path at Unix/Linux ............................................................................................................................ 5 Setting path at Windows ............................................................................................................................... 6 Python Environment Variables ...................................................................................................................... 6 Running Python ............................................................................................................................................. 6 3. PYTHON ─ BASIC SYNTAX .......................................................................................................... 9 First Python Program .................................................................................................................................... 9 Python Identifiers........................................................................................................................................ 10 Python Keywords ........................................................................................................................................ 11 Lines and Indentation.................................................................................................................................. 11 Multi-Line Statements ................................................................................................................................. 13 ii Python Quotation in Python .................................................................................................................................... 13 Comments in Python ................................................................................................................................... 14 Using Blank Lines ........................................................................................................................................ 14 Waiting for the User .................................................................................................................................... 15 Multiple Statements on a Single Line .......................................................................................................... 15 Multiple Statement Groups as Suites .......................................................................................................... 15 Command Line Arguments .......................................................................................................................... 15 Accessing Command-Line Arguments .......................................................................................................... 16 Parsing Command-Line Arguments ............................................................................................................. 17 getopt.getopt method................................................................................................................................. 17 Exception getopt.GetoptError ..................................................................................................................... 17 4. PYTHON ─ VARIABLE TYPES .................................................................................................... 20 Assigning Values to Variables ...................................................................................................................... 20 Multiple Assignment ................................................................................................................................... 21 Standard Data Types ................................................................................................................................... 21 Python Numbers ......................................................................................................................................... 21 Python Strings ............................................................................................................................................. 23 Python Lists ................................................................................................................................................. 24 Python Tuples ............................................................................................................................................. 24 Python Dictionary ....................................................................................................................................... 26 Data Type Conversion ................................................................................................................................. 27 5. PYTHON ─ BASIC OPERATORS ................................................................................................. 29 Types of Operators ...................................................................................................................................... 29 Python Arithmetic Operators ...................................................................................................................... 29 Python Comparison Operators .................................................................................................................... 31 iii Python Python Assignment Operators .................................................................................................................... 34 Python Bitwise Operators ........................................................................................................................... 36 Python Logical Operators ............................................................................................................................ 38 Python Membership Operators ................................................................................................................... 38 Python Identity Operators........................................................................................................................... 40 Python Operators Precedence ..................................................................................................................... 41 6. PYTHON ─ DECISION MAKING................................................................................................. 44 If Statement ................................................................................................................................................ 45 If…else Statement ....................................................................................................................................... 46 The elif Statement ....................................................................................................................................... 48 Single Statement Suites ............................................................................................................................... 49 7. PYTHON ─ LOOPS ................................................................................................................... 51 While Loop .................................................................................................................................................. 52 The Infinite Loop ......................................................................................................................................... 53 Using else Statement with Loops ................................................................................................................ 54 Single Statement Suites ............................................................................................................................... 55 For Loop ...................................................................................................................................................... 56 Iterating by Sequence Index ........................................................................................................................ 57 Using else Statement with Loops ................................................................................................................ 58 Nested Loops .............................................................................................................................................. 59 Loop Control Statements............................................................................................................................. 60 Break Statement ......................................................................................................................................... 61 Continue Statement .................................................................................................................................... 63 Pass Statement ........................................................................................................................................... 65 iv Python 8. PYTHON ─ NUMBERS .............................................................................................................. 66 Number Type Conversion ............................................................................................................................ 67 Random Number Functions ......................................................................................................................... 69 Trigonometric Functions ............................................................................................................................. 69 Mathematical Constants ............................................................................................................................. 70 9. PYTHON ─ STRINGS................................................................................................................. 71 Accessing Values in Strings .......................................................................................................................... 71 Updating Strings .......................................................................................................................................... 71 Escape Characters ....................................................................................................................................... 72 String Special Operators .............................................................................................................................. 73 String Formatting Operator ......................................................................................................................... 74 Triple Quotes .............................................................................................................................................. 76 Unicode String ............................................................................................................................................. 77 Built-in String Methods ............................................................................................................................... 78 capitalize() Method ..................................................................................................................................... 82 center(width, fillchar) Method .................................................................................................................... 82 count(str, beg= 0,end=len(string)) Method ................................................................................................. 83 decode(encoding='UTF-8',errors='strict') Method ....................................................................................... 84 encode(encoding='UTF-8',errors='strict') Method ....................................................................................... 85 endswith(suffix, beg=0, end=len(string)) Method ....................................................................................... 86 expandtabs(tabsize=8) ................................................................................................................................ 87 find(str, beg=0 end=len(string)) ................................................................................................................... 88 index(str, beg=0, end=len(string)) ............................................................................................................... 89 isalnum() Method ....................................................................................................................................... 90 isalpha() ...................................................................................................................................................... 90 v Python isdigit() ........................................................................................................................................................ 91 islower() ...................................................................................................................................................... 92 isnumeric() .................................................................................................................................................. 93 isspace() Method......................................................................................................................................... 94 istitle()......................................................................................................................................................... 95 isupper()...................................................................................................................................................... 96 join(seq) ...................................................................................................................................................... 96 len(string).................................................................................................................................................... 97 ljust(width[, fillchar]) .................................................................................................................................. 98 lower() ........................................................................................................................................................ 99 lstrip() ....................................................................................................................................................... 100 maketrans()............................................................................................................................................... 100 max(str) .................................................................................................................................................... 102 min(str) ..................................................................................................................................................... 102 replace(old, new [, max]) .......................................................................................................................... 103 rfind(str, beg=0,end=len(string)) ............................................................................................................... 104 rindex(str, beg=0, end=len(string)) ............................................................................................................ 105 rjust(width,[, fillchar]) ............................................................................................................................... 106 rstrip() ....................................................................................................................................................... 107 split(str="", num=string.count(str)) ........................................................................................................... 108 splitlines(num=string.count('\n')).............................................................................................................. 109 startswith(str, beg=0,end=len(string)) ....................................................................................................... 110 strip([chars]) ............................................................................................................................................. 111 swapcase() ................................................................................................................................................ 111 title() ......................................................................................................................................................... 112 translate(table, deletechars="") ................................................................................................................ 113 vi Python upper() ...................................................................................................................................................... 114 zfill (width) ................................................................................................................................................ 115 isdecimal()................................................................................................................................................. 116 10. PYTHON ─ LISTS .................................................................................................................... 118 Python Lists ............................................................................................................................................... 118 Accessing Values in Lists ............................................................................................................................ 118 Updating Lists ........................................................................................................................................... 119 Deleting List Elements ............................................................................................................................... 119 Basic List Operations ................................................................................................................................. 120 Indexing, Slicing, and Matrixes .................................................................................................................. 121 Built-in List Functions and Methods .......................................................................................................... 121 Cmp(list1, list2) ......................................................................................................................................... 122 len(List) ..................................................................................................................................................... 123 max(list) .................................................................................................................................................... 124 min(list) ..................................................................................................................................................... 124 List.append(obj) ........................................................................................................................................ 126 list.count(obj)............................................................................................................................................ 127 list.extend(seq) ......................................................................................................................................... 128 list.index(obj) ............................................................................................................................................ 128 list.insert(index,obj) .................................................................................................................................. 129 list.pop(obj=list[-1]) .................................................................................................................................. 130 List.remove(obj) ........................................................................................................................................ 131 List.reverse() ............................................................................................................................................. 131 list.sort([func]) .......................................................................................................................................... 132 vii ......................................................................................................................................................................................................................................................................................................................................... 139 Max(tuple) ................................ 137 Cmp(tuple1..... dict2) ............................................................................................................................................................................. 136 Indexing........................................................................... 140 Min(tuple) .......................................................................................................... 149 dict..... 143 Accessing Values in Dictionary ......................................................... 146 len(dict) .............. Python 11.....................................copy() ................................................................................................................................................................................................. PYTHON ─ TUPLES .............................................. 135 Basic Tuples Operations ..... 134 Accessing Values in Tuples .......................................................................... 141 12............................................................................... 137 Built-in Tuple Functions........................ 151 Dict.................................................................................................................................. 151 viii ..................................clear() .................................................................. 143 Updating Dictionary ............................................................................................................................................................................................................................................................................................................................................................................... 148 type() .................................................... 135 Deleting Tuple Elements ........................................................................................................................................................................................................................................... PYTHON ─ DICTIONARY................................. 145 Built-in Dictionary Functions and Methods ................................................................................................................................................................................................................................................................................................... 144 Delete Dictionary Elements ......................... tuple2) .... 147 str(dict) ........................................................................................................................................................... Slicing................................ 134 Updating Tuples ........................................................... 136 No Enclosing Delimiters................................................................................................................. 141 Tuple(seg) . 144 Properties of Dictionary Keys ...................................................................................................... and Matrixes ........................................................................ 138 Len(tuple).................................................................................................................................................................................................................................. 146 Cmp(dict1. ............ 171 time........................................................................................................................................................................... 154 Dict............................altzone .....................................................................................................................sleep(secs) ............................... 174 ix .......................... 169 time.................................................................................................................................................................................................................................gmtime([secs]) ......................................................................................items() ............................ 163 The time Module ........................ 160 Getting Current Time................................................................................................fmt='%a %b %d %H:%M:%S %Y') ................. 166 time.................................................................................... 168 time....................................................... Python Dict... 162 Getting Formatted Time ............................................................................ctime([secs]) ................................................ 157 dict...............................default=none) ........................................ 170 time......................................................... 160 What is Tick? .......................................................................................................................................................................... default=None) .................................................................... PYTHON ─ DATE AND TIME...................fromkeys() ..........................................................................................update(dict2)..................tupletime]) ...............................................................................................................................................................actime([tupletime]). 163 time............................................... 153 Dict.................................mktime(tupletime)...............................................................................................................................................................localtime([secs]).............................................................................................. 158 13....................................................................................setdefault(key.............................................................................................................................strftime(fmt[....................................values() ..........................................................keys() .......................................................................................... 168 time......clock( ) ..........................................has_key(key) .......................... 160 What is TimeTuple?.................................................................................................................... 162 Getting Calendar for a Month ......................get(key....................................................................................................................................................... 165 time.. 152 Dict............................................strptime(str............................... 155 Dict............... 156 dict................................................................................... 172 time.................................................................................................. 156 dict........................................................ 166 time............... .............................. 182 Calling a Function .................................................................. 185 Required Arguments .. 191 15........................................................................ 194 Namespaces and Scoping ............................................................................................................ 176 time........................... 193 The from................................................................................................................... 188 The Anonymous Functions ............................................................................................................... 184 Function Arguments ..............................import Statement ........................................................................ 193 The PYTHONPATH Variable ......................... 181 14....................................... 185 Keyword Arguments......................................................................................................................................... 194 The dir( ) Function ............................................................ Local variables ..................................................... 193 Locating Modules: .................................................................................................................... 192 The import Statement ............................................................................................................................ 187 Variable Length Arguments .................................................................................................................. 189 The return Statement .................................................................................................................................... 195 x ................................................................................................................................... 190 Scope of Variables ........................................................................................................................................................................................................................... 179 Other Modules and Functions ............................................................................................................................ Python time............................ 186 Default Arguments ............................................................................................................................................................ PYTHON ─ MODULES .............................tzset()................................................................................................................... 177 The calendar Module .....................................................................................................................................................................................................................................................................import * Statement: ......................................................time( ) ........ 182 Defining a Function ................................................................................................................................. 190 Global vs................. PYTHON ─ FUNCTIONS ................................................................................ 183 Passing by Reference Versus Passing by Value .......................................................................... 192 The from.................................................................................................................................................................................................................................................................. ................................................................................................................ PYTHON ─ FILES I/O ............................................................................................................................................................ 206 The remove() Method ................................................................................. 206 Directories in Python ............................................................... 199 The file Object Attributes ................................................................................................................................ 198 Reading Keyboard Input ....................................................................................................................................................... 204 Renaming and Deleting Files ................................................................................................................................................ 199 The open Function ............................................................................................................................................................................................................................................................................ 202 Reading and Writing Files ............................................................................................................................................................................................................................................................................................................................... 209 xi ............. 201 The close() Method .................................. 204 File Positions ..................................................................................................................... 199 Opening and Closing Files ........................................................................ 207 The getcwd() Method................................................................................................. 207 The mkdir() Method ......................................................................... Python The globals() and locals() Functions ................................................................................................................................................................................................................................................................................................... 205 The rename() Method ............................................................................................................................................................ 196 16.................... 198 The raw_input Function ..................................................................................................... 198 Printing to the Screen.................. 203 The write() Method ..................... 208 The rmdir() Method................................................................................................................................................................................................................................................... 196 The reload() Function ............. 198 The input Function ............................................................................................ 208 File and Directory Related Methods ............................................................................................... 207 The chdir() Method ........................................................................................... 203 The read() Method ............................................................................................................................. 196 Packages in Python ................................................... ................................................read([size]) .............................................................................................. 241 User-Defined Exceptions ....................................................................................................................................... 218 file................................................................... 221 file...............................................................................isatty() ...................................................................truncate([size]) ........................................................................................................................................................................... 222 file.................................................................................................................................................................................................................................. 225 OS Object Methods ................................................................................................................................ 211 File................................ 239 Argument of an Exception .............................................next() ......fileno() .................................................... 213 File.................................................................................................. Python file.............................................seek(offset[.................................................................................................... 235 What is Exception? .......... 240 Raising an Exception ................................................................................................................................................................readline([sizehint]) .................................................................................................................................................... 227 17............................................................................................. 238 The except Clause with Multiple Exceptions .............. 224 file.................................................................................. 242 xii ..............................................................writelines(sequence) ....................................................................................................................... 215 File......................................................................................................................................................................................... 236 Handling an Exception .................................... 216 file..................................................................................................................close() .....................................tell() ........................................................................................................................ PYTHON ─ EXCEPTIONS ..................................................................................readline([size]) ......................................... 233 Assertions in Python .......................................................................................... 219 file................................................................... 239 The try-finally Clause ................. 236 The except Clause with No Exceptions .................... 235 The assert Statement ........................................................................................flush() .................................................whence]) ................................................................................................................................................... 210 File.......................write(str) ............... 212 File.................................. 214 File.... ................................. 246 Built-In Class Attributes ......................................................................................... 255 19............................................................................................................................................... 260 Search and Replace ......................................................... 259 Matching Versus Searching .............................................................. 267 20....................................................................... 261 Regular-Expression Patterns ............................................................................................................................................................................... 249 Class Inheritance ..................................................... 270 xiii ................................................................................................................................. 257 The search Function ............................................................................................................................................................. 244 Overview of OOP Terminology .................................................................................................................................................................... 262 Regular-Expression Examples ................................................................................ 270 What is CGI? ....................................................................... PYTHON ─ CGI PROGRAMMING.... 252 Base Overloading Methods ...................................................................................................................................................................................................................................................................................................................................................................................................................................... 251 Overriding Methods ........................................................................................................................ 244 Creating Classes ............... 261 Regular-Expression Modifiers: Option Flags ......................................................................................... Python 18.......................................................................................................................................................................... 245 Creating Instance Objects ....................................................... 254 Data Hiding ......................................................... 270 Web Browsing ................................ 253 Overloading Operators .............. PYTHON ─ REGULAR EXPRESSIONS ................................................................................................. 246 Accessing Attributes .................................................................. 265 Grouping with Parentheses .................................................................................................................................................................................................................................................................................................. 248 Destroying Objects (Garbage Collection) ................................................................................................................................................................ 257 The match Function ................................................................................................................................... 267 Backreferences ................ PYTHON ─ CLASSES AND OBJECTS ... ................ 289 What is MySQLdb? ................................................................... 286 How To Raise a "File Download" Dialog Box? ............................................................................ 271 First CGI Program ........................... 281 Passing Drop Down Box Data to CGI Program ....................................................... Python CGI Architecture ...................................................................................................................................................................................................................................................................................................................... 276 Simple FORM Example: GET Method ............ PYTHON ─ DATABASE ACCESS........................................................................................................................................................................................... 290 Database Connection .................................................................................................................................................................................................................................................... 285 Retrieving Cookies........................................................ 280 Passing Text Area Data to CGI Program ................. 275 Passing Information using GET method: ........................................ 283 Using Cookies in CGI ...................................................... 284 How It Works?............................................................ 277 Passing Information Using POST Method ........................................................................ 278 Passing Checkbox Data to CGI Program .......................................................................................................................................................................................................................................................................... 273 CGI Environment Variables................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 276 Simple URL Example : Get Method ................................................................................................................................................................................................................................................................................................................................................................................................................................. 272 HTTP Header ............................ 292 xiv .............................. 284 Setting up Cookies ........................................... 274 GET and POST Methods ..................... 279 Passing Radio Button Data to CGI Program .. 288 21................................................... 271 Web Server Support and Configuration ...................................................................................... 285 File Upload Example .................. 289 How do I Install MySQLdb? ..................................................... 290 Creating Database Table ......................................... ............................................................................ 306 Further Readings .............................................................................................................................................................................................................................................................. 304 A Simple Client ............................................................................................................................................................................................................................................................................................................... 293 READ Operation ............................................................................................. 296 DELETE Operation .................................................... 313 The Threading Module ...... Python INSERT Operation ........................................................................... PYTHON ─ NETWORK PROGRAMMING .................................... 307 23..................................................... 308 Sending an HTML e-mail using Python .................................................................................... 303 Client Socket Methods .............................................................................................................................................................................................................................................................................................................................................................................................. 299 ROLLBACK Operation .......................................................................................................................................................................................................................... 310 24.................. 300 22................................................................................................... 295 Update Operation .......................................................................................................................................................................................................................................... PYTHON ─ SENDING EMAIL........ 309 Sending Attachments as an E-mail ........................... PYTHON ─ MULTITHREADING ..................................................................................... 302 What is Sockets? ......................................................................................................................................... 303 Server Socket Methods .................. 298 COMMIT Operation ............... 304 General Socket Methods ......................... 299 Disconnecting Database .. 314 xv ............................................................................................................................................................................................................................................................................................................ 304 A Simple Server ......................................................... 313 Starting a New Thread................................................................................ 302 The socket Module .......................................................... 299 Handling Errors ....................................................................................................................................................................................................... 297 Performing Transactions ................................................................................... 305 Python Internet modules ................. ......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 323 What is XML? ........................................... 323 XML Parser Architectures and APIs: ...................................................................................................................................................................................................................................................................................................................................................................................................... 317 Multithreaded Priority Queue ...................................................................... 340 Entry ...................................................................................................................................................... 319 25........ 338 Checkbutton............................................................................................. 329 26................................................................................................................. 369 xvi ................................................................................................................................................................................................................................................................................ 349 Label .............................................. 332 Tkinter Programming ............................................. 362 Message ................................................................................................ 326 Parsing XML with DOM APIs ..................................................................... 325 The parseString Method ............................................................................................................................................................................................ 344 Frame ........................................................................................................................................................................................................................................................................... PYTHON ─ GUI PROGRAMMING ........................................................................ 351 Listbox..................................................................................... 354 MenuButton..................................................................... 358 Menu ........ 366 Radiobutton .............. Python Creating Thread Using Threading Module: ............................ 325 The make_parser Method ............................. 332 Tkinter Widgets .............................................................................................................................................. 335 Canvas ............. 315 Synchronizing Threads ............................................................................................................................................................... 325 The parse Method .............................................................................................. 323 Parsing XML with SAX APIs . PYTHON ─ XML PROCESSING ........................................................................................................................................................................................................... 333 Button ... ......................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 373 Scrollbar ............................................................. 407 Geometry Management ......................... 400 Colors .......................................................................................................... 410 Python Tkinter place() Method .................................................................. 411 27............ 402 Anchors ......................................................................................................................................................................................................................... 413 Pre-Requisites for Writing Extensions ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 401 Fonts .......................................................................................... 393 LabelFrame ............................................................................................. 413 First Look at a Python Extension ...................................................... 414 xvii ....................................................... Python Scale ..........................................................................................................................................................h .......... 409 Python Tkinter grid() Method................................................................... 381 TopLevel ....................................................................... 400 Dimensions .............................................................................................................................................................................................. 390 PanelWindow ................................................................... 398 Standard Attributes....................................................... 408 Python Tkinter pack() Method .............................................................................................................................................................................. PYTHON ─ FURTHER EXTENSIONS.................................................................................................................................................................................................................................................................................................................................... 403 Relief styles ...................................................................................... 406 Cursors ...... 404 Bitmaps ............................. 387 SpinBox ............................ 413 The C Functions .............................................................. 396 tkMessageBox ................................................ 378 Text ......................................................................................................................................................... 413 The Header File Python.............................................................................................................................. ......................... 423 xviii ............................. 421 The Py_BuildValue Function ..................................................................................................................... 418 Passing Function Parameters .................................... 416 Building and Installing Extensions .................................................................................................................................................................................. 415 The Initialization Function ......................................................................................................................................................................................................................................................................................... 418 The PyArg_ParseTuple Function .......... 420 Returning Values ............... 418 Importing Extensions .......................................................................................... Python The Method Mapping Table ............................................................................................................................................................................... C++.  Python is a Beginner's Language: Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. including ABC. Python Features Python's features include:  Easy-to-learn: Python has few keywords.  Easy-to-maintain: Python's source code is fairly easy-to-maintain. Python is derived from many other languages. Python ─ Overview Python is a high-level. and a clearly defined syntax. History of Python 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. interactive and object-oriented scripting language. simple structure. Python is designed to be highly readable. and it has fewer syntactical constructions than other languages. Modula-3. This is similar to PERL and PHP. Like Perl. and other scripting languages. Python is now maintained by a core development team at the institute. 1 . Algol-68.  Easy-to-read: Python code is more clearly defined and visible to the eyes. SmallTalk. interpreted. Python is copyrighted. Unix shell. C. although Guido van Rossum still holds a vital role in directing its progress. You do not need to compile your program before executing it. Python source code is now available under the GNU General Public License (GPL).  Python is Interpreted: Python is processed at runtime by the interpreter.  Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python 1. It uses English keywords frequently where as other languages use punctuation. This allows the student to pick up the language quickly.  Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects. and Macintosh.  Interactive Mode: Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.  It provides very high-level dynamic data types and supports dynamic type checking.  Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. COM.  It supports automatic garbage collection. ActiveX. libraries.  Extendable: You can add low-level modules to the Python interpreter. few are listed below:  It supports functional and structured programming methods as well as OOP.  It can be used as a scripting language or can be compiled to byte-code for building large applications. Python  A broad standard library: Python's bulk of the library is very portable and cross-platform compatible on UNIX. Windows. Apart from the above-mentioned features. CORBA. and the X Window system of Unix.  It can be easily integrated with C. Macintosh. and windows systems. C++.  Databases: Python provides interfaces to all major commercial databases. and Java. These modules enable programmers to add to or customize their tools to be more efficient. such as Windows MFC.  GUI Programming: Python supports GUI applications that can be created and ported to many system calls. 2 . Python has a big list of good features.  Scalable: Python provides a better structure and support for large programs than shell scripting. 3 . IRIX. etc.python.)  Win 9x/NT/2000  Macintosh (Intel. Python 2. AIX. PPC. Let's understand how to set up our Python environment. Linux. is available on the official website of Python: http://www.org/.. binaries. You can download Python documentation from www. HP/UX. The documentation is available in HTML.org/doc/.python. SunOS.  Unix (Solaris. 68K)  OS/2  DOS (multiple versions)  PalmOS  Nokia mobile phones  Windows CE  Acorn/RISC OS  BeOS  Amiga  VMS/OpenVMS  QNX  VxWorks  Psion  Python has also been ported to the Java and . Python ─ Environment Python is available on a wide variety of platforms including Linux and Mac OS X. Local Environment Setup Open a terminal window and type "python" to find out if it is already installed and which version is installed. news. PDF. etc. documentation. FreeBSD. and PostScript formats.NET virtual machines Getting Python The most up-to-date and current source code. you need a C compiler to compile the source code manually.0. If the binary code for your platform is not available.  To use this installer python-XYZ. Here is a quick overview of installing Python on various platforms: Unix and Linux Installation Here are the simple steps to install Python on Unix/Linux machine. 4 . Windows Installation Here are the steps to install Python on Windows machine. You need to download only the binary code applicable for your platform and install Python./configure script  make  make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.python.org/download/. which is really easy to use.  Editing the Modules/Setup file if you want to customize some options. wait until the install is finished.  Run the downloaded file.  Follow the link to download zipped source code available for Unix/Linux.  Download and extract files.org/download/  Follow the link for the Windows installer python-XYZ. Save the installer file to your local machine and then run it to find out if your machine supports MSI.  Open a Web browser and go to http://www.python. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Just accept the default settings.  run . This brings up the Python install wizard.  Open a Web browser and go to http://www.msi file where XYZ is the version you need to install. Python Installing Python Python distribution is available for a wide variety of platforms. the Windows system must support Microsoft Installer 2.msi. and you are done. The path variable is named as PATH in Unix or Path in Windows (Unix is case- sensitive.http://www. Setting up PATH Programs and other executable files can be in many directories. the installer handles the path details.  In the bash shell (Linux): type export ATH="$PATH:/usr/local/bin/python" and press Enter. Python Macintosh Installation Recent Macs come with Python installed.nl/~jack/macpython. Setting path at Unix/Linux To add the Python directory to the path for a particular session in Unix:  In the csh shell: type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.  In the sh or ksh shell: type PATH="$PATH:/usr/local/bin/python" and press Enter.html. Note: /usr/local/bin/python is the path of the Python directory 5 . This variable contains information available to the command shell and other programs. See http://www. You can find complete installation details for Mac OS installation.cwi. Jack Jansen maintains it and you can have full access to the entire documentation at his website . you must add the Python directory to your path. which is a named string maintained by the operating system. Windows is not). MacPython is available.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. but it may be several years out of date. In Mac OS. The path is stored in an environment variable. so operating systems provide a search path that lists the directories that the OS searches for executables. For older Mac OS's before Mac OS X 10. To invoke the Python interpreter from any particular directory.3 (released in 2003).python. which can be recognized by Python: Variable Description It has a role similar to PATH. or any other system that provides you a command-line interpreter or shell window. PYTHONSTARTUP It is named as . This variable tells the Python interpreter where to locate the module files imported into a PYTHONPATH program. DOS. It should include the Python source library directory and the directories containing Python source code. 6 . It is executed every time you start the interpreter. It contains the path of an initialization file containing Python source code. Python Setting path at Windows To add the Python directory to the path for a particular session in Windows: At the command prompt: type path %path%. It is used in Windows to instruct Python to find the first case- PYTHONCASEOK insensitive match in an import statement. PYTHONPATH is sometimes preset by the Python installer.py in Unix and it contains commands that load utilities or modify PYTHONPATH.pythonrc. It is an alternative module search path. Set this variable to any value to activate it. It is usually embedded PYTHONHOME in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. Note: C:\Python is the path of the Python directory Python Environment Variables Here are important environment variables.C:\Python and press Enter. Running Python There are three different ways to start Python: (1) Interactive Interpreter You can start Python from Unix. obsolete starting with version 1. Start coding right away in the interactive interpreter. -X disable class-based built-in exceptions (just use strings). $python # Unix/Linux or python% # Unix/Linux or C:>python # Windows/DOS Here is the list of all the available command line options: Option Description -d It provides debug output. -O It generates optimized bytecode (resulting in .pyo files). -c cmd run Python script sent in as cmd string file run Python script from given file 7 . Python Enter python the command line. -v verbose output (detailed trace on import statements). -S Do not run import site to look for Python paths on startup.6. If you are not able to set up the environment properly. then you can take help from your system admin. We already have set up Python Programming environment online.  Unix: IDLE is the very first Unix IDE for Python.  Macintosh: The Macintosh version of Python along with the IDLE IDE is available from the main website. so that you can execute all the available examples online at the same time when you are learning theory.  Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI. Make sure the Python environment is properly set up and working perfectly fine.py # Windows/DOS Note: Be sure the file permission mode allows execution.py # Unix/Linuxor python% script.3 version available on CentOS flavor of Linux. Feel free to modify any example and execute it online. as in the following: $python script. downloadable as either MacBinary or BinHex'd files. (3) Integrated Development Environment You can run Python from a Graphical User Interface (GUI) environment as well.4. if you have a GUI application on your system that supports Python. Python (2) Script from the Command-line A Python script can be executed at command line by invoking the interpreter on your application. Note: All the examples given in subsequent chapters are executed with Python 2. 8 .py # Unix/Linuxor C:>python script. 2 20080704 (Red Hat 4. then you need to use print statement with parenthesis as in print ("Hello. Python 3.py. Let us write a simple Python program in a script. When the script is finished. 13:34:43) [GCC 4. >>> Type the following text at the Python prompt and press the Enter: >>> print "Hello.py file: print "Hello.4. there are some definite differences between the languages. Python!". "credits" or "license" for more information. "copyright". this produces the following result: Hello. However.4. If you are running new version of Python. Python! Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. Python files have extension . 9 .2-48)] on linux2 Type "help". Interactive Mode Programming: Invoking the interpreter without passing a script file as a parameter brings up the following prompt: $ python Python 2.3 (#1. C. First Python Program Let us execute programs in different modes of programming.. and Java. Nov 11 2010. the interpreter is no longer active.1. Type the following source code in a test.3. Python!". However in Python version 2.1. Python!"). Python ─ Basic Syntax The Python language has many similarities to Perl. Python! Let us try another way to execute a Python script. Manpower and manpower are two different identifiers in Python. underscores and digits (0 to 9). try to run this program as follows: $ chmod +x test. $. 10 . module.py # This is to make file executable $. Python does not allow punctuation characters such as @. Now. We assume that you have Python interpreter available in /usr/bin directory. Thus. and % within identifiers./test. Python is a case sensitive programming language. function. All other identifiers start with a lowercase letter. class. Here is the modified test.py file: #!/usr/bin/python print "Hello. Python!". Here are naming conventions for Python identifiers:  Class names start with an uppercase letter.py This produces the following result: Hello. Python! Python Identifiers A Python identifier is a name used to identify a variable. Python We assume that you have Python interpreter set in PATH variable.py This produces the following result: Hello.  Starting an identifier with a single leading underscore indicates that the identifier is private. or an underscore (_) followed by zero or more letters. try to run this program as follows: $ python test.  Starting an identifier with two leading underscores indicates a strongly private identifier. Now. or other object. An identifier starts with a letter A to Z or a to z. For example: 11 . which is rigidly enforced. the identifier is a language-defined special name. Python  If the identifier also ends with two trailing underscores. And exec Not Assert finally or Break for pass Class from print Continue global raise def if return del import try elif in while else is with except lambda yield Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. These are reserved words and you cannot use them as constant or variable or any other identifier names. The number of spaces in the indentation is variable. but all statements within the block must be indented the same amount. All the Python keywords contain lowercase letters only. Python Keywords The following list shows the Python keywords. Blocks of code are denoted by line indentation. print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file.exit() print "Enter '". in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks: Note: Do not try to understand the logic at this point of time. file_name sys. #!/usr/bin/python import sys try: # open file stream file = open(file_name. Just make sure you understood various blocks even if they are without braces. the following block generates an error: if True: print "Answer" print "True" else: print "Answer" print "False" Thus.close break 12 . "w") except IOError: print "There was an error writing to". Python if True: print "True" else: print "False" However. file_finish. write(file_text) file. For example: total = item_one + \ item_two + \ item_three Statements contained within the [].exit() try: file = open(file_name. 'Friday'] Quotation in Python Python accepts single ('). For example: days = ['Monday'. {}. 13 . 'Thursday'. 'Tuesday'. "r") except IOError: print "There was an error reading file" sys.close() print file_text Multi-Line Statements Statements in Python typically end with a new line. however.write("\n") file. or () brackets do not need to use the line continuation character.read() file. double (") and triple (''' or """) quotes to denote string literals. allow the use of the line continuation character (\) to denote that the line should continue. Python file.close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys. 'Wednesday'.exit() file_text = file. Python does. as long as the same type of quote starts and ends the string. For example. too. you must enter an empty physical line to terminate a multiline statement. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.""" Comments in Python A hash sign (#) that is not inside a string literal begins a comment. Python!". It is made up of multiple lines and sentences. # This is a comment. possibly with a comment. 14 . too. In an interactive interpreter session. # I said that already." paragraph = """This is a paragraph. all the following are legal: word = 'word' sentence = "This is a sentence. Python! You can type a comment on the same line after a statement or expression: name = "Madisetti" # This is again comment You can comment multiple lines as follows: # This is a comment. Python The triple quotes are used to span the string across multiple lines. Using Blank Lines A line containing only whitespace. #!/usr/bin/python # First comment print "Hello. is known as a blank line and Python totally ignores it. # This is a comment. # second comment This produces the following result: Hello. and waits for the user to take action: #!/usr/bin/python raw_input("\n\nPress the enter key to exit.") Here. Once the user presses the key. and class require a header line and a suite. ) allows multiple statements on the single line given that neither statement starts a new code block. Header lines begin the statement (with the keyword) and terminate with a colon (:) and are followed by one or more lines which make up the suite. the program ends. the statement saying “Press the enter key to exit”. which make a single code block are called suites in Python. For example: if expression : suite elif expression : suite else : suite Command Line Arguments Many programs can be run to provide you with some basic information about how they should be run. def. Here is a sample snip using the semicolon: import sys. sys. Python enables you to do this with -h: $ python -h 15 . while.stdout. Compound or complex statements.write(x + '\n') Multiple Statement Groups as Suites A group of individual statements. Multiple Statements on a Single Line The semicolon ( . This is a nice trick to keep a console window open until the user is done with an application. Python Waiting for the User The following line of the program displays the prompt. such as if. "\n\n" is used to create two new lines before displaying the actual line. x = 'foo'. argv is the list of command-line arguments.argv[0] is the program i.e. Here sys..py arg1 arg2 arg3 The Python sys module provides access to any command-line arguments via the sys. [-c cmd | -m mod | file | -] [arg] .py arg1 arg2 arg3 This produces the following result: 16 . $ python test.. len(sys.py: #!/usr/bin/python import sys print 'Number of arguments:'. ] You can also program your script in such a way that it should accept various options.  len(sys. script name.. str(sys. Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit [ etc.' print 'Argument List:'. Example Consider the following script test.argv). Python usage: python [option] . 'arguments. This serves two purposes:  sys.argv.. Accessing Command-Line Arguments Python provides a getopt module that helps you parse command-line options and arguments.argv) is the number of command-line arguments.argv) Now run above script as follows: $ python test.  options: This is the string of option letters that the script wants to recognize. To accept only long options. This module provides two functions and an exception to enable command line argument parsing.GetoptError This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none.. Following is simple syntax for this method: getopt. Parsing Command-Line Arguments Python provided a getopt module that helps you parse command-line options and arguments. '-x') or two hyphens for long options (e. options should be an empty string. 'arg3'] NOTE: As mentioned above.  Each option-and-value pair returned has the option as its first element. long_options]) Here is the detail of the parameters:  args: This is the argument list to be parsed. 'arg2'.py'. value) pairs. '--long-option'). Long options. Exception getopt. must be a list of strings with the names of the long options. with options that require an argument should be followed by a colon (:). prefixed with a hyphen for short options (e.  This method returns value consisting of two elements: the first is a list of (option. Python Number of arguments: 4 arguments. The second is the list of program arguments left after the option list was stripped. first argument is always script name and it is also being counted in number of arguments. Argument List: ['test. 17 ..  long_options: This is optional parameter and if specified. getopt.getopt(args. 'arg1'.getopt method This method parses command line options and parameter list. which require an argument should be followed by an equal sign ('='). which should be supported.g.g. options[. "--ifile"): inputfile = arg elif opt in ("-o". arg in opts: if opt == '-h': print 'test.getopt(argv.py: #!/usr/bin/python import sys.exit(2) for opt."hi:o:".argv[1:]) Now. Example Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script.py -i <inputfile> -o <outputfile>' sys.["ifile=". Usage of the script is as follows: usage: test."ofile="]) except getopt. The attributes msg and opt give the error message and related option.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys. Python The argument to the exception is a string indicating the cause of the error. inputfile print 'Output file is "'.exit() elif opt in ("-i". run above script as follows: 18 . outputfile if __name__ == "__main__": main(sys. getopt def main(argv): inputfile = '' outputfile = '' try: opts. args = getopt.py -i <inputfile> -o <outputfile> Here is the following script to test. "--ofile"): outputfile = arg print 'Input file is "'. py -i <inputfile> -o <outputfile> $ test.py -i inputfile Input file is " inputfile Output file is " 19 .py -i <inputfile> -o <outputfile> $ test.py -h usage: test. Python $ test.py -i BMP -o usage: test. decimals. you reserve some space in memory. The equal sign (=) is used to assign values to variables. Python 4. and name variables respectively. or characters in these variables. Based on the data type of a variable. The declaration happens automatically when you assign a value to a variable. This produces the following result: 100 1000. 1000.0. miles. Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. by assigning different data types to variables. 100. and "John" are the values assigned to counter. Therefore. Python ─ Variable Types Variables are nothing but reserved memory locations to store values. you can store integers.0 # A floating point name = "John" # A string print counter print miles print name Here. the interpreter allocates memory and decides what can be stored in the reserved memory. For example: #!/usr/bin/python counter = 100 # An integer assignment miles = 1000. This means when you create a variable. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable.0 John 20 . var3[.varN]]]] 21 . For example: a = b = c = 1 Here. "john" Here. Python Multiple Assignment Python allows you to assign a single value to several variables simultaneously. two integer objects with values 1 and 2 are assigned to variables a and b respectively. For example: a. a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Number objects are created when you assign a value to them. You can also assign multiple objects to multiple variables. and all three variables are assigned to the same memory location. For example: var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement. and one string object with the value "john" is assigned to the variable c.. 2. The syntax of the del statement is: del var1[.var2[.. For example.. Standard Data Types The data stored in memory can be of many types.. an integer object is created with the value 1. Python has five standard data types:  Numbers  String  List  Tuple  Dictionary Python Numbers Number data types store numeric values. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. b. c = 1. they can also be represented in octal and hexadecimal)  float (floating point real values)  complex (complex numbers) Examples Here are some examples of numbers: int long Float complex 10 51924361L 0. Python You can delete a single object or multiple objects by using the del statement. var_b Python supports four different numerical types:  int (signed integers)  long (long integers.20 45.3+e18 .54e100 3e+26J 0x69 -4721885298529L 70.j -786 0122L -21.876j -0490 535633629843L -90.6545+0J -0x260 -052318172735L -32.14j 100 -0x19323L 15. For example: del var del var_a.9 9. -.0 3.322e-36j 080 0xDEFABCECBDAECBFBAEl 32.2-E12 4.53e-7j 22 . Python Strings Strings in Python are identified as a contiguous set of characters represented in the quotation marks. where x is the real part and b is the imaginary part of the complex number. For example: #!/usr/bin/python str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string This will produce the following result: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST 23 .  A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. Python displays long integers with an uppercase L. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. Python  Python allows you to use a lowercase L with long. Python allows for either pairs of single or double quotes. but it is recommended that you use only an uppercase L to avoid confusion with the number 1. The plus (+) sign is the list concatenation operator. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists This produces the following result: ['abcd'. One difference between them is that all the items belonging to a list can be of different data type. 786. 2. Python Python Lists Lists are the most versatile of Python's compound data types. For example: #!/usr/bin/python list = [ 'abcd'.200000000000003] [123. 2.23. A list contains items separated by commas and enclosed within square brackets ([]). 786 . 'john'.23.23] [2. 70. 'john'. To some extent. 'john'] ['abcd'. while tuples are enclosed in 24 .23. 2. 786. 'john'. however.23. 70. tuples are enclosed within parentheses. 123. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed. 123. 2.200000000000003] abcd [786. A tuple consists of a number of values separated by commas. 'john'.200000000000003. and the asterisk (*) is the repetition operator. 70. 70. 'john'.2 ] tinylist = [123. lists are similar to arrays in C. Unlike lists. 'john'] Python Tuples A tuple is another sequence data type that is similar to the list. 2. 786 . 'john') print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists This produces the following result: ('abcd'. 'john'. 70. 70.23. 2. 70. 'john'.23.23. which is not allowed. 'john'. 2.23.200000000000003) (123. 'john'. 'john'. 70. 123.23) (2. 2. Similar case is possible with lists: #!/usr/bin/python tuple = ( 'abcd'. 123. because we attempted to update a tuple. Tuples can be thought of as read- only lists. 786. 786 .2 ) tinytuple = (123. 70.200000000000003. Python parentheses ( ( ) ) and cannot be updated. 'john') ('abcd'. 786.23.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list 25 . 786 . 2.23.200000000000003) abcd (786. 70. 'john') The following code is invalid with tuple. 'john'. 2. 'john'. For example: #!/usr/bin/python tuple = ( 'abcd'.2 ) list = [ 'abcd'. 'john'] Dictionaries have no concept of order among elements. 26 . It is incorrect to say that the elements are "out of order". Values. A dictionary key can be almost any Python type. 'name'] ['sales'. 'code': 6734. but are usually numbers or strings. 'name': 'john'} ['dept'.values() # Prints all the values This produces the following result: This is one This is two {'dept': 'sales'. '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. Python Python Dictionary Python's dictionaries are kind of hash table type.'code':6734. For example: #!/usr/bin/python dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john'. They work like associative arrays or hashes found in Perl and consist of key-value pairs.keys() # Prints all the keys print tinydict. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). on the other hand. 'code'. they are simply unordered. can be any arbitrary Python object. 6734. d must be a sequence of (key. chr(x) Converts an integer to a character. set(s) Converts s to a set.imag]) Creates a complex number. To convert between types. There are several built-in functions to perform conversion from one data type to another. Function Description Converts x to an integer.value) dict(d) tuples. eval(str) Evaluates a string and returns an object. you may need to perform conversions between the built-in types. repr(x) Converts object x to an expression string. base specifies the base if x is a int(x [. str(x) Converts object x to a string representation. Python Data Type Conversion Sometimes. tuple(s) Converts s to a tuple. you simply use the type name as a function. list(s) Converts s to a list. base specifies the base if x is long(x [.base] ) a string. float(x) Converts x to a floating-point number. Creates a dictionary. These functions return a new object representing the converted value. 27 . complex(real [. frozenset(s) Converts s to a frozen set.base]) string. Converts x to a long integer. oct(x) Converts an integer to an octal string. 28 . Python unichr(x) Converts an integer to a Unicode character. ord(x) Converts a single character to its integer value. hex(x) Converts an integer to a hexadecimal string. Subtraction a – b = -10 operand. * Multiplication Multiplies values on either side of the operator a * b = 200 Divides left hand operand by right hand / Division b/a=2 operand 29 . then: Operator Description Example + Addition Adds values on either side of the operator.  Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators Let us have a look on all operators one by one. Python Arithmetic Operators Assume variable a holds 10 and variable b holds 20. Types of Operators Python language supports the following types of operators. Python ─ Basic Operators Operators are the constructs which can manipulate the value of operands. Here. a + b = 30 Subtracts right hand operand from left hand . Python 5. 4 and 5 are called operands and + is called operator. Consider the expression 4 + 5 = 9. c c = a / b print "Line 4 . c c = a % b print "Line 5 .The division of operands where 9//2 = 4 and // the result is the quotient in which the digits 9.b print "Line 2 .Value of c is ".Value of c is ". Example Assume variable a holds 10 and variable b holds 20.Value of c is ".Value of c is ".0//2.0 = 4. c c = a . Python Divides left hand operand by right hand % Modulus b%a=0 operand and returns remainder Performs exponential (power) calculation on a**b =10 to ** Exponent operators the power 20 Floor Division .0 after the decimal point are removed.Value of c is ". c c = a * b print "Line 3 . then: #!/usr/bin/python a = 21 b = 10 c = 0 c = a + b print "Line 1 . c 30 .Value of c is ". c a = 2 b = 3 c = a**b print "Line 6 . it produces the following result: Line 1 .Value of c is 11 Line 3 . then the condition becomes true. (a != b) is true. similar to != operator.Value of c is 210 Line 4 .Value of c is 8 Line 7 . != If values of two operands are not equal.Value of c is 1 Line 6 .Value of c is 2 Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. Python a = 10 b = 5 c = a//b print "Line 7 . then condition becomes true. 31 . then condition becomes true. c When you execute the above program. than the value of right operand. Assume variable a holds 10 and variable b holds 20. then: Operator Description Example == If the values of two operands are equal.Value of c is ". This is then condition becomes true.Value of c is 31 Line 2 . (a <> b) is true. They are also called Relational operators. (a == b) is not true.Value of c is 2 Line 5 . > If the value of left operand is greater (a > b) is not true. <> If values of two operands are not equal. a is equal to b" 32 .a is equal to b" if ( a <> b ): print "Line 3 .a is not equal to b" else: print "Line 3 . then: #!/usr/bin/python a = 21 b = 10 c = 0 if ( a == b ): print "Line 1 . Example Assume variable a holds 10 and variable b holds 20. then condition becomes true. >= If the value of left operand is greater (a >= b) is not true. Python < If the value of left operand is less than (a < b) is true. the value of right operand.a is not equal to b" else: print "Line 2 . than or equal to the value of right operand. or equal to the value of right operand.a is not equal to b" if ( a != b ): print "Line 2 . then condition becomes true. then condition becomes true.a is equal to b" else: print "Line 1 . <= If the value of left operand is less than (a <= b) is true. Python if ( a < b ): print "Line 4 - a is less than b" else: print "Line 4 - a is not less than b" if ( a > b ): print "Line 5 - a is greater than b" else: print "Line 5 - a is not greater than b" a = 5; b = 20; if ( a <= b ): print "Line 6 - a is either less than or equal to b" else: print "Line 6 - a is neither less than nor equal to b" if ( b >= a ): print "Line 7 - b is either greater than or equal to b" else: print "Line 7 - b is neither greater than nor equal to b" When you execute the above program it produces the following result: Line 1 - a is not equal to b Line 2 - a is not equal to b Line 3 - a is not equal to b Line 4 - a is not less than b Line 5 - a is greater than b Line 6 - a is either less than or equal to b Line 7 - b is either greater than or equal to b 33 Python Python Assignment Operators Assume variable a holds 10 and variable b holds 20, then: Operator Description Example = Assigns values from right side operands to c = a + b assigns left side operand value of a + b into c += It adds right operand to the left operand c += a is equivalent and assign the result to left operand to c = c + a Add AND -= It subtracts right operand from the left c -= a is equivalent operand and assign the result to left to c = c - a Subtract AND operand *= It multiplies right operand with the left c *= a is equivalent operand and assign the result to left to c = c * a Multiply AND operand /= It divides left operand with the right c /= a is equivalent operand and assign the result to left to c = c / a Divide AND operand %= It takes modulus using two operands and c %= a is assign the result to left operand equivalent to c = c Modulus AND %a **= Performs exponential (power) calculation c **= a is on operators and assign value to the left equivalent to c = c Exponent AND operand ** a //= It performs floor division on operators and c //= a is assign value to the left operand equivalent to c = c Floor Division // a 34 Python Example Assume variable a holds 10 and variable b holds 20, then: #!/usr/bin/python a = 21 b = 10 c = 0 c = a + b print "Line 1 - Value of c is ", c c += a print "Line 2 - Value of c is ", c c *= a print "Line 3 - Value of c is ", c c /= a print "Line 4 - Value of c is ", c c = 2 c %= a print "Line 5 - Value of c is ", c c **= a print "Line 6 - Value of c is ", c c //= a print "Line 7 - Value of c is ", c When you execute the above program, it produces the following result: Line 1 - Value of c is 31 Line 2 - Value of c is 52 Line 3 - Value of c is 1092 Line 4 - Value of c is 52 35 Python Line 5 - Value of c is 2 Line 6 - Value of c is 2097152 Line 7 - Value of c is 99864 Python Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Python language. Operator Description Example & Operator copies a bit to the result if it (a & b) = 12 Binary AND exists in both operands. (means 0000 1100) It copies a bit if it exists in either (a | b) = 61 | Binary OR operand. (means 0011 1101) It copies the bit if it is set in one (a ^ b) = 49 (means ^ Binary XOR operand but not both. 0011 0001) ~ (~a ) = -61 (means 1100 0011 in 2's It is unary and has the effect of Binary complement form due 'flipping' bits. to a signed binary Ones Complement number. 36 Python << The left operands value is moved left a << 2 = 240 by the number of bits specified by the Binary Left Shift right operand. (means 1111 0000) >> The left operands value is moved a >> 2 = 15 right by the number of bits specified Binary Right Shift by the right operand. (means 0000 1111) Example #!/usr/bin/python a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b; # 12 = 0000 1100 print "Line 1 - Value of c is ", c c = a | b; # 61 = 0011 1101 print "Line 2 - Value of c is ", c c = a ^ b; # 49 = 0011 0001 print "Line 3 - Value of c is ", c c = ~a; # -61 = 1100 0011 print "Line 4 - Value of c is ", c c = a << 2; # 240 = 1111 0000 print "Line 5 - Value of c is ", c c = a >> 2; # 15 = 0000 1111 print "Line 6 - Value of c is ", c 37 Python When you execute the above program it produces the following result: Line 1 - Value of c is 12 Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 Python Logical Operators There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then: Operator Description Example and If both the operands are true then condition (a and b) is true. becomes true. Logical AND or If any of the two operands are non-zero (a or b) is true. then condition becomes true. Logical OR not Used to reverse the logical state of its Not (a and b) is false. operand. Logical NOT Python Membership Operators Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below: Operator Description Example Evaluates to true if it finds a variable in x in y, here in results in a 1 if in the specified sequence and false x is a member of sequence y. otherwise. 38 Python Evaluates to true if it does not finds a x not in y, here not in results not in variable in the specified sequence and in a 1 if x is not a member of false otherwise. sequence y. Example #!/usr/bin/python a = 10 b = 20 list = [1, 2, 3, 4, 5 ]; if ( a in list ): print "Line 1 - a is available in the given list" else: print "Line 1 - a is not available in the given list" if ( b not in list ): print "Line 2 - b is not available in the given list" else: print "Line 2 - b is available in the given list" a = 2 if ( a in list ): print "Line 3 - a is available in the given list" else: print "Line 3 - a is not available in the given list" When you execute the above program it produces the following result: Line 1 - a is not available in the given list Line 2 - b is not available in the given list Line 3 - a is available in the given list 39 Python Python Identity Operators Identity operators compare the memory locations of two objects. There are two Identity operators as explained below: Operator Description Example is Evaluates to true if the variables on either side x is y, here is results of the operator point to the same object and in 1 if id(x) equals false otherwise. id(y). is not Evaluates to false if the variables on either x is not y, here is side of the operator point to the same object not results in 1 if id(x) and true otherwise. is not equal to id(y). Example #!/usr/bin/python a = 20 b = 20 if ( a is b ): print "Line 1 - a and b have same identity" else: print "Line 1 - a and b do not have same identity" if ( id(a) == id(b) ): print "Line 2 - a and b have same identity" else: print "Line 2 - a and b do not have same identity" b = 30 if ( a is b ): print "Line 3 - a and b have same identity" else: print "Line 3 - a and b do not have same identity" 40 a and b do not have same identity Line 4 .a and b have same identity" When you execute the above program it produces the following result: Line 1 .a and b have same identity Line 3 .a and b do not have same identity Python Operators Precedence The following table lists all operators from highest precedence to lowest. Ccomplement. Operator Description ** Exponentiation (raise to the power) ~+. Python if ( a is not b ): print "Line 4 . Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^| Bitwise exclusive `OR' and regular `OR' <= < > >= Comparison operators 41 . unary plus and minus (method names for the last two are +@ and -@) * / % // Multiply.a and b have same identity Line 2 .a and b do not have same identity" else: print "Line 4 . modulo and floor division +. divide. For example. here. those with the lowest appear at the bottom. e 42 . not 20 because operator * has higher precedence than +. e e = ((a + b) * c) / d # (30 * 15 ) / 5 print "Value of ((a + b) * c) / d is ". Example #!/usr/bin/python a = 20 b = 10 c = 15 d = 5 e = 0 e = (a + b) * c / d #( 30 * 15 ) / 5 print "Value of (a + b) * c / d is ". Here. # (30) * (15/5) print "Value of (a + b) * (c / d) is ". Python <> == != Equality operators = %= /= //= -= += Assignment operators *= **= is is not Identity operators in not in Membership operators not or and Logical operators Operator precedence affects how an expression is evaluated. operators with the highest precedence appear at the top of the table. x = 7 + 3 * 2. x is assigned 13. e e = (a + b) * (c / d). so it first multiplies 3*2 and then adds into 7. e When you execute the above program. it produces the following result: Value of (a + b) * c / d is 90 Value of ((a + b) * c) / d is 90 Value of (a + b) * (c / d) is 90 Value of a + (b * c) / d is 50 43 . Python e = a + (b * c) / d. # 20 + (150/5) print "Value of a + (b * c) / d is ". Python ─ Decision Making Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Python programming language provides following types of decision making statements. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise. Following is the general form of a typical decision making structure found in most of the programming languages: Python programming language assumes any non-zero and non-null values as TRUE. Python 6. and if it is either zero or null. Statement Description if statement consists of a boolean expression followed by one or if statements more statements. 44 . Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. Click the following links to check their detail. then it is assumed as FALSE value. nested if You can use one if or else if statement inside another if or else statements if statement(s). Flow Diagram 45 . If Statement It is similar to that of other languages. then the block of statement(s) inside the if statement is executed.else statements executes when the boolean expression is FALSE. Syntax if expression: statement(s) If the boolean expression evaluates to TRUE. which if. Python if statement can be followed by an optional else statement.. If boolean expression evaluates to FALSE. then the first set of code after the end of the if statement(s) is executed. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison.. Python Example #!/usr/bin/python var1 = 100 if var1: print "1 .Got a true expression value" print var1 var2 = 0 if var2: print "2 . Syntax The syntax of the if.. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. it produces the following result: 1 . The else statement is an optional statement and there could be at most only one else statement following if.Got a true expression value 100 Good bye! If…else Statement An else statement can be combined with an if statement.Got a true expression value" print var2 print "Good bye!" When the above code is executed..else statement is: if expression: statement(s) else: statement(s) 46 . Python Flow Diagram Example #!/usr/bin/python var1 = 100 if var1: print "1 .Got a true expression value" print var1 else: print "1 .Got a false expression value" print var1 var2 = 0 if var2: print "2 .Got a true expression value" print var2 47 . Got a false expression value" print var2 print "Good bye!" When the above code is executed.. for which there can be at most one statement. However.Got a false expression value 0 Good bye! The elif Statement The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else. there can be an arbitrary number of elif statements following an if. but we can use if. it produces the following result: 1 . Syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) Core Python does not provide switch or case statements as in other languages. the elif statement is optional.statements to simulate switch case as follows: 48 . Python else: print "2 .Got a true expression value 100 2 .. unlike else.elif.. it produces the following result: 3 .Got a true expression value" print var elif var == 150: print "2 . Python Example #!/usr/bin/python var = 100 if var == 200: print "1 .Got a true expression value" print var else: print "4 .Got a true expression value 100 Good bye! Single Statement Suites If the suite of an if clause consists only of a single line. it may go on the same line as the header statement.Got a true expression value" print var elif var == 100: print "3 . Here is an example of a one-line if clause: 49 .Got a false expression value" print var print "Good bye!" When the above code is executed. it produces the following result: Value of expression is 100 Good bye! 50 . Python #!/usr/bin/python var = 100 if ( var == 100 ) : print "Value of expression is 100" print "Good bye!" When the above code is executed. for or do. It tests the condition before executing the loop body. 51 . statements are executed sequentially: The first statement in a function is executed first. The following diagram illustrates a loop statement: Python programming language provides following types of loops to handle looping requirements.while nested loops loop. and so on.. A loop statement allows us to execute a statement or group of statements multiple times. You can use one or more loop inside any another while. Programming languages provide various control structures that allow for more complicated execution paths. Loop Type Description Repeats a statement or group of statements while a given condition is while loop TRUE. Executes a sequence of statements multiple times and abbreviates the for loop code that manages the loop variable. Python ─ Loops In general. followed by the second. There may be a situation when you need to execute a block of code several number of times. Python 7. Flow Diagram 52 . The loop iterates while the condition is true. all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. statement(s) may be a single statement or a block of statements. The condition may be any expression. When the condition becomes false. program control passes to the line immediately following the loop. Syntax The syntax of a while loop in Python programming language is: while expression: statement(s) Here. In Python. and true is any non-zero value. Python uses indentation as its method of grouping statements. Python While Loop A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Such a loop is called an infinite loop. the current value of the index count is displayed and then increased by 1. count count = count + 1 print "Good bye!" When the above code is executed. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. 53 . Example #!/usr/bin/python count = 0 while (count < 9): print 'The count is:'. This results in a loop that never ends. it produces the following result: The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye! The block here. is executed repeatedly until count is no longer less than 9. Python Here. key point of the while loop is that the loop might not ever run. consisting of the print and increment statements. With each iteration. the loop body will be skipped and the first statement after the while loop will be executed. The Infinite Loop A loop becomes infinite loop if a condition never becomes FALSE. When the condition is tested and the result is false. Using else Statement with Loops Python supports to have an else statement associated with a loop statement. the else statement is executed when the condition becomes false. it produces the following result: Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number between :Traceback (most recent call last): File "test.py". the else statement is executed when the loop has exhausted iterating the list.  If the else statement is used with a while loop. in <module> num = raw_input("Enter a number :") KeyboardInterrupt Above example goes in an infinite loop and you need to use CTRL+C to exit the program. line 5.  If the else statement is used with a for loop. 54 . #!/usr/bin/python var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ". Python An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. num print "Good bye!" When the above code is executed. it produces the following result: 0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is not less than 5 Single Statement Suites Similar to the if statement syntax. " is less than 5" count = count + 1 else: print count. Here is the syntax and example of a one-line while clause: #!/usr/bin/python flag = 1 while (flag): print 'Given flag is really true!' print "Good bye!" It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit. otherwise else statement gets executed. " is not less than 5" When the above code is executed. it may be placed on the same line as the while header. #!/usr/bin/python count = 0 while count < 5: print count. if your while clause consists only of a single statement. Python The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5. 55 . 'apple'. Syntax for iterating_var in sequence: statements(s) If a sequence contains an expression list. the statements block is executed. it is evaluated first. 'mango'] 56 . Each item in the list is assigned to iterating_var. Python For Loop It has the ability to iterate over the items of any sequence. such as a list or a string. Flow Diagram Example #!/usr/bin/python for letter in 'Python': # First Example print 'Current Letter :'. Next. letter fruits = ['banana'. and the statement(s) block is executed until the entire sequence is exhausted. Then. the first item in the sequence is assigned to the iterating variable iterating_var. fruit print "Good bye!" When the above code is executed. it produces the following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! Iterating by Sequence Index An alternative way of iterating through each item is by index offset into the sequence itself. 'apple'. Python for fruit in fruits: # Second Example print 'Current fruit :'. 'mango'] for index in range(len(fruits)): print 'Current fruit :'. it produces the following result: Current fruit : banana Current fruit : apple Current fruit : mango Good bye! 57 . Following is a simple example: #!/usr/bin/python fruits = ['banana'. fruits[index] print "Good bye!" When the above code is executed. The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20. the else statement is executed when the loop has exhausted iterating the list.20): #to iterate between 10 to 20 for i in range(2.  If the else statement is used with a while loop. which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over. we took the assistance of the len() built-in function.i. it produces the following result: 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number 58 . 'is a prime number' When the above code is executed.num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num. Python Here. the else statement is executed when the condition becomes false. Using else Statement with Loops Python supports to have an else statement associated with a loop statement.j) break #to move to the next number.  If the else statement is used with a for loop. the #first FOR else: # else part of the loop print num. #!/usr/bin/python for num in range(10. it produces following result: 59 . Example The following program uses a nested for loop to find the prime numbers from 2 to 100: #!/usr/bin/python i = 2 while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j) : print i. Following section shows few examples to illustrate the concept. Syntax for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s) The syntax for a nested while loop statement in Python programming language is as follows: while expression: while expression: statement(s) statement(s) A final note on loop nesting is that you can put any type of loop inside of any other type of loop. Python Nested Loops Python programming language allows to use one loop inside another loop. " is prime" i = i + 1 print "Good bye!" When the above code is executed. For example a for loop can be inside a while loop or vice versa. Python 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime Good bye! Loop Control Statements Loop control statements change execution from its normal sequence. 60 . When execution leaves a scope. Click the following links to check their detail. all automatic objects that were created in that scope are destroyed. Python supports the following control statements. The break statement can be used in both while and for loops. Python Control Description Statement Terminates the loop statement and transfers execution to the break statement statement immediately following the loop. continue Causes the loop to skip the remainder of its body and statement immediately retest its condition prior to reiterating. Syntax The syntax for a break statement in Python is as follows: break 61 . just like the traditional break statement in C. The pass statement in Python is used when a statement is pass statement required syntactically but you do not want any command or code to execute. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. the break statement stops the execution of the innermost loop and start executing the next line of code after the block. Break Statement It terminates the current loop and resumes execution at the next statement. If you are using nested loops. Python Flow Diagram Example #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :'. var var = var -1 if var == 5: break print "Good bye!" 62 . letter var = 10 # Second Example while var > 0: print 'Current variable value :'. Syntax continue Flow Diagram 63 . The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops. Python When the above code is executed. it produces the following result: Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye! Continue Statement It returns the control to the beginning of the while loop. var print "Good bye!" When the above code is executed. it produces the following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Current variable value : 4 Current variable value : 3 Current variable value : 2 Current variable value : 1 Current variable value : 0 Good bye! 64 . Python Example #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :'. letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :'. Python Pass Statement It is used when a statement is required syntactically but you do not want any command or code to execute. letter print "Good bye!" When the above code is executed. but has not been written yet (e. The pass statement is a null operation. The pass is also useful in places where your code will eventually go. nothing happens when it executes.. in stubs for example): Syntax pass Example #!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :'. it produces following result: Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! 65 .g. They are immutable data types. For example: var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement. var_b Python supports four different numerical types:  int (signed integers): They are often called just integers or ints... and the imaginary part is b..varN]]]] You can delete a single object or multiple objects by using the del statement.var3[. 66 .  complex (complex numbers) : are of the form a + bJ.. Floats may also be in scientific notation. means that changing the value of a number data type results in a newly allocated object. The real part of the number is a. they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Python ─ Numbers Number data types store numeric values. written like integers and followed by an uppercase or lowercase L. Complex numbers are not used much in Python programming.  long (long integers): Also called longs. they are integers of unlimited size.5e2 = 2. are positive or negative whole numbers with no decimal point.  float (floating point real values) : Also called floats. Number objects are created when you assign a value to them. For example: del var del var_a. where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). with E or e indicating the power of 10 (2.5 x 102 = 250). Python 8.var2[. The syntax of the del statement is: del var1[. Number Type Conversion Python converts numbers internally in an expression containing mixed types to a common type for evaluation.14j 100 -0x19323L 15.876j -0490 535633629843L -90.  Type long(x) to convert x to a long integer. But sometimes.20 45. Python displays long integers with an uppercase L.54e100 3e+26J 0x69 -4721885298529L 70.  A complex number consists of an ordered pair of real floating point numbers denoted by a + bj.  Type int(x) to convert x to a plain integer. where a is the real part and b is the imaginary part of the complex number.0 3.6545+0J -0x260 -052318172735L -32.  Type float(x) to convert x to a floating-point number. but it is recommended that you use only an uppercase L to avoid confusion with the number 1.2-E12 4.322e-36j 080 0xDEFABCECBDAECBFBAEL 32.53e-7j  Python allows you to use a lowercase L with long. -. 67 .9 9.3+e18 . Python Examples Here are some examples of numbers: int Long float complex 10 51924361L 0. you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.j -786 0122L -21. max(x1.) The largest of its arguments: the value closest to positive infinity min(x1.0... x2. ceil(x) The ceiling of x: the smallest integer not less than x cmp(x.. Both parts have modf(x) the same sign as x. for x> 0 log10(x) The base-10 logarithm of x for x> 0. y) -1 if x < y.0 and round(-0. Python rounds away from round(x [. floor(x) The floor of x: the largest integer not greater than x log(x) The natural logarithm of x. pow(x. 0 if x == y. y) The value of x**y.. or 1 if x > y exp(x) The exponential of x: ex fabs(x) The absolute value of x. Python  Type complex(x) to convert x to a complex number with real part x and imaginary part zero.5) is -1. 68 .  Type complex(x. Function Returns ( description ) abs(x) The absolute value of x: the (positive) distance between x and zero.. x and y are numeric expressions Mathematical Functions Python includes following functions that perform mathematical calculations.) The smallest of its arguments: the value closest to negative infinity The fractional and integer parts of x in a two-item tuple.5) is 1. x2.n]) zero as a tie-breaker: round(0. The integer part is returned as a float.. x rounded to n digits from the decimal point. y) to convert x and y to a complex number with real part x and imaginary part y. such that x is less than or equal to r uniform(x. randrange ([start.] stop [. stop. or string. Python sqrt(x) The square root of x for x > 0 Random Number Functions Random numbers are used for games. A random float r. testing. such that 0 is less than or equal to r random() and r is less than 1 Sets the integer starting value used in generating seed([x]) random numbers. shuffle(lst) Randomizes the items of a list in place. simulations. in radians. A randomly selected element from range(start. Call this function before calling any other random module function. Function Description acos(x) Return the arc cosine of x. and privacy applications.step]) step) A random float r. Returns None. Function Description choice(seq) A random item from a list. tuple. y) and r is less than y Trigonometric Functions Python includes following functions that perform trigonometric calculations. Python includes following functions that are commonly used. in radians. security. 69 . Returns None. asin(x) Return the arc sine of x. radians(x) Converts angle x from degrees to radians. Python atan(x) Return the arc tangent of x. y) Return the Euclidean norm. e The mathematical constant e. 70 . in radians. hypot(x. tan(x) Return the tangent of x radians. degrees(x) Converts angle x from radians to degrees. Mathematical Constants The module also defines two mathematical constants: Constants Description pi The mathematical constant pi. cos(x) Return the cosine of x radians. x) Return atan(y / x). atan2(y. sin(x) Return the sine of x radians. sqrt(x*x + y*y). in radians. Python ─ Strings Strings are amongst the most popular types in Python. var1[0] print "var2[1:5]: ". Creating strings is as simple as assigning a value to a variable. these are treated as strings of length one. thus also considered a substring. We can create them simply by enclosing characters in quotes. it produces the following result: var1[0]: H var2[1:5]: ytho Updating Strings You can "update" an existing string by (re)assigning a variable to another string. use the square brackets for slicing along with the index or indices to obtain your substring. For example: #!/usr/bin/python var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ". Python 9. Python treats single quotes the same as double quotes. The new value can be related to its previous value or to a completely different string altogether. For example: #!/usr/bin/python var1 = 'Hello World!' 71 . For example: var1 = 'Hello World!' var2 = "Python Programming" Accessing Values in Strings Python does not support a character type. To access substrings. var2[1:5] When the above code is executed. Python print "Updated String :.". where n is in the range 0. var1[:6] + 'Python' When the above code is executed.7 \r 0x0d Carriage return \s 0x20 Space 72 . Hello Python Escape Characters Following table is a list of escape or non-printable characters that can be represented with backslash notation. Backslash Hexadecimal Description notation character \a 0x07 Bell or alert \b 0x08 Backspace \cx Control-x \C-x Control-x \e 0x1b Escape \f 0x0c Formfeed \M-\C-x Meta-Control-x \n 0x0a Newline \nnn Octal notation. in a single quoted as well as double quoted strings. it produces the following result: Updated String :. An escape character gets interpreted. Returns true if a character in H in a will give 1 exists in the given string Membership .F String Special Operators Assume string variable a holds 'Hello' and variable b holds 'Python'.Gives the character from the given [] a[1] will give e index Range Slice .9. a*2 will give - * concatenating multiple copies of the same HelloHello string Slice .Adds values on either side a + b will give + of the operator HelloPython Repetition .Suppresses actual meaning of Escape characters.Returns true if a character not in M not in a will give 1 does not exist in the given string Raw String . Python \t 0x09 Tab \v 0x0b Vertical tab \x Character x Hexadecimal notation. \xnn a. where n is in the range 0.Gives the characters from the [:] a[1:4] will give ell given range Membership .Creates new strings.f. then: Operator Description Example Concatenation . or A. The syntax for raw print r'\n' prints \n r/R strings is exactly the same as for normal and print R'\n'prints \n strings with the exception of the raw string 73 . Python operator. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. the letter "r. 21) When the above code is executed.Performs String formatting See at next section String Formatting Operator One of Python's coolest features is the string format operator %. Following is a simple example: #!/usr/bin/python print "My name is %s and weight is %d kg!" % ('Zara'." which precedes the quotation marks. it produces the following result: My name is Zara and weight is 21 kg! Here is the list of complete set of symbols which can be used along with %: Format Symbol Conversion %c character %s string conversion via str() prior to formatting %i signed decimal integer %d signed decimal integer %u unsigned decimal integer %o octal integer %x hexadecimal integer (lowercase letters) 74 . % Format . left justification + display the sign <sp> leave a blank space before a positive number # add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X'. 0 pad from left with zeros (instead of spaces) % '%%' leaves you with a single literal '%' (var) mapping variable (dictionary arguments) 75 . Python %X hexadecimal integer (UPPERcase letters) %e exponential notation (with lowercase 'e') %E exponential notation (with UPPERcase 'E') %f floating point real number %g the shorter of %f and %e %G the shorter of %f and %E Other supported symbols and functionality are listed in the following table: Symbol Functionality * argument specifies width or precision . depending on whether 'x' or 'X' were used. right down to the last NEWLINE at the end of the string between the "up. m is the minimum total width and n is the number of digits to display after the decimal point (if appl. or just a NEWLINE within the variable assignment will also show up.) Triple Quotes Python's triple quotes comes to the rescue by allowing strings to span multiple lines. 76 . The syntax for triple quotes consists of three consecutive single or double quotes. #!/usr/bin/python para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n): this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. or just a NEWLINE within the variable assignment will also show up. """ print para_str. NEWLINEs within the string. whether explicitly given like this within the brackets [ ]. it produces the following result. whether explicitly given like this within the brackets [ \n ]. TABs. including verbatim NEWLINEs. When the above code is executed. NEWLINEs within the string.n. and any other special characters. Python m. Note how every single special character has been converted to its printed form." and closing triple quotes. while Unicode strings are stored as 16-bit Unicode. it produces the following result: C:\\nowhere Unicode String Normal strings in Python are stored internally as 8-bit ASCII. We would put expression in r'expression' as follows: #!/usr/bin/python print r'C:\\nowhere' When the above code is executed. it produces the following result: Hello. it produces the following result: C:\nowhere Now let's make use of raw string. Unicode strings use the prefix u. Python Raw strings do not treat the backslash as a special character at all. I'll restrict my treatment of Unicode strings to the following: #!/usr/bin/python print u'Hello. This allows for a more varied set of characters. 77 . world!' When the above code is executed. Every character you put into a raw string stays the way you wrote it: #!/usr/bin/python print 'C:\\nowhere' When the above code is executed. just as raw strings use the prefix r. including special characters from most languages in the world. world! As you can see. beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting 8 index beg and ending index end are given returns index if found and -1 otherwise. returns true if so and false otherwise. decode(encoding='UTF-8'. beg=0. Python Built-in String Methods Python includes the following built-in methods to manipulate strings: Sr. expandtabs(tabsize=8) 7 Expands tabs in string to multiple spaces. fillchar) 2 Returns a space-padded string with the original string centered to a total of width columns. default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. find(str. Methods with Description capitalize() 1 Capitalizes first letter of string.errors='strict') 5 Returns encoded string version of string. on error.errors='strict') 4 Decodes the string using the codec registered for encoding. end=len(string)) Determines if string or a substring of string (if starting index beg and 6 ending index end are given) ends with suffix.end=len(string)) 3 Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given. endswith(suffix. count(str. encoding defaults to the default string encoding. defaults to 8 spaces per tab if tabsize not provided. center(width. No. beg= 0. 78 . encode(encoding='UTF-8'. but raises an exception if str not found. Python index(str. 79 . len(string) 19 Returns the length of the string. istitle() 16 Returns true if string is properly "titlecased" and false otherwise. beg=0. join(seq) 18 Merges (concatenates) the string representations of elements in sequence seq into a string. with separator string. isspace() 15 Returns true if string contains only whitespace characters and false otherwise. isalnum() 10 Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. islower() 13 Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. isalpha() 11 Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. isnumeric() 14 Returns true if a unicode string contains only numeric characters and false otherwise. isupper() 17 Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. end=len(string)) 9 Same as find(). isdigit() 12 Returns true if string contains only digits and false otherwise. Python ljust(width[.end=len(string)) 27 Same as find(). fillchar]) 20 Returns a space-padded string with the original string left-justified to a total of width columns. but search backwards in string. lower() 21 Converts all uppercase letters in string to lowercase. fillchar]) 29 Returns a space-padded string with the original string right-justified to a total of width columns. end=len(string)) 28 Same as index(). maketrans() 23 Returns a translation table to be used in translate function. but search backwards in string. rjust(width. 80 . beg=0.[. rstrip() 30 Removes all trailing whitespace of string. rindex( str. new [. max]) 26 Replaces all occurrences of old in string with new or at most max occurrences if max given. lstrip() 22 Removes all leading whitespace in string. beg=0. replace(old. max(str) 24 Returns the max alphabetical character from the string str. min(str) 25 Returns the min alphabetical character from the string str. rfind(str. returns true if so and false otherwise. that is. num=string. translate(table. deletechars="") 37 Translates string according to translation table str(256 chars). Python split(str="". zfill() retains any sign given (less one zero). swapcase() 35 Inverts case for all letters in string. zfill (width) Returns original string leftpadded with zeros to a total of width 39 characters. split into at most num substrings if given. strip([chars]) 34 Performs both lstrip() and rstrip() on string. beg=0.count(str)) 31 Splits string according to delimiter str (space if not provided) and returns list of substrings. upper() 38 Converts lowercase letters in string to uppercase.count('\n')) 32 Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed. intended for numbers. removing those in the del string. startswith(str. isdecimal() 40 Returns true if a unicode string contains only decimal characters and false otherwise.end=len(string)) Determines if string or a substring of string (if starting index beg and 33 ending index end are given) starts with substring str. all words begin with uppercase and the rest are lowercase. 81 . title() 36 Returns "titlecased" version of string. splitlines( num=string. capitalize() Result str. Default filler is a space.. Syntax str..  fillchar -. fillchar) Method The method center() returns centered in a string of length width.capitalize() : This is string example. Padding is done using the specified fillchar.capitalize() Parameters NA Return Value string Example #!/usr/bin/python str = "this is string example..This is the total width of the string.wow!!!". str. 82 .wow!!! center(width.This is the filler character.. fillchar]) Parameters  width -.center(width[.. print "str. Python capitalize() Method It returns a copy of the string with only its first character capitalized.. Syntax str.capitalize() : ". .center(40. Example #!/usr/bin/python str = "this is string example..Search ends from this index. First character starts from 0 index.center(40. 'a') : aaaathis is string example. Optional arguments start and end are interpreted as in slice notation. By default search ends at the last index.  end -. Return Value Centered in a string of length width. end]..wow!!!".end=len(string)) Parameters  sub -.center(40.. start= 0. First character starts from 0 index..end=len(string)) Method The method count() returns the number of occurrences of substring sub in the range [start.Search starts from this index. str. Example #!/usr/bin/python str = "this is string example.count(sub.  start -.This is the substring to be searched. 'a') : ".. 83 .wow!!!". Syntax str. beg= 0. 'a') Result str..wow!!!aaaa count(str. By default search starts from 0 index. Python Return Value This method returns centered in a string of length width... print "str. For a list of all encoding schemes please visit: Standard Encodings.count(sub) Result str.count(sub) : ". print "Encoded String: " + str. 'backslashreplace' and any other name registered via codecs.This may be given to set a different error handling scheme. It defaults to the default string encoding. 'xmlcharrefreplace'. 40) : ". str = str. print "str.register_error(). 40) : 2 str. 4.count(sub.'strict'). Return Value Decoded string. 4. 4.wow!!!". meaning that encoding errors raise a UnicodeError. 'replace'.count(sub.encode('base64'. 4. str..errors='strict') Method The method decode() decodes the string using the codec registered for encoding.This is the encodings to be used.. 84 . Other possible values are 'ignore'.  errors -. str. The default for errors is 'strict'. Example #!/usr/bin/python str = "this is string example. print "str.count(sub. 40) : 1 decode(encoding='UTF-8'.. Syntax str.errors='strict') Parameters  encoding -. 40) sub = "wow". Python sub = "i".count(sub.decode(encoding='UTF-8'. encode(encoding='UTF-8'. Python print "Decoded String: " + str.. Default encoding is the current default string encoding... print "Encoded String: " + str.decode('base64'.'strict') Result Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE= Decoded String: this is string example.  errors -. 'backslashreplace' and any other name registered via codecs.This may be given to set a different error handling scheme. The default for errors is 'strict'. 'xmlcharrefreplace'. 'replace'. Return Value Encoded string... Example #!/usr/bin/python str = "this is string example. meaning that encoding errors raise a UnicodeError.This is the encodings to be used.wow!!!". The errors may be given to set a different error handling scheme. Other possible values are 'ignore'.encode('base64'.errors='strict') Method The method encode() returns an encoded version of the string.register_error().'strict') Result Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE= 85 . Syntax str.wow!!! encode(encoding='UTF-8'.errors='strict') Parameters  encoding -. For a list of all encoding schemes please visit Standard Encodings..  end -. 2. 4). end]]) Parameters  suffix -. suffix = "is".The slice begins from here.. end=len(string)) Method It returns True if the string ends with the specified suffix. suffix = "wow!!!". 2. print str.20).  start -.endswith(suffix[.endswith(suffix. Result True True True False 86 .This could be a string or could also be a tuple of suffixes to look for.endswith(suffix).wow!!!". Example #!/usr/bin/python str = "this is string example. print str.endswith(suffix. otherwise return False optionally restricting the matching with the given indices start and end.. beg=0. Python endswith(suffix. otherwise FALSE. 6).The slice ends here. print str. print str. Syntax str. start[.. Return Value TRUE if the string ends with the specified suffix.endswith(suffix. .wow!!! 87 . Syntax str.wow!!! Double exapanded tab: this is string example.e.expandtabs(16). Result Original string: this is string example.expandtabs(tabsize=8) Parameters  tabsize -. '\t' have been expanded using spaces. print "Defualt exapanded tab: " + str. '\t' are expanded using spaces.. optionally using the given tabsize (default 8).expandtabs().. print "Double exapanded tab: " + str.This specifies the number of characters to be replaced for a tab character '\t'....wow!!!".. print "Original string: " + str. Python expandtabs(tabsize=8) It returns a copy of the string in which tab characters ie.wow!!! Defualt exapanded tab: this is string example. Example #!/usr/bin/python str = "this is\tstring example...... Return Value  This method returns a copy of the string in which tab characters i.. 10).find(str2. print str1. by default its 0. print str1. Python find(str. print str1. beg=0 end=len(string)) It determines if string str occurs in string. Example The following example shows the usage of find() method.find(str2)..This is the starting index.This specifies the string to be searched. by default its equal to the lenght of the string..  beg -. Result 15 15 -1 88 . or in a substring of string if starting index beg and ending index end are given.  end -. beg=0 end=len(string)) Parameters  str -.wow!!!". Return Value Index if found and -1 otherwise.This is the ending index. str2 = "exam".find(str2.find(str. #!/usr/bin/python str1 = "this is string example. 40).. Syntax str. by default its 0. print str1. but raises an exception if sub is not found. Example #!/usr/bin/python str1 = "this is string example.py". by default its equal to the length of the string. 10). str2 = "exam". This method is same as find().index(str2). ValueError: substring not found shell returned 1 89 . in print str1. print str1. Syntax str.  end -.This specifies the string to be searched.This is the ending index. Python index(str.index(str.index(str2. print str1.index(str2. end=len(string)) It determines if string str occurs in string or in a substring of string if starting index beg and ending index end are given. Return Value Index if found otherwise raises an exception if str is not found.index(str2..wow!!!". 40).. 40).. Result 15 15 Traceback (most recent call last): File "test.  beg -. beg=0 end=len(string)) Parameters  str -.This is the starting index. beg=0. line 8. Python isalnum() Method It checks whether the string consists of alphanumeric characters.isa1num() Parameters NA Return Value TRUE if all characters in the string are alphanumeric and there is at least one character.isalpha() 90 . Syntax str..isalnum(). FASLE otherwise. print str. str = "this is string example.isalnum()...wow!!!". Syntax Following is the syntax for islpha() method: str. Example #!/usr/bin/python str = "this2009". # No space in this string print str. Result True False isalpha() The method isalpha() checks whether the string consists of alphabetic characters only. false otherwise.. it produces following result: True False isdigit() The method isdigit() checks whether the string consists of digits only. false otherwise. 91 . Python Parameters  NA Return Value This method returns true if all characters in the string are alphabetic and there is at least one character...wow!!!". print str.isalpha(). Example The following example shows the usage of isalpha() method. #!/usr/bin/python str = "this". When we run above program.isdigit() Parameters  NA Return Value This method returns true if all characters in the string are digits and there is at least one character. Syntax Following is the syntax for isdigit() method: str. # No space & digit in this string print str.isalpha(). str = "this is string example. 92 . # Only digit in this string print str. str = "this is string example. Python Example The following example shows the usage of isdigit() method.isdigit().islower() Parameters  NA Return Value This method returns true if all cased characters in the string are lowercase and there is at least one cased character. #!/usr/bin/python str = "123456". false otherwise. it produces following result: True False islower() Description The method islower() checks whether all the case-based characters (letters) of the string are lowercase. Syntax Following is the syntax for islower() method: str. When we run above program..wow!!!".. print str..isdigit(). islower(). When we run above program.islower()..isnumeric() Parameters  NA Return Value This method returns true if all characters in the string are numeric. 93 . Note: To define a string as Unicode. false otherwise. print str. Python Example The following example shows the usage of islower() method. Below is the example.wow!!!". This method is present only on unicode objects.. Syntax Following is the syntax for isnumeric() method: str. str = "this is string example.wow!!!"... print str. it produces following result: False True isnumeric() Description The method isnumeric() checks whether the string consists of only numeric characters... one simply prefixes a 'u' to the opening quotation mark of the assignment. #!/usr/bin/python str = "THIS is string example. print str.isnumeric().isnumeric()..isspace(). When we run above program. print str. str = u"23443434".. false otherwise.. #!/usr/bin/python str = " ".isspace(). Syntax Following is the syntax for isspace() method: str. #!/usr/bin/python str = u"this2009". 94 . print str. Python Example The following example shows the usage of isnumeric() method. print str. str = "This is string example.isspace() Parameters  NA Return Value This method returns true if there are only whitespace characters in the string and there is at least one character. it produces following result: False True isspace() Method The method isspace() checks whether the string consists of whitespace.wow!!!". Example The following example shows the usage of isspace() method. . print str. Python When we run above program. it produces following result: True False 95 . str = "This is string example..wow!!!". Example The following example shows the usage of istitle() method.istitle(). Syntax Following is the syntax for istitle() method: str..Wow!!!".istitle().. When we run above program..It returns false otherwise. for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. it produces following result: True False istitle() The method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase.istitle() Parameters  NA Return Value This method returns true if the string is a titlecased string and there is at least one character. print str. #!/usr/bin/python str = "This Is String Example. WOW!!!"...isupper(). print str. #!/usr/bin/python str = "THIS IS STRING EXAMPLE.isupper() Parameters NA Return Value This method returns true if all cased characters in the string are uppercase and there is at least one cased character.. Example The following example shows the usage of isupper() method.. str = "THIS is string example. print str. Python isupper() The method isupper() checks whether all the case-based characters (letters) of the string are uppercase. false otherwise. When we run above program.isupper().. it produces following result: True False join(seq) Description The method join() returns a string in which the string elements of sequence have been joined by str separator. 96 . Syntax Following is the syntax for isupper() method: str..wow!!!". "c"). print str. Python Syntax Following is the syntax for join() method: str. Return Value This method returns a string. # This is sequence of strings. "b". Example The following example shows the usage of join() method. #!/usr/bin/python str = "-". 97 . which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.join(sequence) Parameters sequence -. it produces following result: a-b-c len(string) The method len() returns the length of the string. Syntax Following is the syntax for len() method: len( str ) Parameters NA Return Value This method returns the length of the string. When we run above program. seq = ("a".join( seq ).This is a sequence of the elements to be joined.  fillchar -. it produces following result: Length of the string: 32 ljust(width[.ljust(width[. Example The following example shows the usage of ljust() method. 98 ...This is filler character. The original string is returned if width is less than len(s). len(str).. fillchar]) The method ljust() returns the string left justified in a string of length width.wow!!!". default is a space. Padding is done using the specified fillchar (default is a space). #!/usr/bin/python str = "this is string example. print "Length of the string: ".This is string length in total after padding. #!/usr/bin/python str = "this is string example. fillchar]) Parameters  width -. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)..wow!!!". When we run above program. Syntax Following is the syntax for ljust() method: str... Python Example The following example shows the usage of len() method. Return Value This method returns the string left justified in a string of length width. . #!/usr/bin/python str = "THIS IS STRING EXAMPLE.ljust(50.lower() Parameters NA Return Value This method returns a copy of the string in which all case-based characters have been lowercased.. '0'). Python print str.wow!!! 99 .. When we run above program..WOW!!!".lower().wow!!!000000000000000000 lower() The method lower() returns a copy of the string in which all case-based characters have been lowercased.. it produces following result: this is string example. Syntax Following is the syntax for lower() method: str.. Example The following example shows the usage of lower() method. print str. it produces following result: this is string example... When we run above program.. print str. Example The following example shows the usage of lstrip() method. 100 .. Then this table is passed to the translate() function.wow!!! ".lstrip([chars]) Parameters chars -.. str = "88888888this is string example..lstrip().wow!!! this is string example. Note: Both intab and outtab must have the same length. Syntax Following is the syntax for lstrip() method: str. print str...lstrip('8'). Python lstrip() The method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters). Return Value This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters). #!/usr/bin/python str = " this is string example.wow!!!8888888 maketrans() The method maketrans() returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string.wow!!!8888888".You can supply what chars have to be trimmed..... it produces following result: this is string example. When we run above program.... . Python Syntax Following is the syntax for maketrans() method: str.wow!!!".translate(trantab). Under this. outtab) str = "this is string example. Return Value This method returns a translate table to be used translate() function... print str. it produces following result: th3s 3s str3ng 2x1mpl2.This is the string having corresponding mapping character..This is the string having actual characters. intab = "aeiou" outtab = "12345" trantab = maketrans(intab. When we run above program.. Parameters  intab -..maketrans(intab.w4w!!! 101 . Example The following example shows the usage of maketrans() method. outtab]). every vowel in a string is replaced by its vowel position: #!/usr/bin/python from string import maketrans # Required to call maketrans function.  outtab -. str = "this is a string example. Python max(str) The method max() returns the max alphabetical character from the string str.... Example The following example shows the usage of max() method..wow!!!". Syntax Following is the syntax for min() method: min(str) 102 . print "Max character: " + max(str).. print "Max character: " + max(str).wow!!!". Return Value This method returns the max alphabetical character from the string str. #!/usr/bin/python str = "this is really a string example. Syntax Following is the syntax for max() method: max(str) Parameters  str -..This is the string from which max alphabetical character needs to be returned. it produces following result: Max character: y Max character: x min(str) The method min() returns the min alphabetical character from the string str. When we run above program. optionally restricting the number of replacements to max.  max -. max]) The method replace() returns a copy of the string in which the occurrences of old have been replaced with new. only the first count occurrences are replaced. str = "this-is-a-string-example.. 103 .wow!!!".If this optional argument max is given.This is old substring to be replaced.. Syntax Following is the syntax for replace() method: str. Example The following example shows the usage of min() method.. #!/usr/bin/python str = "this-is-real-string-example. Python Parameters  str -. print "Min character: " + min(str). new [..wow!!!". new[.. print "Min character: " + min(str). max]) Parameters  old -.This is new substring.replace(old. it produces following result: Min character: ! Min character: ! replace(old. which would replace old substring. When we run above program.. Return Value This method returns the max alphabetical character from the string str.This is the string from which min alphabetical character needs to be returned.  new -. . 3)..This specifies the string to be searched. Return Value This method returns last index if found and -1 otherwise. optionally restricting the search to string[beg:end]..wow!!! thwas was really string thwas was string example. If the optional argument max is given.. 104 . Syntax Following is the syntax for rfind() method: str.wow!!! this is really string". beg=0 end=len(string)) Parameters  str -. it produces following result: thwas was string example.  end -.rfind(str.end=len(string)) Description The method rfind() returns the last index where the substring str is found.. "was"). beg=0. by default its equal to the length of the string.replace("is". Example The following example shows the usage of replace() method.. "was". #!/usr/bin/python str = "this is string example.wow!!! thwas is really string rfind(str. by default its 0.This is the starting index. When we run above program... print str.replace("is".This is the ending index. or -1 if no such index exists.. print str.  beg -. Python Return Value This method returns a copy of the string with all occurrences of substring old replaced by new. only the first count occurrences are replaced. print str. print str. str = "is".rfind(str). it produces following result: 5 5 -1 2 2 -1 rindex(str. beg=0. print str. print str.. 10). print str. #!/usr/bin/python str = "this is really a string example.rindex(str. 0.. 10.find(str. Syntax Following is the syntax for rindex() method: str. When we run above program.. 0. 0). beg=0 end=len(string)) Parameters 105 .find(str. or raises an exception if no such index exists. 0).wow!!!".rfind(str. print str. optionally restricting the search to string[beg:end]. Python Example The following example shows the usage of rfind() method.rfind(str. end=len(string)) The method rindex() returns the last index where the substring str is found. 10). 10.find(str). rjust(width[.. by default its 0  len -.index(str2). Example The following example shows the usage of rindex() method. Padding is done using the specified fillchar (default is a space)..rindex(str2).This specifies the string to be searched.wow!!!". str2 = "is". Python  str -. print str1. The original string is returned if width is less than len(s). it produces following result: 5 2 rjust(width.This is the starting index.  beg -. fillchar]) The method rjust() returns the string right justified in a string of length width. Syntax Following is the syntax for rjust() method: str. #!/usr/bin/python str1 = "this is string example. When we run above program.This is ending index. print str1. by default its equal to the length of the string. Return Value This method returns last index if found otherwise raises an exception if str is not found. fillchar]) Parameters 106 .[.. Return Value This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).wow!!! rstrip() The method rstrip() returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters)..rstrip([chars]) Parameters  chars -. Syntax Following is the syntax for rstrip() method: str. When we run above program.  fillchar -.This is the filler character. Return Value This method returns the string right justified in a string of length width. #!/usr/bin/python str = "this is string example. Padding is done using the specified fillchar (default is a space).wow!!!"..rjust(50. it produces following result: 000000000000000000this is string example.You can supply what chars have to be trimmed. The original string is returned if width is less than len(s)...This is the string length in total after padding. Example The following example shows the usage of rjust() method. Example 107 . Python  width -. default is a space.. '0').. print str. .rstrip('8'). num=string. optionally limiting the number of splits to num.. print str.count(str))..rstrip(). num=string.this is number of lines to be made.wow!!! split(str="". Python The following example shows the usage of rstrip() method. #!/usr/bin/python str = " this is string example. by default it is space.. Syntax Following is the syntax for split() method: str. print str.. str = "88888888this is string example....wow!!! ".. 108 . using str as the separator (splits on all whitespace if left unspecified).split(str=""... Example The following example shows the usage of split() method. Parameters  str -.wow!!!8888888". Return Value This method returns a list of lines.count(str)) The method split() returns a list of all the words in the string. it produces following result: this is string example.wow!!! 88888888this is string example.  num -. When we run above program.This is any delimeter.. #!/usr/bin/python str = "Line1-a b c d e f\nLine2. 'Line4-abcd'] ['Line1-abcdef'. When we run above program. 1 ). optionally including the line breaks (if num is supplied and is true) Syntax Following is the syntax for splitlines() method: str. Python #!/usr/bin/python str = "Line1-abcdef \nLine2-abc \nLine4-abcd". print str. 109 .splitlines( num=string.splitlines( ).count('\n')) The method splitlines() returns a list with all the lines in string. print str. print str.splitlines( 0 ). Return Value This method returns true if found matching string otherwise false. 'Line2-abc'. '\nLine2-abc \nLine4-abcd'] splitlines(num=string. print str. it produces following result: ['Line1-abcdef'.This is any number.split(' '.a b c\n\nLine4.count('\n')) Parameters  num -. print str. Example The following example shows the usage of splitlines() method.splitlines( 3 ). if present then it would be assumed that line breaks need to be included in the lines.splitlines( 5 ).splitlines( 4 ).a b c d". print str.split( ). print str. 2. 'Line4.a b c d'] ['Line1-a b c d e f\n'. Syntax Following is the syntax for startswith() method: str.wow!!!"..startswith(str..This is the optional parameter to set start index of the matching boundary.a b c d'] ['Line1-a b c d e f\n'.end=len(string)) The method startswith() checks whether string starts with str. it produces following result: ['Line1-a b c d e f'.end=len(string)). print str. 4 ). 'Line2. 'Line2.  end -.a b c d'] startswith(str. 'Line4. beg=0..This is the optional parameter to set start index of the matching boundary.a b c'.startswith( 'this'.a b c\n'. 'Line4. '\n'.startswith( 'this' ).a b c\n'. 'Line4. 'Line2. Python When we run above program. 'Line2. ''. '\n'. Return Value This method returns true if found matching string otherwise false.startswith( 'is'. print str. 2. print str.This is the string to be checked. 110 . 'Line2. Parameters  str -. Example The following example shows the usage of startswith() method. optionally restricting the matching with the given indices start and end. beg=0.a b c d'] ['Line1-a b c d e f\n'.  beg -. ''. 4 ).a b c'.a b c\n'. 'Line4. #!/usr/bin/python str = "this is string example. '\n'.a b c d'] ['Line1-a b c d e f'. Example The following example shows the usage of strip() method.. When we run above program. Parameters  chars -. Syntax Following is the syntax for strip() method: str.wow!!!0000000".strip([chars]).. 111 . it produces following result: True True False strip([chars]) The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).. print str.strip( '0' ). Return Value This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string.... #!/usr/bin/python str = "0000000this is string example. Python When we run above program.The characters to be removed from beginning or end of the string.wow!!! swapcase() The method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped. it produces following result: this is string example. .. print str... Example The following example shows the usage of swapcase() method. #!/usr/bin/python str = "this is string example. When we run above program. it produces following result: title() The method title() returns a copy of the string in which first characters of all the words are capitalized.swapcase().swapcase().title().swapcase()... print str.wow!!!". Python Syntax Following is the syntax for swapcase() method: str. Parameters NA Return Value 112 .WOW!!!". str = "THIS IS STRING EXAMPLE. Parameters NA Return Value This method returns a copy of the string in which all the case-based characters have had their case swapped. Syntax Following is the syntax for title() method: str. Example The following example shows the usage of title() method. Example The following example shows the usage of translate() method. print str... deletechars]). When we run above program.. Syntax Following is the syntax for translate() method: str.The list of characters to be removed from the source string..translate(table[. #!/usr/bin/python str = "this is string example. Under this every vowel in a string is replaced by its vowel position: 113 . Parameters  table -. deletechars="") The method translate() returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module). it produces following result: This Is String Example.wow!!!". Return Value This method returns a translated copy of the string. optionally deleting all characters found in the string deletechars.You can use the maketrans() helper function in the string module to create a translation table.title(). Python This method returns a copy of the string in which first characters of all the words are capitalized.Wow!!! translate(table..  deletechars -.. intab = "aeiou" outtab = "12345" trantab = maketrans(intab. 'xm')... print str. outtab) str = "this is string example.w4w!!! Following is the example to delete 'x' and 'm' characters from the string: #!/usr/bin/python from string import maketrans # Required to call maketrans function.translate(trantab). print str.. Syntax Following is the syntax for upper() method: 114 ...wow!!!".translate(trantab. outtab) str = "this is string example..wow!!!".. When we run above program. intab = "aeiou" outtab = "12345" trantab = maketrans(intab... This will produce following result: th3s 3s str3ng 21pl2.w4w!!! upper() The method upper() returns a copy of the string in which all case-based characters have been uppercased.... it produces following result: th3s 3s str3ng 2x1mpl2. Python #!/usr/bin/python from string import maketrans # Required to call maketrans function. This is the width which we would get after filling zeros.WOW!!! zfill (width) The method zfill() pads string on the left with zeros to fill width. #!/usr/bin/python str = "this is string example.wow!!!"..capitalize() : ". Python str. print "str. str. 115 ..This is final width of the string. it produces following result: THIS IS STRING EXAMPLE. Syntax Following is the syntax for zfill() method: str..upper() When we run above program. Return Value This method returns padded string. Example The following example shows the usage of upper() method.upper() Parameters NA Return Value This method returns a copy of the string in which all case-based characters have been uppercased...zfill(width) Parameters  width -.. .. When we run above program..isdecimal() Parameters  NA Return Value This method returns true if all characters in the string are decimal. Below is the example.zfill(50). #!/usr/bin/python str = "this is string example. print str....wow!!! 000000000000000000this is string example. print str. false otherwise.wow!!! isdecimal() The method isdecimal() checks whether the string consists of only decimal characters. Syntax Following is the syntax for isdecimal() method: str. it produces following result: 00000000this is string example. 116 .. one simply prefixes a 'u' to the opening quotation mark of the assignment. Python Example The following example shows the usage of zfill() method.. This method are present only on unicode objects.zfill(40). Example The following example shows the usage of isdecimal() method. Note: To define a string as Unicode.. #!/usr/bin/python str = u"this2009".wow!!!". Python print str.isdecimal(). it produces following result: False True 117 . print str. When we run above program.isdecimal(). str = u"23443434". 2000]. list1[0] 118 . Python has six built-in types of sequences. The first index is zero. 5 ]. These operations include indexing. 'chemistry'. adding. 2. list2 = [1. 3. In addition. print "list1[0]: ". Similar to string indices. which we would see in this tutorial. 5. the second index is one. 1997. 6. Accessing Values in Lists To access values in lists. and so forth. For example: #!/usr/bin/python list1 = ['physics'. 7 ]. 3. slicing. use the square brackets for slicing along with the index or indices to obtain value available at that index.its position or index. Important thing about a list is that items in a list need not be of the same type. Python Lists The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. and lists can be sliced. For example: list1 = ['physics'. "d"]. concatenated and so on. list3 = ["a". There are certain things you can do with all sequence types. 4. list indices start at 0. "b". "c". list2 = [1. Python 10. Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements. Each element of a sequence is assigned a number . 4. 2000]. 'chemistry'. but the most common ones are lists and tuples. and checking for membership. multiplying. Python ─ Lists The most basic data structure in Python is the sequence. Creating a list is as simple as putting different comma-separated values between square brackets. 2. 1997. 2000]. it produces the following result: list1[0]: physics list2[1:5]: [2. list[2] = 2001. When the above code is executed. it produces the following result: Value available at index 2 : 1997 New value available at index 2 : 2001 Deleting List Elements To remove a list element. 5] Updating Lists You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator. Note: append() method is discussed in subsequent section. 1997. and you can add to elements in a list with the append() method. For example: #!/usr/bin/python 119 . Python print "list2[1:5]: ". 3. list2[1:5] When the above code is executed. For example: #!/usr/bin/python list = ['physics'. 'chemistry'. 4. print "New value available at index 2 : " print list[2]. print "Value available at index 2 : " print list[2]. you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. 2. 2000] Note: remove() method is discussed in subsequent section. 2000] After deleting value at index 2 : ['physics'. it produces following result: ['physics'. 2. 5. 3] + [4. 'chemistry'. 123 Iteration 120 . they mean concatenation and repetition here too. 3] True Membership for x in [1. 2. 2000]. 6] Concatenation ['Hi!'] * 4 ['Hi!'. In fact. 3]) 3 Length [1. Python Expression Results Description len([1. del list1[2]. 6] [1. 5. 1997. 2. print "After deleting value at index 2 : " print list1. 1997. 'Hi!'] Repetition 3 in [1. 3]: print x. 'Hi!'. When the above code is executed. 'chemistry'. 'chemistry'. Basic List Operations Lists respond to the + and * operators much like strings. 2. not a string. Python list1 = ['physics'. print list1. lists respond to all of the general sequence operations we used on strings in the prior chapter. except that the result is a new list. 'Hi!'. 3. 4. min(list) 4 Returns item from the list with min value. indexing and slicing work the same way for lists as they do for strings. list2) 1 Compares elements of both lists. 'Spam'. 121 . 'SPAM!'] Slicing fetches sections Built-in List Functions and Methods Python includes the following list functions: Sr. max(list) 3 Returns item from the list with max value. and Matrixes Because lists are sequences. len(list) 2 Gives the total length of the list. Assume the following input: L = ['spam'. cmp(list1. Slicing. Function with Description No. Python Indexing. 'SPAM!'] Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam'. list(seq) 5 Converts a tuple into list. types are sorted alphabetically by name. list3) 122 . list3 = list2 + [786]. then the other element is "larger" (numbers are "smallest"). perform numeric coercion if necessary and compare.  If numbers. If elements are different types. list2 = [123. Python Cmp(list1. [456. list2) The method cmp() compares elements of two lists.  If either element is a number. the longer list is "larger. If we reached the end of one of the lists. 'abc'] print cmp(list1.  Otherwise. Syntax Following is the syntax for cmp() method: cmp(list1. list1). list2) Parameters  list1 -.This is the first list to be compared." If we exhaust both lists and share the same data. the result is a tie. #!/usr/bin/python list1. print cmp(list2. list2). Example The following example shows the usage of cmp() method. print cmp(list2.This is the second list to be compared. check to see if they are numbers. 'xyz'].  list2 -. perform the compare and return the result. Return Value If elements are of the same type. meaning that 0 is returned. it produces following result: First list length : 3 Second lsit length : 2 123 . 'abc'] print "First list length : ". Python When we run above program. 'xyz'. 'zara']. Example The following example shows the usage of len() method. #!/usr/bin/python list1. Syntax Following is the syntax for len() method: len(list) Parameters  list -. [456. When we run above program. Return Value This method returns the number of elements in the list. len(list2). print "Second list length : ". len(list1). it produces following result: -1 1 -1 len(List) The method len() returns the number of elements in the list.This is a list for which number of elements to be counted. list2 = [123. Example The following example shows the usage of max() method. Return Value This method returns the elements from the list with maximum value. Syntax Following is the syntax for max() method: max(list) Parameters  list -. print "Max value element : ". it produces following result: Max value element : zara Max value element : 700 min(list) The method min() returns the elements from the list with minimum value. 'xyz'. 'zara'. Python max(list) The method max returns the elements from the list with maximum value. Syntax Following is the syntax for min() method: min(list) 124 . [456. max(list2). When we run above program. #!/usr/bin/python list1. 'abc']. 700. 200] print "Max value element : ". list2 = [123. max(list1).This is a list from which max valued element to be returned. insert(index. No. 'xyz'.count(obj) Returns count of how many times obj occurs in list 3 list. 'abc']. #!/usr/bin/python list1. 700. [456. Python Parameters  list -. 200] print "min value element : ". min(list1). When we run above program. 'zara'. min(list2). Return Value This method returns the elements from the list with minimum value. list2 = [123.append(obj) Appends object obj to list 2 list. it produces following result: min value element : 123 min value element : 200 Python includes following list methods: Sr. print "min value element : ". Methods with Description 1 list.This is a list from which min valued element to be returned. Example The following example shows the usage of min() method.index(obj) Returns the lowest index in list that obj appears 5 list.extend(seq) Appends the contents of seq to list 4 list. obj) Inserts object obj into list at offset index 125 . pop(obj=list[-1]) Removes and returns last object or obj from list 7 list. 126 . Example The following example shows the usage of append() method. use compare func if given List. 'zara'.append(obj) Parameters  obj -. 'abc'].sort([func]) Sorts objects of list.remove(obj) Removes object obj from list 8 list.reverse() Reverses objects of list in place 9 list.append(obj) The method append() appends a passed obj into the existing list. Python 6 list.This is the object to be appended in the list.append( 2009 ). aList. aList. Return Value This method does not return any value but updates existing list. 'xyz'. #!/usr/bin/python aList = [123. Syntax Following is the syntax for append() method: list. print "Updated List : ". aList. 2009] list. #!/usr/bin/python aList = [123. Syntax Following is the syntax for count() method: list. Return Value This method returns count of how many times obj occurs in list. it produces following result: Updated List : [123.count(obj) Parameters  obj -. aList. 123]. 'xyz'. 'zara'. 'abc'.count(obj) The method count() returns count of how many times obj occurs in list. print "Count for 123 : ". Python When we run above program. Example The following example shows the usage of count() method.This is the object to be counted in the list. When we run above program.count(123). 'abc'. 'zara'. it produces following result: Count for 123 : 2 Count for zara : 1 127 . 'xyz'. print "Count for zara : ".count('zara'). extend(seq) Parameters  seq -. Python list. 'xyz'. 'manni']. 'xyz'. Syntax Following is the syntax for extend() method: list.index(obj) The method index() returns the lowest index in list that obj appears. 'zara'. aList . it produces following result: Extended List : [123. 123]. Example The following example shows the usage of extend() method. 'abc'. aList. When we run above program. 'manni'] list. 'abc'. 2009. #!/usr/bin/python aList = [123.extend(seq) The method extend() appends the contents of seq to list.index(obj) 128 .This is the list of elements Return Value This method does not return any value but add the content to existing list.extend(bList) print "Extended List : ". bList = [2009. 123. 'zara'. Syntax Following is the syntax for index() method: list. Python Parameters  obj -.insert(index. 'abc']. Return Value This method returns index of the found object otherwise raise an exception indicating that value does not find. Example The following example shows the usage of index() method. #!/usr/bin/python aList = [123. it produces following result: Index for xyz : 1 Index for zara : 2 list. 129 . 'zara'. When we run above program. aList.index( 'zara' ) .This is the Index where the object obj need to be inserted. Return Value This method does not return any value but it inserts the given element at the given index. aList. Syntax Following is the syntax for insert() method: list.obj) The method insert() inserts object obj into list at offset index. obj) Parameters  index -.This is the Object to be inserted into the given list.This is the object to be find out. 'xyz'. print "Index for xyz : ".index( 'xyz' ) . print "Index for zara : ".insert(index.  obj -. This is an optional parameter. aList.pop(obj=list[-1]) Parameters  obj -. print "A List : ". #!/usr/bin/python aList = [123. 130 . 'zara'. 'abc'] list.insert( 3. aList. it produces following result: Final List : [123. 'xyz'. print "B List : ".pop(). 2009) print "Final List : ". Return Value This method returns the removed object from the list. #!/usr/bin/python aList = [123. 'zara'. 'abc']. 'zara'. 2009.pop(obj=list[-1]) The method pop() removes and returns last object or obj from the list. aList When we run above program. index of the object to be removed from the list. Example The following example shows the usage of pop() method. 'xyz'. 'xyz'. 'abc'] aList. Python Example The following example shows the usage of insert() method. Syntax Following is the syntax for pop() method: list.pop(2). Python When we run above program. print "List : ".remove('xyz'). 'abc'. 'xyz'] List. Example The following example shows the usage of remove() method. 'zara'. 'xyz'] List : [123. 'abc'. When we run above program. 'zara'.remove(obj) Parameters  obj -. aList.reverse() The method reverse() reverses objects of list in place. 'xyz'. print "List : ". 'xyz']. #!/usr/bin/python aList = [123. it produces following result: A List : abc B List : zara List. Syntax Following is the syntax for reverse() method: list.remove('abc'). aList. aList. Return Value This method does not return any value but removes the given object from the list.reverse() 131 .This is the object to be removed from the list. 'zara'. aList. it produces following result: List : [123. 123] list.reverse() Parameters NA Return Value This method does not return any value but reverse the given object from the list. 'xyz'.sort([func]) The method reverse() reverses objects of list in place. Syntax Following is the syntax for reverse() method: list. 'abc'.reverse(). it produces following result: List : ['xyz'. 'xyz'. When we run above program. 132 . 'xyz']. 'abc'. #!/usr/bin/python aList = [123. 'zara'. 'zara'. print "List : ". aList. Example The following example shows the usage of reverse() method. Python Parameters NA Return Value This method does not return any value but reverse the given object from the list. aList. #!/usr/bin/python aList = [123. 'abc'. aList. it produces following result: List : ['xyz'.reverse(). 'xyz'. Python Example The following example shows the usage of reverse() method. 'zara'. print "List : ". 'xyz'. 'zara'. 123] 133 . 'abc'. 'xyz']. aList. When we run above program. 2000). The differences between tuples and lists are. 'chemistry'. 'chemistry'. For example: #!/usr/bin/python tup1 = ('physics'. 5. it produces the following result: tup1[0]: physics tup2[1:5]: [2. just like lists. the tuples cannot be changed unlike lists and tuples use parentheses. 3. Python 11. 2. 4. 1997. 4. Python ─ Tuples A tuple is a sequence of immutable Python objects. 3. 2000). print "tup1[0]: ". and so on. 5 ). tup2[1:5] When the above code is executed. Accessing Values in Tuples To access values in tuple. tup3 = "a". tuple indices start at 0. Like string indices. 6. To write a tuple containing a single value you have to include a comma. 2. and they can be sliced. 7 ). 4. 5] 134 . "b". Optionally you can put these comma-separated values between parentheses also. 1997. 3. tup1[0] print "tup2[1:5]: ". "d". even though there is only one value: tup1 = (50. concatenated. "c". For example: tup1 = ('physics'. tup2 = (1.). whereas lists use square brackets. tup2 = (1. use the square brackets for slicing along with the index or indices to obtain value available at that index. Tuples are sequences. The empty tuple is written as two parentheses containing nothing: tup1 = (). Creating a tuple is as simple as putting different comma-separated values. 'xyz').56). 'abc'. print tup3. 'chemistry'. del tup. 2000). 1997. 'xyz') Deleting Tuple Elements Removing individual tuple elements is not possible. # So let's create a new tuple as follows tup3 = tup1 + tup2. print tup. nothing wrong with putting together another tuple with the undesired elements discarded. For example: #!/usr/bin/python tup = ('physics'. just use the del statement. When the above code is executed. 135 . of course. There is. To explicitly remove an entire tuple. 34. # Following action is not valid for tuples # tup1[0] = 100.56. it produces the following result: (12. You are able to take portions of existing tuples to create new tuples as the following example demonstrates: #!/usr/bin/python tup1 = (12. Python Updating Tuples Tuples are immutable which means you cannot update or change the values of tuple elements. 34. tup2 = ('abc'. print "After deleting tup : " print tup. 5. 6) Concatenation ('Hi!'. NameError: name 'tup' is not defined Basic Tuples Operations Tuples respond to the + and * operators much like strings. 3): print x. 2. 2. except that the result is a new tuple. Note an exception raised. 1997. 2000) After deleting tup : Traceback (most recent call last): File "test. 3.) * 4 ('Hi!'. 'Hi!') Repetition 3 in (1. 'Hi!'. Slicing. 4. 3) + (4. this is because after del tup. In fact. 2. 'SPAM!') 136 . Assuming following input: L = ('spam'. 3)) 3 Length (1. 5. 'Hi!'. Python This produces the following result. 2. in <module> print tup. 6) (1. and Matrixes Because tuples are sequences. tuples respond to all of the general sequence operations we used on strings in the prior chapter: Python Expression Results Description len((1. 3) True Membership for x in (1.py". 2. 123 Iteration Indexing. not a string. 'Spam'. tuple does not exist anymore: ('physics'. they mean concatenation and repetition here too. indexing and slicing work the same way for tuples as they do for strings. line 9. 'chemistry'. When the above code is executed. 137 . Python Python Expression Results Description L[2] 'SPAM!' Offsets start at zero L[-2] 'Spam' Negative: count from the right L[1:] ['Spam'.24e+93 (18+6. x.. as indicated in these short examples: #!/usr/bin/python print 'abc'. y : 1 2 Built-in Tuple Functions Python includes the following tuple functions: Sr.24e93. i. No. comma-separated. y : ". default to tuples. 18+6. it produces the following result: abc -4.6j) xyz Value of x .e. -4. etc. tuple2) Compares elements of both tuples.6j. brackets for lists.. parentheses for tuples. y = 1. Function with Description 1 cmp(tuple1. print "Value of x . written without identifying symbols. 'xyz'.y. 2. 'SPAM!'] Slicing fetches sections No Enclosing Delimiters Any set of multiple objects. 2 len(tuple) Gives the total length of the tuple. x.  Otherwise. Python 3 max(tuple) Returns item from the tuple with max value. meaning that 0 is returned. Cmp(tuple1. tuple2) Parameters  tuple1 -.This is the second tuple to be compared Return Value If elements are of the same type. perform the compare and return the result." If we exhaust both tuples and share the same data. the longer tuple is "larger.  If either element is a number. perform numeric coercion if necessary and compare. 138 .This is the first tuple to be compared  tuple2 -. then the other element is "larger" (numbers are "smallest"). If we reached the end of one of the tuples. 5 tuple(seq) Converts a list into tuple. If elements are different types. 4 min(tuple) Returns item from the tuple with min value. check to see if they are numbers. the result is a tie. tuple2) The method cmp() compares elements of two tuples. types are sorted alphabetically by name.  If numbers. Syntax Following is the syntax for cmp() method: cmp(tuple1. Example The following example shows the usage of len() method. #!/usr/bin/python tuple1. 'abc') 139 . Return Value This method returns the number of elements in the tuple. (456. tuple2).). tuple3) When we run above program. print cmp(tuple2. 'xyz'. #!/usr/bin/python tuple1.This is a tuple for which number of elements to be counted. Syntax Following is the syntax for len() method: len(tuple) Parameters  tuple -. 'zara'). tuple3 = tuple2 + (786. tuple2 = (123. 'xyz'). Python Example The following example shows the usage of cmp() method. 'abc') print cmp(tuple1. tuple1). print cmp(tuple2. it produces following result: -1 1 -1 Len(tuple) The method len() returns the number of elements in the tuple. tuple2 = (123. (456. Return Value This method returns the elements from the tuple with maximum value. Example The following example shows the usage of max() method. len(tuple1). When we run above program.This is a tuple from which max valued element to be returned. it produces following result: Max value element : zara Max value element : 700 140 . max(tuple1). (456. 'xyz'. len(tuple2). 'abc'). print "Second tuple length : ". max(tuple2). When we run above program. 700. #!/usr/bin/python tuple1. Syntax Following is the syntax for max() method: max(tuple) Parameters  tuple -. tuple2 = (123. 200) print "Max value element : ". print "Max value element : ". 'zara'. it produces following result: First tuple length : 3 Second tuple length : 2 Max(tuple) The method max() returns the elements from the tuple with maximum value. Python print "First tuple length : ". #!/usr/bin/python tuple1. tuple2 = (123. 'zara'. Example The following example shows the usage of min() method.This is a tuple from which min valued element to be returned. print "min value element : ". Return Value This method returns the elements from the tuple with minimum value. Syntax Following is the syntax for min() method: min(tuple) Parameters  tuple -. min(tuple2). When we run above program. 700. (456. 200) print "min value element : ". Syntax Following is the syntax for tuple() method: tuple( seq ) 141 . min(tuple1). 'abc'). 'xyz'. Python Min(tuple) The method min() returns the elements from the tuple with minimum value. it produces following result: min value element : 123 min value element : 200 Tuple(seg) The method tuple() compares elements of two tuples. 'abc'). aTuple = tuple(aList) print "Tuple elements : ". #!/usr/bin/python aList = (123. 'zara'. 'xyz'. it produces following result: Tuple elements : (123. Example The following example shows the usage of tuple() method. Python Parameters  seq -. 'xyz'.This is a tuple to be converted into tuple. aTuple When we run above program. 'zara'. 'abc') 142 . Return Value This method returns the tuple. Python 12. Python ─ Dictionary Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Accessing Values in Dictionary To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age']; When the above code is executed, it produces the following result: dict['Name']: Zara dict['Age']: 7 If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Alice']: ", dict['Alice']; 143 Python When the above code is executed, it produces the following result: dict['Zara']: Traceback (most recent call last): File "test.py", line 4, in <module> print "dict['Alice']: ", dict['Alice']; KeyError: 'Alice' Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School']; When the above code is executed, it produces the following result: dict['Age']: 8 dict['School']: DPS School Delete Dictionary Elements You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement. For example: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; 144 Python del dict['Name']; # remove entry with key 'Name' dict.clear(); # remove all entries in dict del dict ; # delete entire dictionary print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School']; This produces the following result. Note that an exception is raised because after del dict, dictionary does not exist anymore: dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable Note: del() method is discussed in subsequent section. Properties of Dictionary Keys Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. There are two important points to remember about dictionary keys: (a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. For example: #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print "dict['Name']: ", dict['Name']; When the above code is executed, it produces the following result: dict['Name']: Manni (b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example: 145 Python #!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name']; When the above code is executed, it produces the following result: Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable Built-in Dictionary Functions and Methods Python includes the following dictionary functions: Sr. No. Function with Description 1 cmp(dict1, dict2) Compares elements of both dict. 2 len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. 3 str(dict) Produces a printable string representation of a dictionary 4 type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. Cmp(dict1, dict2) The method cmp() compares two dictionaries based on key and values. 146 Python Syntax Following is the syntax for cmp() method: cmp(dict1, dict2) Parameters  dict1 -- This is the first dictionary to be compared with dict2.  dict2 -- This is the second dictionary to be compared with dict1. Return Value This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2, and 1 if dict1 > dic2. Example The following example shows the usage of cmp() method. #!/usr/bin/python dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = {'Name': 'Mahnaz', 'Age': 27}; dict3 = {'Name': 'Abid', 'Age': 27}; dict4 = {'Name': 'Zara', 'Age': 7}; print "Return Value : %d" % cmp (dict1, dict2) print "Return Value : %d" % cmp (dict2, dict3) print "Return Value : %d" % cmp (dict1, dict4) When we run above program, it produces following result: Return Value : -1 Return Value : 1 Return Value : 0 len(dict) The method len() gives the total length of the dictionary. This would be equal to the number of items in the dictionary. Syntax 147 Python Following is the syntax for len() method: len(dict) Parameters  dict -- This is the dictionary, whose length needs to be calculated. Return Value This method returns the length. Example The following example shows the usage of len() method. #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict) When we run above program, it produces following result: Length : 2 str(dict) The method str() produces a printable string representation of a dictionary. Syntax Following is the syntax for str() method: str(dict) Parameters  dict -- This is the dictionary. Return Value This method returns string representation. Example The following example shows the usage of str() method. 148 Python #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) When we run above program, it produces following result: Equivalent String : {'Age': 7, 'Name': 'Zara'} type() The method type() returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type. Syntax Following is the syntax for type() method: type(dict) Parameters  dict -- This is the dictionary. Return Value This method returns the type of the passed variable. Example The following example shows the usage of type() method. #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Variable Type : %s" % type (dict) When we run the above program, it produces the following result: Variable Type : <type 'dict'> Python includes following dictionary methods: 149 Python Sr. No. Methods with Description 1 dict.clear() Removes all elements of dictionary dict 2 dict.copy() Returns a shallow copy of dictionary dict 3 dict.fromkeys() Create a new dictionary with keys from seq and values set to value. 4 dict.get(key, default=None) For key key, returns value or default if key not in dictionary 5 dict.has_key(key) Returns true if key in dictionary dict, false otherwise 6 dict.items() Returns a list of dict's (key, value) tuple pairs 7 dict.keys() Returns list of dictionary dict's keys 8 dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict 9 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict 10 dict.values() Returns list of dictionary dict's values 150 Example The following example shows the usage of clear() method. 'Age': 7}.clear() Parameters  NA Return Value This method does not return any value. print "Start Len : %d" % len(dict) dict.clear() The method clear() removes all items from the dictionary. Syntax Following is the syntax for copy() method: 151 . Python dict.copy() The method copy() returns a shallow copy of the dictionary. it produces following result: Start Len : 2 End Len : 0 Dict.clear() print "End Len : %d" % len(dict) When we run above program. #!/usr/bin/python dict = {'Name': 'Zara'. Syntax Following is the syntax for clear() method: dict. dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2) When we run above program. if provided then value would be set to this value 152 .fromkeys() The method fromkeys() creates a new dictionary with keys from seq and values set to value. 'Age': 7}.fromkeys(seq[.This is optional. Python dict. 'Name': 'Zara'} Dict. Syntax Following is the syntax for fromkeys() method: dict.copy() Parameters  NA Return Value This method returns a shallow copy of the dictionary.  value -. Example The following example shows the usage of copy() method. value])) Parameters  seq -. it produces following result: New Dictinary : {'Age': 7.This is the list of values which would be used for dictionary keys preparation. #!/usr/bin/python dict1 = {'Name': 'Zara'. 'name': 10.This is the Value to be returned in case key does not exist.get(key. Return Value 153 . 'sex': None} New Dictionary : {'age': 10. default=None) Parameters  key -.get(key. 10) print "New Dictionary : %s" % str(dict) When we run above program. Example The following example shows the usage of fromkeys() method.default=none) The method get() returns a value for the given key. Python Return Value This method returns the list. 'name': None. #!/usr/bin/python seq = ('name'. 'age'. Syntax Following is the syntax for get() method: dict. it produces following result: New Dictionary : {'age': None.This is the Key to be searched in the dictionary.fromkeys(seq. 'sex': 10} Dict.fromkeys(seq) print "New Dictionary : %s" % str(dict) dict = dict. 'sex') dict = dict.  default -. If key is not available then returns default value None. #!/usr/bin/python 154 . Syntax Following is the syntax for has_key() method: dict.get('Education'. otherwise it returns a false. Return Value This method return true if a given key is available in the dictionary. Python This method return a value for the given key. Example The following example shows the usage of get() method. #!/usr/bin/python dict = {'Name': 'Zabra'.This is the Key to be searched in the dictionary.has_key(key) The method has_key() returns true if a given key is available in the dictionary.get('Age') print "Value : %s" % dict. "Never") When we run above program. it produces the following result: Value : 7 Value : Never Dict. otherwise it returns a false. Example The following example shows the usage of has_key() method. 'Age': 7} print "Value : %s" % dict.has_key(key) Parameters  key -. then returns default value None. If key is not available. 'Age': 7} print "Value : %s" % dict.has_key('Age') print "Value : %s" % dict. it produces following result: Value : True Value : False Dict. Python dict = {'Name': 'Zara'.items() The method items() returns a list of dict's (key. 'Zara')] 155 . it produces following result: Value : [('Age'.items() When we run above program.has_key('Sex') When we run above program. ('Name'. Example The following example shows the usage of items() method. 'Age': 7} print "Value : %s" % dict. #!/usr/bin/python dict = {'Name': 'Zara'. value) tuple pairs Syntax Following is the syntax for items() method: dict. 7).items() Parameters  NA Return Value This method returns a list of tuple pairs. it produces following result: Value : ['Age'. 'Name'] dict. #!/usr/bin/python dict = {'Name': 'Zara'. Python Dict. 'Age': 7} print "Value : %s" % dict.keys() When we run above program. Example The following example shows the usage of keys() method. Syntax Following is the syntax for setdefault() method: 156 . default=None) The method setdefault() is similar to get().keys() Parameters NA Return Value This method returns a list of all the available keys in the dictionary. but will set dict[key]=default if key is not already in dict. Syntax Following is the syntax for keys() method: dict.keys() The method keys() returns a list of all the available keys in the dictionary.setdefault(key. None) When we run above program.This is the Value to be returned in case key is not found. it produces following result: Value : 7 Value : None dict.update(dict2) The method update() adds dictionary dict2's key-values pairs in to dict. Python dict.setdefault('Sex'.setdefault('Age'.setdefault(key. Return Value This method returns the key value available in the dictionary and if given key is not available then it will return provided default value. #!/usr/bin/python dict = {'Name': 'Zara'.This is the key to be searched.  default -.update(dict2) 157 . default=None) Parameters  key -. None) print "Value : %s" % dict. 'Age': 7} print "Value : %s" % dict. This function does not return anything. Example The following example shows the usage of setdefault() method. Syntax Following is the syntax for update() method: dict. 'Name': 'Zara'. #!/usr/bin/python dict = {'Name': 'Zara'. Python Parameters  dict2 -.This is the dictionary to be added into dict. 'Age': 7} dict2 = {'Sex': 'female' } dict.values() The method values() returns a list of all the values available in a given dictionary.values() Parameters NA 158 . Example The following example shows the usage of update() method. 'Sex': 'female'} dict. Return Value This method does not return any value. it produces following result: Value : {'Age': 7. Syntax Following is the syntax for values() method: dict.update(dict2) print "Value : %s" % dict When we run above program. #!/usr/bin/python dict = {'Name': 'Zara'.values() When we run above program. 'Age': 7} print "Value : %s" % dict. 'Zara'] 159 . Example The following example shows the usage of values() method. it produces following result: Value : [7. Python Return Value This method returns a list of all the values available in a given dictionary. the cutoff point is sometime in 2038 for UNIX and Windows. There is a popular time module available in Python which provides functions for working with times and for converting between representations.73399 Date arithmetic is easy to do with ticks. ticks = time.time() returns the current system time in ticks since 12:00am. Python 13. January 1. However. The function time. Particular instants in time are expressed in seconds since 12:00am. dates before the epoch cannot be represented in this form. Converting between date formats is a common chore for computers. January 1. # This is required to include time module. Dates in the far future also cannot be represented this way . as shown below: Index Field Values 0 4-digit year 2008 160 . What is Tick? Time intervals are floating-point numbers in units of seconds. January 1. Python's time and calendar modules help track dates and times. 1970:". Python ─ Date and Time A Python program can handle date and time in several ways. 1970(epoch). January 1.time() print "Number of ticks since 12:00am. What is TimeTuple? Many of Python's time functions handle time as a tuple of 9 numbers. 1970: 7186862. ticks This would produce a result something as follows: Number of ticks since 12:00am. Example #!/usr/bin/python import time. 1970(epoch). 1. Python 1 Month 1 to 12 2 Day 1 to 31 3 Hour 0 to 23 4 Minute 0 to 59 5 Second 0 to 61 (60 or 61 are leap-seconds) 6 Day of Week 0 to 6 (0 is Monday) 7 Day of year 1 to 366 (Julian day) 8 Daylight savings -1. This structure has following attributes: Index Attributes Values 0 tm_year 2008 1 tm_mon 1 to 12 2 tm_mday 1 to 31 3 tm_hour 0 to 23 4 tm_min 0 to 59 5 tm_sec 0 to 61 (60 or 61 are leap-seconds) 6 tm_wday 0 to 6 (0 is Monday) 161 . -1 means library determines DST The above tuple is equivalent to struct_time structure. 0. localtime) that returns a time-tuple with all nine items valid.struct_time(tm_year=2013. localtime This would produce the following result: Local current time : Tue Jan 13 10:17:09 2009 162 . tm_isdst=0) Getting Formatted Time You can format any time as per your requirement. tm_yday=198. tm_mday=17. tm_hour=21. tm_sec=3. -1 means library determines DST Getting Current Time To translate a time instant from a seconds since the epoch floating-point value into a time-tuple. but simple method to get time in readable format is asctime(): #!/usr/bin/python import time.localtime(time. tm_min=26. localtime = time.asctime( time. pass the floating-point value to a function (For example. localtime = time. 0.localtime(time. tm_mon=7. localtime This would produce the following result.time()) print "Local current time :". Python 7 tm_yday 1 to 366 (Julian day) 8 tm_isdst -1. #!/usr/bin/python import time. tm_wday=2. 1. which could be formatted in any other presentable form: Local current time : time.time()) ) print "Local current time :". No.altzone 1 The offset of the local DST timezone. we print a calendar for a given month ( Jan 2008 ): #!/usr/bin/python import calendar cal = calendar.month(2008. Here is the list of all available methods: Sr. if one is defined. This would produce the following result: Here is the calendar: January 2008 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 The time Module There is a popular time module available in Python which provides functions for working with times and for converting between representations. including the UK). Here. 2 time. Python Getting Calendar for a Month The calendar module gives a wide range of methods to play with yearly and monthly calendars. in seconds west of UTC. 1) print "Here is the calendar:" print cal.asctime([tupletime]) 163 . Only use this if daylight is nonzero. Function with Description time. This is negative if the local DST timezone is east of UTC (as in Western Europe. To measure computational costs of different approaches.fmt='%a %b %d %H:%M:%S %Y') 10 Parses str according to format string fmt and returns the instant in time-tuple format.mktime(tupletime) 7 Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch. time. 164 . Python Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'.strftime(fmt[.sleep(secs) 8 Suspends the calling thread for secs seconds. time. depending on whether DST applies to instant secs by local rules).clock( ) 3 Returns the current CPU time as a floating-point number of seconds.strptime(str. time. time.localtime([secs]) 6 Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.gmtime([secs]) 5 Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time.clock is more useful than that of time. time. the value of time.tm_isdst is always 0 time. time.tupletime]) 9 Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt.time().ctime([secs]) 4 Like asctime(localtime(secs)) and without arguments is like asctime( ) time. Note : t.tm_isdst is 0 or 1. Only use this if daylight is nonzero.time( ) 11 Returns the current time instant.tzset() 12 Resets the time conversion rules used by the library routines. #!/usr/bin/python import time print "time.altzone When we run above program. in seconds west of UTC. it produces following result: time. in seconds west of UTC. This is negative if the local DST timezone is east of UTC (as in Western Europe. if one is defined. Python time. time. Example The following example shows the usage of altzone() method. This returns the offset of the local DST timezone.altzone Parameters NA Return Value This method returns the offset of the local DST timezone.altzone %d " % time.altzone() 25200 165 . including the UK). The environment variable TZ specifies how this is done. time. if one is defined. a floating-point number of seconds since the epoch.altzone The method altzone() is the attribute of the time module. Syntax Following is the syntax for altzone() method: time. clock( ) The method clock() returns the current processor time as a floating point number expressed in seconds on Unix. but in any case.asctime(t) When we run above program. as a floating point number.This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function.actime([tupletime]) The method asctime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'. Syntax Following is the syntax for asctime() method: time.asctime(t): %s " % time. Return Value This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'. this is the function to use for benchmarking Python or timing algorithms. Example The following example shows the usage of asctime() method. this function returns wall-clock seconds elapsed since the first call to this function.localtime() print "time.asctime(t): Tue Feb 17 09:42:58 2009 time. Python time. On Windows. it produces following result: time. based on the Win32 function QueryPerformanceCounter. #!/usr/bin/python import time t = time.asctime([t])) Parameters  t -. 166 . The precision depends on that of the C function of the same name. "seconds process time" # measure wall time t0 = time. "seconds wall time" When we run above program.50023603439 seconds wall time Note: Not all systems can measure the true process time.5) # measure process time t0 = time.clock() . Python Syntax Following is the syntax for clock() method: time. 167 .clock() procedure() print time.t0. it produces following result: 0.0 seconds process time 2.sleep(2.clock() Parameters NA Return Value This method returns the current processor time as a floating point number expressed in seconds on Unix and in Windows it returns wall-clock seconds elapsed since the first call to this function. On such systems (including Windows). clock usually measures the wall time since the program was started. as a floating point number.t0. #!/usr/bin/python import time def procedure(): time. Example The following example shows the usage of clock() method.time() .time() procedure() print time. This function is equivalent to asctime(localtime(secs)). If secs is not provided or None.ctime() : %s" % time.ctime() : Tue Feb 17 10:00:18 2009 time.gmtime([secs]) The method gmtime() converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. Example The following example shows the usage of ctime() method.ctime() When we run above program. the current time as returned by time() is used. Return Value This method does not return any value. #!/usr/bin/python import time print "time. Python time. it produces following result: time. If secs is not provided or None. Locale information is not used by ctime().ctime([secs]) The method ctime() converts a time expressed in seconds since the epoch to a string representing local time. Syntax Following is the syntax for ctime() method: time.ctime([ sec ]) Parameters  sec -. the current time as returned by time() is used.These are the number of seconds to be converted into string representation. Syntax Following is the syntax for gmtime() method: 168 . Return Value This method does not return any value.These are the number of seconds to be converted into structure struct_time representation. Python time.localtime([ sec ]) Parameters  sec -. If secs is not provided or None.gmtime([ sec ]) Parameters  sec -. it produces following result: time. 17. 0) time.localtime([secs]) The method localtime() is similar to gmtime() but it converts number of seconds to local time. Example The following example shows the usage of gmtime() method. 17. 3. #!/usr/bin/python import time print "time.gmtime() : (2009.gmtime() When we run above program. the current time as returned by time() is used. Return Value This method does not return any value. 1. 38.These are the number of seconds to be converted into structure struct_time representation. The dst flag is set to 1 when DST applies to the given time. 169 . 48. Syntax Following is the syntax for localtime() method: time. 2.gmtime() : %s" % time. If the input value cannot be represented as a valid time. 48. 3. 17. for compatibility with time(). 38.mktime(tupletime) Description The method mktime() is the inverse function of localtime(). Return Value This method returns a floating point number. 48. #!/usr/bin/python import time t = (2009.localtime() : (2009. 0) time. Its argument is the struct_time or full 9-tuple and it returns a floating point number. 17. Example The following example shows the usage of mktime() method. 2. either OverflowError or ValueErrorwill be raised.localtime() When we run above program.localtime() : %s" % time. 1. 1. 38.This is the struct_time or full 9-tuple. 17. #!/usr/bin/python import time print "time. Python Example The following example shows the usage of localtime() method. 2. 17. it produces following result: time. 3. Syntax Following is the syntax for mktime() method: time. 0) 170 . for compatibility with time().mktime(t) Parameters  t -. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Return Value This method does not return any value. #!/usr/bin/python import time print "Start : %s" % time.ctime() When we run above program.sleep(t) Parameters  t -.000000 asctime(localtime(secs)): Tue Feb 17 17:03:38 2009 time. it produces following result: 171 .mktime(t) : 1234915418.This is the number of seconds execution to be suspended.mktime(t) : %f" % secs print "asctime(localtime(secs)): %s" % time.sleep( 5 ) print "End : %s" % time. Example The following example shows the usage of sleep() method.localtime(secs)) When we run above program.mktime( t ) print "time. it produces following result: time. The argument may be a floating point number to indicate a more precise sleep time.ctime() time.asctime(time.sleep(secs) The method sleep() suspends execution for the given number of seconds. Python secs = time. Syntax Following is the syntax for sleep() method: time.  format -.4-digit year corresponding to the ISO week number (see %V). Syntax Following is the syntax for strftime() method: time.abbreviated weekday name  %A . If t is not provided.abbreviated month name  %B .day of the month (1 to 31)  %g .strftime(fmt[. An exception ValueError is raised if any field in t is outside of the allowed range.full weekday name  %b . The following directives can be embedded in the format string: Directive  %a .  %h . range 00 to 99)  %d .century number (the year divided by 100.tupletime]) The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.strftime(format[.same as %b  %H .same as %m/%d/%y  %e .preferred date and time representation  %C . using a 24-hour clock (00 to 23) 172 . but without the century  %G . t]) Parameters  t -.This is the time in number of seconds to be formatted.like %G. format must be a string. Python Start : Tue Feb 17 10:19:18 2009 End : Tue Feb 17 10:19:23 2009 time.full month name  %c .hour. the current time as returned by localtime() is used.This is the directive which would be used to format given time.day of the month (01 to 31)  %D . year including the century  %Z or %z . Warning: In Sun Solaris Sunday=1  %U . Sunday=0  %x .either am or pm according to the given time value  %r . Monday=1. and with Monday as the first day of the week  %W . and p. where week 1 is the first week that has at least 4 days in the current year.time in a.year without a century (range 00 to 99)  %Y .tab character  %T .m.The ISO 8601 week number of the current year (01 to 53).week number of the current year. equal to %H:%M:%S  %u .month (01 to 12)  %M . using a 12-hour clock (01 to 12)  %j .time in 24 hour notation  %S .day of the week as a decimal. Example 173 .newline character  %p .current time.minute  %n .time zone or name or abbreviation  %% . Python  %I .a literal % character Return Value This method does not return any value.preferred time representation without the date  %y .preferred date representation without the time  %X .day of the year (001 to 366)  %m .second  %t . starting with the first Sunday as the first day of the first week  %V .m.hour. starting with the first Monday as the first day of the first week  %w .weekday as a number (1 to 7).week number of the current year. notation  %R . ValueError is raised. time.mktime(t) print time. 1.gmtime(t)) When we run above program. 0) t = time. 38. 3. #!/usr/bin/python import time t = (2009. 2. The following directives can be embedded in the format string: Directive 174 . it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().strptime(str. If string cannot be parsed according to format. or if it has excess data after parsing. it produces following result: Feb 18 2009 00:03:38 time.strftime("%b %d %Y %H:%M:%S".strptime(string[. 48. Python The following example shows the usage of strftime() method.  format -. The format parameter uses the same directives as those used by strftime().fmt='%a %b %d %H:%M:%S %Y') The method strptime() parses a string representing a time according to a format. 17. Syntax Following is the syntax for strptime() method: time.This is the time in string format which would be parsed based on the given format.This is the directive which would be used to parse the given string. format]) Parameters  string -. 17. The return value is a struct_time as returned by gmtime() or localtime(). minute  %n . equal to %H:%M:%S  %u .abbreviated weekday name  %A . using a 12-hour clock (01 to 12)  %j . where week 1 is the first week that has at least 4 days in the current year.hour.century number (the year divided by 100.month (01 to 12)  %M .same as %m/%d/%y  %e .tab character  %T .day of the month (1 to 31)  %g .time in 24 hour notation  %S .full month name  %c . Warning: In Sun Solaris Sunday=1  %U . Python  %a .hour. using a 24-hour clock (00 to 23)  %I .m. Monday=1.m.week number of the current year. and p.day of the year (001 to 366)  %m .abbreviated month name  %B .newline character  %p .full weekday name  %b .weekday as a number (1 to 7).preferred date and time representation  %C .  %h .day of the month (01 to 31)  %D .time in a. starting with the first Sunday as the first day of the first week  %V . notation  %R .current time.same as %b  %H .The ISO 8601 week number of the current year (01 to 53).4-digit year corresponding to the ISO week number (see %V).like %G. range 00 to 99)  %d .second  %t . but without the century  %G . and with Monday as the first day of the week 175 .either am or pm according to the given time value  %r . "%d %b %y") print "returned tuple: %s " % struct_time When we run above program. not all systems provide time with a better precision than 1 second. 335. -1) time. in UTC. it produces following result: returned tuple: (2000. 3.a literal % character Return Value This return value is struct_time as returned by gmtime() or localtime().time( ) The method time() returns the time as a floating point number expressed in seconds since the epoch. it can return a lower value than a previous call if the system clock has been set back between the two calls.preferred time representation without the date  %y .week number of the current year.year including the century  %Z or %z . 0.strptime("30 Nov 00". starting with the first Monday as the first day of the first week  %w . #!/usr/bin/python import time struct_time = time. While this function normally returns non-decreasing values.day of the week as a decimal. 11.year without a century (range 00 to 99)  %Y . 0. Sunday=0  %x . Python  %W .preferred date representation without the time  %X . Example The following example shows the usage of strptime() method. 0. Note: Even though the time is always returned as a floating point number.time zone or name or abbreviation  %% . 30. Syntax Following is the syntax for time() method: 176 . The standard format of the TZ environment variable is (whitespace added for clarity): std offset [dst [offset [. These will be propagated into time.time() ) print time. otherwise.asctime( time. it produces following result: time. in UTC.start[/time]. it is west. 1. summer time is assumed to be one hour ahead of standard time. 48. If no offset follows dst.localtime(time. 10.time(): 1234892919.hh[:mm[:ss]].tzset() The method tzset() resets the time conversion rules used by the library routines.time() Parameters NA Return Value This method returns the time as a floating point number expressed in seconds since the epoch. This indicates the value added the local time to arrive at UTC. 48.time() print time. 2. 17. #!/usr/bin/python import time print "time. 177 . Example The following example shows the usage of time() method. 0) Tue Feb 17 10:48:39 2009 time.time()) ) When we run above program.655932 (2009. Python time.time(): %f " % time. 39. the timezone is east of the Prime Meridian. end[/time]]]]  std and dst: Three or more alphanumerics giving the timezone abbreviations. If preceded by a '-'.tzname. The environment variable TZ specifies how this is done.localtime( time.  offset: The offset has the form: . M10. where week 5 means 'the last d day in month m' which may occur in either the fourth or the fifth week).0.5. Week 1 is the first week in which the d'th day occurs.environ['TZ'] = 'EST+05EDT. Leap days are not counted.0.tzset() 178 . #!/usr/bin/python import time import os os. Leap days are counted.0' time.1.environ['TZ'] = 'AEST-10AEDT-11.n. The default.M4.5. o time: This has the same format as offset except that no leading sign ('- ' or '+') is allowed. 1 <= m <= 12. Python  start[/time]. Day zero is Sunday. end[/time]: Indicates when to change to and back from DST. if time is not given.5.M3.tzset() print time. Example The following example shows the usage of tzset() method. is 02:00:00.strftime('%X %x %Z') os.M10.0' time. and it is possible to refer to February 29.tzset() Parameters NA Return Value This method does not return any value. The format of the start and end dates are one of the following: o Jn: The Julian day n (1 <= n <= 365). o n: The zero-based Julian day (0 <= n <= 365). o Mm. so in all years February 28 is day 59 and March 1 is day 60.d: The d'th day (0 <= d <= 6) or week n of month m of the year (1 <= n <= 5. Syntax Following is the syntax for tzset() method: time. The calendar Module The calendar module supplies calendar-related functions. Here is a list of functions available with the calendar module: Sr.calendar(year. Python print time.timezone 1 Attribute time. time.c=6) 179 . To change this. call calendar. including functions to print a text calendar for a given month or year. <=0 in most of Europe. No. By default.strftime('%X %x %Z') When we run above program. it produces following result: 13:00:40 02/17/09 EST 05:00:40 02/18/09 AEDT There are following two important attributes available with time module: Sr.w=2.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas. Function with Description 1 calendar. Asia. Africa). time. Attribute with Description No.l=1. calendar takes Monday as the first day of the week and Sunday as the last one. which are the names of the local time zone without and with DST. respectively.tzname 2 Attribute time.tzname is a pair of locale-dependent strings.setfirstweekday() function. l. the second one is the number of days in the month. The first one is the code of the weekday for the 7 first day of the month month in year. 1 and up. Each sublist denotes a week.leapdays(y1. 9 calendar. c=6) 8 Like print calendar.prmonth(year. each line has length 7*w+6. when calendar is first imported.month(year. l=1. w=2.w=2.month. calendar. days within the month are set to their day- of-month.isleap(year) 3 Returns True if year is a leap year.firstweekday( ) 2 Returns the current setting for the weekday that starts each week. l is the number of lines for each week. this is 0.monthrange(year. w.month) Returns two integers. calendar.month) 6 Returns a list of lists of ints. c). Weekday codes are 0 (Monday) to 6 (Sunday). calendar. month numbers are 1 to 12. False. meaning Monday. otherwise. l=1) 180 . Days outside month of year are set to 0.y2) 4 Returns the total number of leap days in the years within range(y1.l=1) 5 Returns a multiline string with a calendar for month of year. each line has length 21*w+18+2*c. calendar. one line per week plus two header lines. calendar. w is the width in characters of each date. w=2.prcal(year. calendar. w is the width in characters of each date. l is the number of lines for each week. By default.y2). Python Returns a multiline string with a calendar for year formatted into three columns separated by c spaces. calendar.calendar(year.monthcalendar(year. month. then here you would find a list of other important modules and functions to play with date & time in Python:  The datetime Module  The pytz Module  The dateutil Module 181 . Weekday codes are 0 (Monday) to 6 (Sunday). Python Like print calendar. Other Modules and Functions If you are interested. w.gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.weekday(year.month(year. Weekday codes are 0 (Monday) to 6 (Sunday).timegm(tupletime) 11 The inverse of time.month. calendar. calendar. month.setfirstweekday(weekday) 10 Sets the first day of each week to weekday code weekday. month numbers are 1 (January) to 12 (December).day) 12 Returns the weekday code for the given date. calendar. l). Here are simple rules to define a function in Python. Functions provide better modularity for your application and a high degree of code reusing.  Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). optionally passing back an expression to the caller.  The statement return [expression] exits a function. Python 14. 182 . As you already know. These functions are called user-defined functions.  The code block within every function starts with a colon (:) and is indented.  The first statement of a function can be an optional statement .  Any input parameters or arguments should be placed within these parentheses. related action. Defining a Function You can define functions to provide the required functionality. Python ─ Functions A function is a block of organized. parameters have a positional behavior and you need to inform them in the same order that they were defined. reusable code that is used to perform a single. Syntax def functionname( parameters ): "function_docstring" function_suite return [expression] By default. A return statement with no arguments is the same as return None.the documentation string of the function or docstring. You can also define parameters inside these parentheses. Python gives you many built-in functions such as print() and but you can also create your own functions. return. you can execute it by calling it from another function or directly from the Python prompt. When the above code is executed. Once the basic structure of a function is finalized. Python Example The following function takes a string as input parameter and prints it on standard screen. specifies the parameters that are to be included in the function and structures the blocks of code. 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. it produces the following result: I'm first call to user defined function! Again second call to the same function 183 . 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. printme("Again second call to the same function"). # Now you can call printme function printme("I'm first call to user defined function!"). 20. For example: #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist. Python Passing by Reference Versus Passing by Value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function. So. 3. 30. mylist return # Now you can call changeme function 184 . #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1.3. [1.3. print "Values inside the function: ". [1. changeme( mylist ). 20.4]. 2. # This would assig new reference in mylist print "Values inside the function: ". 4]] Values outside the function: [10. mylist return # Now you can call changeme function mylist = [10. 4]] There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function. mylist Here.4]). 3.append([1.2. 2.30]. 20. this would produce the following result: Values inside the function: [10.2. the change also reflects back in the calling function. we are maintaining reference of the passed object and appending values in the same object. print "Values outside the function: ". 30. 20. it produces the following result: 185 . 3. 30] Function Arguments You can call a function by using the following types of formal arguments:  Required arguments  Keyword arguments  Default arguments  Variable-length arguments Required Arguments Required arguments are the arguments passed to a function in correct positional order.20. 2.30]. return. 4] Values outside the function: [10. changeme( mylist ). mylist The parameter mylist is local to the function changeme. When the above code is executed. the number of arguments in the function call should match exactly with the function definition. you definitely need to pass one argument. The function accomplishes nothing and finally this would produce the following result: Values inside the function: [1. To call the function printme(). print "Values outside the function: ". Changing mylist within the function does not affect mylist. otherwise it gives a syntax error as follows: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str. Python mylist = [10. # Now you can call printme function printme(). Here. You can also make keyword calls to the printme() function in the following ways: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str. When you use keyword arguments in a function call. return. it produces the following result: My string The following example gives more clear picture. the caller identifies the arguments by the parameter name.py". in <module> printme(). age ): "This prints a passed info into this function" print "Name: ". This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. #!/usr/bin/python # Function definition is here def printinfo( name. Python Traceback (most recent call last): File "test. When the above code is executed. # Now you can call printme function printme( str = "My string"). Note that the order of parameters does not matter. TypeError: printme() takes exactly 1 argument (0 given) Keyword Arguments Keyword arguments are related to the function calls. line 11. name. 186 . When the above code is executed. name="miki" ). it produces the following result: Name: miki Age 50 Default Arguments A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. it prints default age if it is not passed: #!/usr/bin/python # Function definition is here def printinfo( name. return. print "Age ". name. printinfo( name="miki" ). # Now you can call printinfo function printinfo( age=50. The following example gives an idea on default arguments. age. age = 35 ): "This prints a passed info into this function" print "Name: ". it produces the following result: Name: miki Age 50 Name: miki Age 35 187 . age. Python print "Age ". When the above code is executed. # Now you can call printinfo function printinfo( age=50. name="miki" ). return. 60. *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return. 50 ). These arguments are called variable-length arguments and are not named in the function definition.] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. Syntax for a function with non-keyword variable arguments is this: def functionname([formal_args. it produces the following result: Output is: 10 Output is: 70 60 50 188 . This tuple remains empty if no additional arguments are specified during the function call. Python Variable Length Arguments You may need to process a function for more arguments than you specified while defining the function. Following is a simple example: #!/usr/bin/python # Function definition is here def printinfo( arg1. # Now you can call printinfo function printinfo( 10 ). unlike required and default arguments. printinfo( 70. When the above code is executed. sum( 20..  An anonymous function cannot be a direct call to print because lambda requires an expression. they are not equivalent to inline statements in C or C++. it produces the following result: Value of total : 30 Value of total : 40 189 . arg2: arg1 + arg2. sum( 10.arg2. whose purpose is by passing function stack allocation during invocation for performance reasons. 20 ) When the above code is executed... You can use the lambda keyword to create small anonymous functions. They cannot contain commands or multiple expressions. Python The Anonymous Functions These functions are called anonymous because they are not declared in the standard manner by using the def keyword.  Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.. Syntax The syntax of lambda functions contains only a single statement..  Although it appears that lambda's are a one-line version of a function. # Now you can call sum as a function print "Value of total : ".argn]]:expression Following is the example to show how lambda form of function works: #!/usr/bin/python # Function definition is here sum = lambda arg1. which is as follows: lambda [arg1 [. 20 ) print "Value of total : ".  Lambda forms can take any number of arguments but return just one value in the form of an expression. # Now you can call sum function total = sum( 10. 20 ). A return statement with no arguments is the same as return None. it produces the following result: Inside the function : 30 Outside the function : 30 Scope of Variables All variables in a program may not be accessible at all locations in that program. arg2 ): # Add both the parameters and return them. Python The return Statement The statement return [expression] exits a function. optionally passing back an expression to the caller. All the above examples are not returning any value. You can return a value from a function as follows: #!/usr/bin/python # Function definition is here def sum( arg1. There are two basic scopes of variables in Python:  Global variables  Local variables 190 . The scope of a variable determines the portion of the program where you can access a particular identifier. print "Outside the function : ". This depends on where you have declared a variable. total return total." total = arg1 + arg2 print "Inside the function : ". total When the above code is executed. it produces the following result: Inside the function local total : 30 Outside the function global total : 0 191 . whereas global variables can be accessed throughout the program body by all functions. # This is global variable. Local variables Variables that are defined inside a function body have a local scope. total When the above code is executed. arg2 ): # Add both the parameters and return them. total return total. # Now you can call sum function sum( 10. and those defined outside have a global scope. Python Global vs. print "Inside the function local total : ". print "Outside the function global total : ". 20 ). When you call a function. Following is a simple example: #!/usr/bin/python total = 0. # Here total is local variable. the variables declared inside it are brought into scope. # Function definition is here def sum( arg1. This means that local variables can be accessed only inside the function in which they are declared." total = arg1 + arg2. py def print_func( par ): print "Hello : ". Python 15.print_func("Zara") When the above code is executed.py. Example The Python code for a module named aname normally resides in a file named aname... classes and variables. moduleN] When the interpreter encounters an import statement. A module can also include runnable code. Simply. par return The import Statement You can use any Python source file as a module by executing an import statement in some other Python source file. A module can define functions. A module is a Python object with arbitrarily named attributes that you can bind and reference. Here is an example of a simple module. Python ─ Modules A module allows you to logically organize your Python code. support. For example. module2[. it produces the following result: Hello : Zara 192 . Grouping related code into a module makes the code easier to understand and use. a module is a file consisting of Python code. The import has the following syntax: import module1[. to import the module hello.. it imports the module if the module is present in the search path. you need to put the following command at the top of the script: #!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support. A search path is a list of directories that the interpreter searches before importing a module.py. This prevents the module execution from happening over and over again if multiple imports occur.import has the following syntax: from modname import name1[. 193 . The from.. to import the function fibonacci from the module fib. the Python interpreter searches for the module in the following sequences:  The current directory. Python then searches each directory in the shell variable PYTHONPATH. Python checks the default path.  If the module isn't found. however.. Locating Modules: When you import a module. . nameN]] For example. regardless of the number of times it is imported..  If all else fails.. On UNIX.. The from. The from. name2[. use the following statement: from fib import fibonacci This statement does not import the entire module fib into the current namespace. it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.. Python A module is loaded only once. this default path is normally /usr/local/lib/python/..import * Statement: It is also possible to import all names from a module into the current namespace by using the following import statement: from modname import * This provides an easy way to import all the items from a module into the current namespace.import Statement Python's from statement lets you import specific attributes from a module into the current namespace. this statement should be used sparingly.. However. in order to assign a value to a global variable within a function.path variable contains the current directory. Python makes educated guesses on whether variables are local or global. The sys. The syntax of PYTHONPATH is the same as that of the shell variable PATH. A Python statement can access variables in a local namespace and in the global namespace. therefore Python assumes Money as a local variable. Each function has its own local namespace. If a local and a global variable have the same name. we define a variable Money in the global namespace. Within the functionMoney. PYTHONPATH. we accessed the value of the local variable Money before setting it. Python stops searching the local namespace for the variable. we assign Money a value. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). Here is a typical PYTHONPATH from a Windows system: set PYTHONPATH=c:\python20\lib. Python The module search path is stored in the system module sys as the sys. The PYTHONPATH Variable The PYTHONPATH is an environment variable. the local variable shadows the global variable. and the installation-dependent default. Therefore. you must first use the global statement. so an UnboundLocalError is the result. It assumes that any variable assigned a value in a function is local. consisting of a list of directories. And here is a typical PYTHONPATH from a UNIX system: set PYTHONPATH=/usr/local/lib/python Namespaces and Scoping Variables are names (identifiers) that map to objects. 194 .path variable. Uncommenting the global statement fixes the problem. Class methods follow the same scoping rule as ordinary functions. The statement global VarName tells Python that VarName is a global variable. For example. 'sinh'. Following is a simple example: #!/usr/bin/python # Import built-in module math import math content = dir(math) print content. and __file__ is the filename from which the module was loaded. 'sqrt'. 'exp'. 'frexp'. 'sin'. 'asin'. 'log'. 'radians'. 'degrees'. 'pow'. 'cos'. Python #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money The dir( ) Function The dir() built-in function returns a sorted list of strings containing the names defined by a module. 'fabs'. 'fmod'. the special string variable __name__ is the module's name. 'atan'. 'pi'. 'tanh'] Here. 'modf'. 'tan'. 'hypot'. 'atan2'. 195 . 'ldexp'. 'ceil'. 'floor'. '__name__'. 'log10'. it produces the following result: ['__doc__'. 'cosh'. '__file__'. 'e'. The list contains the names of all the modules. When the above code is executed. 'acos'. variables and functions that are defined in a module. The reload() Function When the module is imported into a script. it will return all the names that can be accessed globally from that function. The syntax of the reload() function is this: reload(module_name) Here. For example.py available in Phone directory. Consider a file Pots. to reload hello module. The reload() function imports a previously imported module again. This file has following line of source code: #!/usr/bin/python def Pots(): print "I'm Pots Phone" 196 .  If globals() is called from within a function. you can use the reload()function. and so on. if you want to reexecute the top-level code in a module. The return type of both these functions is dictionary. Python The globals() and locals() Functions The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called.  If locals() is called from within a function. module_name is the name of the module you want to reload and not the string containing the module name. Therefore. Therefore. do the following: reload(hello) Packages in Python A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub- subpackages. it will return all the names that can be accessed locally from that function. names can be extracted using the keys() function. the code in the top-level portion of a module is executed only once. create one more file __init__.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 After you add these lines to __init__. it produces the following result: I'm Pots Phone I'm 3G Phone I'm ISDN Phone In the above example. you need to put explicit import statements in __init__. #!/usr/bin/python # Now import your Phone Package. Python Similar way. import Phone Phone. we have taken example of a single functions in each file.py in Phone directory:  Phone/__init__.Pots() Phone.py To make all of your functions available when you've imported Phone.G3() When the above code is executed.py file having function Isdn()  Phone/G3.Isdn() Phone. 197 . we have another two files having different functions with the same name as above:  Phone/Isdn.py. but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes. you have all of these classes available when you import the Phone package.py file having function G3() Now. which by default comes from the keyboard. Python 16. str This prompts you to enter any string and it would display same string on the screen. #!/usr/bin/python str = raw_input("Enter your input: "). For more functions. its output is like this: 198 . Printing to the Screen The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas.". Python ─ Files I/O This chapter covers all the basic I/O functions available in Python. please refer to standard Python documentation. isn't it? Reading Keyboard Input Python provides two built-in functions to read a line of text from standard input. print "Received input is : ". These functions are:  raw_input  input The raw_input Function The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline). "isn't it?". This produces the following result on your standard screen: Python is really a great language. When I typed "Hello Python!". This function converts the expressions you pass into a string and writes the result to standard output as follows: #!/usr/bin/python print "Python is really a great language. e. we will see how to use actual data files. #!/usr/bin/python str = input("Enter your input: "). access_mode][. This function creates a file object. The open Function Before you can read or write a file. str This would produce the following result against the entered input: Enter your input: [x*5 for x in range(2. Syntax file object = open(file_name [.  access_mode: The access_mode determines the mode in which the file has to be opened. print "Received input is : ". You can do your most of the file manipulation using a file object. 20. Python provides basic functions and methods necessary to manipulate files by default. i. Python Enter your input: Hello Python Received input is : Hello Python The input Function The input([prompt]) function is equivalent to raw_input. buffering]) Here are parameter details:  file_name: The file_name argument is a string value that contains the name of the file that you want to access. you have to open it using Python's built- in open()function.2)] Recieved input is : [10. read. etc. Now. A complete list of possible values 199 .. you have been reading and writing to the standard input and output.10. which would be utilized to call other support methods associated with it. except that it assumes the input is a valid Python expression and returns the evaluated result to you. 30. 40] Opening and Closing Files Until now. write. append. rb+ Opens a file for both reading and writing in binary format. line buffering is performed while accessing a file. creates a new file for writing. then buffering action is performed with the indicated buffer size. If the file does not exist. The file pointer is placed at the beginning of the file. If you specify the buffering value as an integer greater than 1. Here is a list of the different modes of opening a file: Modes Description r Opens a file for reading only. creates a new file for writing. Python is given below in the table. This is the default mode. This is the default mode. Overwrites the file if the file exists. 200 . Overwrites the existing file if the file exists. creates a new file for reading and writing. w Opens a file for writing only. rb Opens a file for reading only in binary format. If the file does not exist. no buffering takes place.  buffering: If the buffering value is set to 0. This is optional parameter and the default file access mode is read (r). w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist. If negative. wb Opens a file for writing only in binary format. The file pointer is placed at the beginning of the file. creates a new file for reading and writing. The file pointer is placed at the beginning of the file. The file pointer is placed at the beginning of the file. If the file does not exist. Overwrites the file if the file exists. If the buffering value is 1. r+ Opens a file for both reading and writing. the buffer size is the system default (default behavior). wb+ Opens a file for both writing and reading in binary format. name Returns name of the file. file. it creates a new file for reading and writing. 201 . a+ Opens a file for both appending and reading. ab Opens a file for appending in binary format. The file opens in the append mode.softspace Returns false if space explicitly required with print. The file pointer is at the end of the file if the file exists. file. If the file does not exist. Python a Opens a file for appending. ab+ Opens a file for both appending and reading in binary format. The file Object Attributes Once a file is opened and you have one file object. That is. The file opens in the append mode. it creates a new file for writing. If the file does not exist.mode Returns access mode with which file was opened. it creates a new file for writing. you can get various information related to that file. the file is in the append mode.closed Returns true if file is closed. the file is in the append mode. false otherwise. If the file does not exist. it creates a new file for reading and writing. That is. Here is a list of all attributes related to file object: Attribute Description file. file. The file pointer is at the end of the file if the file exists. true otherwise. The file pointer is at the end of the file if the file exists. If the file does not exist. The file pointer is at the end of the file if the file exists. It is a good practice to use the close() method to close a file. fo. fo. fo.closed print "Opening mode : ". Python Example #!/usr/bin/python # Open a file fo = open("foo.close(). fo.txt".txt Closed or not : False Opening mode : wb Softspace flag : 0 The close() Method The close() method of a file object flushes any unwritten information and closes the file object.name print "Closed or not : ".mode print "Softspace flag : ". "wb") print "Name of the file: ".softspace This produces the following result: Name of the file: foo. fo. "wb") print "Name of the file: ". Syntax fileObject. Python automatically closes a file when the reference object of a file is reassigned to another file.txt".close() 202 . after which no more writing can be done.name # Close opend file fo. Example #!/usr/bin/python # Open a file fo = open("foo. Here. "wb") fo. Python is a great language. The write() Method The write() method writes any string to an open file.txt".close() The above method would create foo. it would have following content. Example #!/usr/bin/python # Open a file fo = open("foo. # Close opend file fo. Python This produces the following result: Name of the file: foo. passed parameter is the content to be written into the opened file.txt file and would write given content in that file and finally it would close that file.write( "Python is a great language.write(string). If you would open this file.txt Reading and Writing Files The file object provides a set of access methods to make our lives easier. The write() method does not add a newline character ('\n') to the end of the string: Syntax fileObject. Yeah its great!! 203 . We would see how to use read() and write() methods to read and write files.\nYeah its great!!\n"). It is important to note that Python strings can have binary data and not just text. Syntax fileObject. from]) method changes the current file position. This method starts reading from the beginning of the file and if count is missing. maybe until the end of file. Python The read() Method The read() method reads a string from an open file. str # Close opend file fo.close() This produces the following result: Read String is : Python is File Positions The tell() method tells you the current position within the file.txt. apart from text data.read(10). Here. then it tries to read as much as possible. which we created above. If from is set to 0. #!/usr/bin/python # Open a file fo = open("foo. print "Read String is : ". in other words. the next read or write will occur at that many bytes from the beginning of the file. The from argument specifies the reference position from where the bytes are to be moved.read([count]).txt". Example Let us take a file foo. The seek(offset[. "r+") str = fo. It is important to note that Python strings can have binary data. 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. 204 . passed parameter is the number of bytes to be read from the opened file. The offset argument indicates the number of bytes to be moved. str # Close opend file fo.tell(). print "Current file position : ".read(10).txt". str = fo. "r+") str = fo. such as renaming and deleting files. position # Reposition pointer at the beginning once again position = fo. print "Again read String is : ".close() This produces the following result: Read String is : Python is Current file position : 10 Again read String is : Python is Renaming and Deleting Files Python os module provides methods that help you perform file-processing operations.read(10). str # Check current position position = fo. Python Example Let us take a file foo. 0).txt. #!/usr/bin/python # Open a file fo = open("foo. which we created above.seek(0. print "Read String is : ". 205 . To use this module you need to import it first and then you can call any related functions. the current filename and the new filename.rename( "test1. Python The rename() Method The rename() method takes two arguments. "test2.txt os. Syntax os.remove("text2.txt: #!/usr/bin/python import os # Rename a file from test1. new_file_name) Example Following is the example to rename an existing file test1.txt".txt" ) The remove() Method You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.txt: #!/usr/bin/python import os # Delete file test2.txt os. Syntax os.remove(file_name) Example Following is the example to delete an existing file test2.txt to test2.txt") 206 .rename(current_file_name. remove. The chdir() method takes an argument. and change directories. Syntax os.chdir("newdir") 207 . You need to supply an argument to this method which contains the name of the directory to be created. which is the name of the directory that you want to make the current directory. The mkdir() Method You can use the mkdir() method of the os module to create directories in the current directory. Python Directories in Python All files are contained within various directories. Syntax os. and Python has no problem handling these too.mkdir("test") The chdir() Method You can use the chdir() method to change the current directory.mkdir("newdir") Example Following is the example to create a directory test in the current directory: #!/usr/bin/python import os # Create a directory "test" os. The os module has several methods that help you create. rmdir('dirname') 208 . Python Example Following is the example to go into "/home/newdir" directory: #!/usr/bin/python import os # Changing a directory to "/home/newdir" os.getcwd() The rmdir() Method The rmdir() method deletes the directory.getcwd() Example Following is the example to give current directory: #!/usr/bin/python import os # This would give location of the current directory os.chdir("/home/newdir") The getcwd() Method The getcwd() method displays the current working directory. all the contents in it should be removed. which is passed as an argument in the method. Before removing a directory. Syntax os. Syntax os. file.next() 5 Returnss the next line from the file each time it is being called. which provide a wide range of utility methods to handle and manipulate files and directories on Windows and Unix operating systems. 209 .isatty() 4 Returns True if the file is connected to a tty(-like) device. They are as follows: File Object Methods: The file object provides functions to manipulate files.close() 1 Close the file. Python Example Following is the example to remove "/tmp/test" directory. otherwise it would search for that directory in the current directory. os. It is required to give fully qualified name of the directory. #!/usr/bin/python import os # This would remove "/tmp/test" directory. file. else False.rmdir( "/tmp/test" ) File and Directory Related Methods There are two important sources. Methods with Description file. A closed file cannot be read or written any more.read([size]) 6 Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).flush() 2 Flush the internal buffer. file. file. No. This may be a no-op on some file- like objects. file.fileno() 3 Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system. like stdio's fflush. A file object is created using open function and here is a list of functions which can be called on this object: Sr. OS Object Methods: This provides methods to process files as well as directories. Parameters NA Return Value This method does not return any value. It is a good practice to use the close() method to close a file. If the 8 optional sizehint argument is present.close() The method close() closes the opened file. file.tell() 10 Returns the file's current position file. 210 . Python file.whence]) 9 Sets the file's current position. There is no return value. typically a list of strings.seek(offset[.writelines(sequence) 13 Writes a sequence of strings to the file. file. file. If the optional size argument is present. the file is truncated to (at most) that size. whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Syntax Following is the syntax for close() method: fileObject. file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines. The sequence can be any iterable object producing strings. file.readline([size]) 7 Reads one entire line from the file. A trailing newline character is kept in the string. file. Any operation.write(str) 12 Writes a string to the file. which requires that the file be opened will raise a ValueError after the file has been closed. Python automatically closes a file when the reference object of a file is reassigned to another file. Calling close() more than once is allowed. instead of reading up to EOF. A closed file cannot be read or written any more.close().truncate([size]) 11 Truncates the file's size. "wb") print "Name of the file: ". #!/usr/bin/python # Open a file fo = open("foo.name # Close opend file fo. fo. This may be a no- op on some file-like objects.txt". Example The following example shows the usage of flush() method. But you may want to flush the data before closing any file.close() When we run above program.txt". Python automatically flushes the files when closing them. Parameters NA Return Value This method does not return any value. "wb") 211 . it produces following result: Name of the file: foo. like stdio's fflush.txt File.flush() The method flush() flushes the internal buffer. Syntax Following is the syntax for flush() method: fileObject. #!/usr/bin/python # Open a file fo = open("foo. Python Example The following example shows the usage of close() method.flush(). Syntax Following is the syntax for fileno() method: fileObject.fileno(). Parameters NA Return Value This method returns the integer file descriptor.txt".txt File. fo.name fid = fo.fileno() The method fileno() returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.flush() # Close opend file fo. but you can call it with read operation.name # Here it does nothing.fileno() print "File Descriptor: ". fid 212 . fo. fo. it produces following result: Name of the file: foo. "wb") print "Name of the file: ". #!/usr/bin/python # Open a file fo = open("foo. Python print "Name of the file: ".close() When we run above program. Example The following example shows the usage of fileno() method. fo.isatty(). else False.txt". else false.close() When we run above program.isatty() print "Return value : ". Syntax Following is the syntax for isatty() method: fileObject. Example The following example shows the usage of isatty() method. Python # Close opend file fo.txt File Descriptor: 3 File.isatty() The method isatty() returns True if the file is connected (is associated with a terminal device) to a tty(-like) device. #!/usr/bin/python # Open a file fo = open("foo. "wb") print "Name of the file: ". Parameters NA Return Value This method returns true if the file is connected (is associated with a terminal device) to a tty(-like) device.name ret = fo. it produces following result: Name of the file: foo. ret # Close opend file 213 . Python fo. Combining next() method with other file methods like readline() does not work right.close() When we run above program.next() The method next() is used when a file is used as an iterator. typically in a loop. "rw+") print "Name of the file: ". it produces following result: Name of the file: foo.next(). Parameters NA Return Value This method returns the next input line. usingseek() to reposition the file to an absolute position will flush the read- ahead buffer. or raises StopIteration when EOF is hit. the next() method is called repeatedly. Example The following example shows the usage of next() method. #!/usr/bin/python # Open a file fo = open("foo.txt Return value : False File.txt".name # Assuming file has following 5 lines # This is 1st line 214 . However. This method returns the next input line. Syntax Following is the syntax for next() method: fileObject. fo. then it reads only available bytes.close() When we run above program.read([size]) The method read() reads at most size bytes from the file.This is 2nd line Line No 2 . Parameters  size -. line) # Close opend file fo.%s" % (index.This is 4th line Line No 4 .read( size ).txt Line No 0 .This is the number of bytes to be read from the file. 215 .This is 5th line File. Return Value This method returns the bytes read in string. If the read hits EOF before obtaining size bytes.This is 3rd line Line No 3 . it produces following result: Name of the file: foo. Syntax Following is the syntax for read() method: fileObject. Python # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line for index in range(5): line = fo.next() print "Line No %d .This is 1st line Line No 1 . Python Example The following example shows the usage of read() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.read(10) print "Read Line: %s" % (line) # Close opend file fo.close() When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1s File.readline([size]) The method readline() reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. 216 Python Syntax Following is the syntax for readline() method: fileObject.readline( size ); Parameters size -- This is the number of bytes to be read from the file. Return Value This method returns the line read from the file. Example The following example shows the usage of readline() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) line = fo.readline(5) print "Read Line: %s" % (line) # Close opend file fo.close() 217 Python When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1st line Read Line: This file.readline([sizehint]) The method readline() reads one entire line from the file. A trailing newline character is kept in the string. If the size argument is present and non-negative, it is a maximum byte count including the trailing newline and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. Syntax Following is the syntax for readline() method: fileObject.readline( size ); Parameters size -- This is the number of bytes to be read from the file. Return Value This method returns the line read from the file. Example The following example shows the usage of readline() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line 218 Python # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) line = fo.readline(5) print "Read Line: %s" % (line) # Close opend file fo.close() When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1st line Read Line: This file.seek(offset[,whence]) The method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write. If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+'). If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. Syntax 219 Python Following is the syntax for seek() method: fileObject.seek(offset[, whence]) Parameters  offset -- This is the position of the read/write pointer within the file.  whence -- This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end. Return Value This method does not return any value. Example The following example shows the usage of seek() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) # Again set the pointer to the beginning fo.seek(0, 0) line = fo.readline() print "Read Line: %s" % (line) 220 Python # Close opend file fo.close() When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1st line Read Line: This is 1st line file.tell() The method tell() returns the current position of the file read/write pointer within the file. Syntax Following is the syntax for tell() method: fileObject.tell() Parameters NA Return Value This method returns the current position of the file read/write pointer within the file. Example The following example shows the usage of tell() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line 221 Python # This is 3rd line # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) # Get the current position of the file. pos = fo.tell() print "Current Position: %d" % (pos) # Close opend file fo.close() When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1st line Current Position: 18 file.truncate([size]) The method truncate() truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.. The size defaults to the current position. The current file position is not changed. Note that if a specifiedsize exceeds the file's current size, the result is platform-dependent. Note: This method would not work in case file is opened in read-only mode. Syntax Following is the syntax for truncate() method: fileObject.truncate( [ size ]) Parameters size -- If this optional argument is present, the file is truncated to (at most) that size. 222 Python Return Value This method does not return any value. Example The following example shows the usage of truncate() method. #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) # Now truncate remaining file. fo.truncate() # Try to read file now line = fo.readline() print "Read Line: %s" % (line) # Close opend file fo.close() When we run above program, it produces following result: Name of the file: foo.txt Read Line: This is 1st line 223 fo. Return Value This method does not return any value. Due to buffering. the string may not actually show up in the file until the flush() or close() method is called. "rw+") print "Name of the file: ". There is no return value. Example The following example shows the usage of write() method. 224 .write( str ) Parameters str -. Syntax Following is the syntax for write() method: fileObject.This is the String to be written in the file.write(str) The method write() writes a string str to the file. Python Read Line: file.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line str = "This is 6th line" # Write a line at the end of the file. #!/usr/bin/python # Open a file in write mode fo = open("foo.txt". %s" % (index.close() When we run above program.seek(0. it produces following result: Name of the file: foo.This is 6th line file.This is 2nd line Line No 2 . 225 . 2) line = fo.txt Line No 0 .0) for index in range(6): line = fo. line) # Close opend file fo.This is 3rd line Line No 3 .next() print "Line No %d .writelines(sequence) The method writelines() writes a sequence of strings to the file. Syntax Following is the syntax for writelines() method: fileObject. fo.writelines( sequence ) Parameters sequence -.This is 1st line Line No 1 . Python fo.This is the Sequence of the strings. typically a list of strings. The sequence can be any iterable object producing strings.write( str ) # Now read complete file from beginning. There is no return value.This is 4th line Line No 4 .This is 5th line Line No 5 .seek(0. Python Return Value This method does not return any value. "This is 7th line"] # Write sequence of lines at the end of the file.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line seq = ["This is 6th line\n".This is 1st line Line No 1 .txt".seek(0. "rw+") print "Name of the file: ". line) # Close opend file fo.txt Line No 0 .next() print "Line No %d . fo. fo. #!/usr/bin/python' # Open a file in witre mode fo = open("foo.close() When we run above program. fo.seek(0.0) for index in range(7): line = fo.%s" % (index.writelines( seq ) # Now read complete file from beginning. Example The following example shows the usage of writelines() method. 2) line = fo. it produces following result: Name of the file: foo.This is 2nd line 226 . flags) 3 Set the flags of path to the numeric flags. os. fd_high) 8 Close all file descriptors from fd_low (inclusive) to fd_high (exclusive). os. os.This is 6th line Line No 6 . os. os. os. ignoring errors.chroot(path) 6 Change the root directory of the current process to path.This is 4th line Line No 4 . gid) 5 Change the owner and group id of path to the numeric uid and gid.chflags(path. os.dup(fd) 9 Return a duplicate of file descriptor fd.chown(path. mode) 4 Change the mode of path to the numeric mode.This is 5th line Line No 5 . Python Line No 2 .close(fd) 7 Close file descriptor fd.access(path. 227 .chmod(path. No.closerange(fd_low.mode) 1 Use the real uid/gid to test for access to path.chdir(path) 2 Change the current working directory to path os. Sr.This is 3rd line Line No 3 .This is 7th line OS Object Methods This provides methods to process files as well as directories. Methods with Description os. uid. os. fd2) 10 Duplicate file descriptor fd to fd2.fstat(fd) 17 Return status for file descriptor fd. like statvfs().fchmod(fd. mode[.fpathconf(fd. os. 228 .fdopen(fd[. like stat(). os. os. mode) 12 Change the mode of the file given by fd to the numeric mode.fchown(fd. os. closing the latter first if necessary. os. uid.ftruncate(fd. Python os.fdatasync(fd) 14 Force write of file with filedescriptor fd to disk.getcwd() 21 Return a string representing the current working directory. gid) 13 Change the owner and group id of the file given by fd to the numeric uid and gid. name specifies the configuration value to retrieve. length) 20 Truncate the file corresponding to file descriptor fd. os. os.getcwdu() 22 Return a Unicode object representing the current working directory.fsync(fd) 19 Force write of file with filedescriptor fd to disk. os. os.fstatvfs(fd) 18 Return information about the filesystem containing the file associated with file descriptor fd. bufsize]]) 15 Return an open file object connected to the file descriptor fd. os. name) 16 Return system configuration information relevant to an open file. os.dup2(fd.fchdir(fd) 11 Change the current working directory to the directory represented by the file descriptor fd. so that it is at most length bytes in size. flags) 24 Set the flags of path to the numeric flags.lchown(path. os. os. os. This function will not follow symbolic links. os.major(device) 31 Extract the device major number from a raw device number. os. os. minor) 32 Compose a raw device number from the major and minor device numbers. os. mode]) 35 Create a directory named path with numeric mode mode.minor(device) 34 Extract the device minor number from a raw device number . else False.mkdir(path[. uid.lchflags(path.lchmod(path. gid) 26 Change the owner and group id of path to the numeric uid and gid. os. os. os. but do not follow symbolic links. os. os. pos. dst) 27 Create a hard link pointing to src named dst. but do not follow symbolic links. how) 29 Set the current position of file descriptor fd to position pos.listdir(path) 28 Return a list containing the names of the entries in the directory given by path.isatty(fd) 23 Return True if the file descriptor fd is open and connected to a tty(-like) device.lseek(fd.lstat(path) 30 Like stat().makedev(major. modified by how.makedirs(path[. mode) 25 Change the mode of path to the numeric mode. like chflags(). mode]) 33 Recursive directory creation function.link(src. 229 . Python os. w) usable for reading and writing. mode=0600.rename(src. os.remove(path) 45 Remove the file path. respectively. os.mknod(filename[. Python os. an empty string is returned.read(fd. mode]) 36 Create a FIFO (a named pipe) named path with numeric mode mode. respectively. If the end of the file referred to by fd has been reached.open(file. os. Return a pair of file descriptors (r. slave) for the pty and the tty. mode[. 230 .pipe() 41 Create a pipe. bufsize]]) 42 Open a pipe to or from command. device special file or named pipe) named filename. os. os. os. os. Return a pair of file descriptors (master. name) 40 Return system configuration information relevant to a named file. os.removedirs(path) 46 Remove directories recursively. n) Read at most n bytes from file descriptor fd. os.mkfifo(path[. mode]) 38 Open the file file and set various flags according to flags and possibly its mode according to mode.popen(command[. The default mode is 0666 (octal). dst) 47 Rename the file or directory src to dst.pathconf(path.openpty() 39 Open a new pseudo-terminal pair. os. flags[. Return a string containing the 43 bytes read. device]) 37 Create a filesystem node (file. os.readlink(path) 44 Return a string representing the path to which the symbolic link points. os. os. new) 48 Recursive directory or file renaming function. os. os.stat_float_times([newvalue]) 51 Determine whether stat_result represents time stamps as float objects. Python os.stat(path) 50 Perform a stat system call on the given path. os. an exception is raised.statvfs(path) 52 Perform a statvfs system call on the given path.rmdir(path) 49 Remove the directory path os.ttyname(fd) Return a string which specifies the terminal device associated with file 59 descriptor fd. 231 .unlink(path) 60 Remove the file path. os. dst) 53 Create a symbolic link pointing to src named dst.symlink(src. prefix]]) 56 Return a unique path name that is reasonable for creating a temporary file.tcgetpgrp(fd) 54 Return the process group associated with the terminal given by fd (an open file descriptor as returned by open()). os. os. pg) 55 Set the process group associated with the terminal given by fd (an open file descriptor as returned by open()) to pg. os.tcsetpgrp(fd. If fd is not associated with a terminal device.tmpnam() 58 Return a unique path name that is reasonable for creating a temporary file. os. os.tempnam([dir[.tmpfile() 57 Return a new file object opened in update mode (w+b).renames(old. walk(top[. topdown=True[. followlinks=False]]]) 62 Generate the file names in a directory tree by walking the tree either top-down or bottom-up.utime(path. os. 232 . Return the number of bytes actually written. os. times) 61 Set the access and modified times of the file specified by path. Python os.write(fd. onerror=None[. str) 63 Write the string str to file descriptor fd. List of Standard Exceptions Exception Name Description Exception Base class for all exceptions Raised when the next() method of an iterator does not point StopIteration to any object. Base class for all built-in exceptions except StopIteration StandardError and SystemExit.exit() function. Python ─ Exceptions Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them:  Exception Handling: This would be covered in this tutorial. Raised when division or modulo by zero takes place for all ZeroDivisonError numeric types. ArithmeticError Base class for all errors that occur for numeric calculation. AttributeError Raised in case of failure of attribute reference or assignment. ImportError Raised when an import statement fails. FloatingPointError Raised when a floating point calculation fails. Raised when a calculation exceeds maximum limit for a OverflowError numeric type. Raised when there is no input from either the raw_input() or EOFError input() function and the end of file is reached. Python 17.  Assertions: This would be covered in Assertions in Python tutorial. 233 . SystemExit Raised by the sys. Here is a list standard Exceptions available in Python: Standard Exceptions. AssertionError Raised in case of failure of the Assert statement. SyntaxError Raised when there is an error in Python syntax. Base class for all exceptions that occur outside the Python EnvironmentError environment. Raised when an input/ output operation fails. Raised when an operation or function is attempted that is TypeError invalid for the specified data type. Raised when an identifier is not found in the local or global NameError namespace. 234 . IndentationError Raised when indentation is not specified properly. but the arguments have invalid values specified. such as the IOError print statement or the open() function when trying to open a file that does not exist. Python Raised when the user interrupts program execution. If not handled in the code. Raised when Python interpreter is quit by using the SystemExit sys.exit() function. IndexError Raised when an index is not found in a sequence. causes the interpreter to exit. usually KeyboardInterrupt by pressing Ctrl+c. Raised when the interpreter finds an internal problem. Raised when trying to access a local variable in a function or UnboundLocalError method but no value has been assigned to it. OSError Raised for operating system-related errors. KeyError Raised when the specified key is not found in the dictionary. but SystemError when this error is encountered the Python interpreter does not exit. LookupError Base class for all lookup errors. Raised when the built-in function for a data type has the ValueError valid type of arguments. Assertions are carried out by the assert statement. Python raises an AssertionError exception. and if the result comes up false. AssertionError exceptions can be caught and handled like any other exception using the try-except statement. Since zero degrees Kelvin is as cold as it gets. a raise-if-not statement). introduced in version 1. but if not handled. Assertions in Python An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. Arguments] If the assertion fails. Python uses ArgumentExpression as the argument for the AssertionError. Programmers often place assertions at the start of a function to check for valid input. The syntax for assert is: assert Expression[.5. An expression is tested. an exception is raised. Python Raised when a generated error does not fall into any RuntimeError category. If the expression is false. Python evaluates the accompanying expression. they will terminate the program and produce a traceback. which is hopefully true. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate. the function bails out if it sees a negative temperature: 235 . the newest keyword to Python. Example Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Raised when an abstract method that needs to be NotImplementedError implemented in an inherited class is not actually implemented. and after a function call to check for valid output. The assert Statement When it encounters an assert statement. Handling an Exception If you have some suspicious code that may raise an exception. when a Python script encounters a situation that it cannot cope with. followed by a block of code which handles the problem as elegantly as possible. When a Python script raises an exception. line 4. it raises an exception.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505. in KelvinToFahrenheit assert (Temperature >= 0).0 451 Traceback (most recent call last): File "test. it must either handle the exception immediately otherwise it terminates and quits. An exception is a Python object that represents an error. which occurs during the execution of a program that disrupts the normal flow of the program's instructions. Python #!/usr/bin/python def KelvinToFahrenheit(Temperature): assert (Temperature >= 0). you can defend your program by placing the suspicious code in a try: block.78)) print KelvinToFahrenheit(-5) When the above code is executed."Colder than absolute zero!" AssertionError: Colder than absolute zero! What is Exception? An exception is an event. After the try: block.py". include an except: statement."Colder than absolute zero!" return ((Temperature-273)*1.py". In general. in <module> print KelvinToFahrenheit(-5) File "test. line 9. it produces the following result: 32. 236 . . The code in the else-block executes if the code in the try: block does not raise an exception... . else: If there is no exception then execute this block...... file and comes out gracefully because there is no problem at all: #!/usr/bin/python try: fh = open("testfile".... you can include an else-clause.else blocks: try: You do your operations here. Example This example opens a file..... except ExceptionII: If there is ExceptionII. then execute this block..... "w") fh..except... ...  After the except clause(s).. Here are few important points about the above-mentioned syntax:  A single try statement can have multiple except statements..write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" 237 ... writes content in the....  You can also provide a generic except clause. then execute this block..... except ExceptionI: If there is ExceptionI.  The else-block is a good place for code that does not need the try: block's protection....... which handles any exception..... Python Syntax Here is simple syntax of try. This is useful when the try block contains statements that may throw different types of exceptions... ... then execute this block....... 238 ...close() This produces the following result: Written content in the file successfully Example This example tries to open a file where you do not have write permission. "r") fh.. Using this kind of try-except statement is not considered a good programming practice though...... so it raises an exception: #!/usr/bin/python try: fh = open("testfile". ......write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" This produces the following result: Error: can't find file or read data The except Clause with No Exceptions You can also use the except statement with no exceptions defined as follows: try: You do your operations here....... Python fh.......... except: If there is any exception.... else: If there is no exception then execute this block. .. This kind of a try-except statement catches all the exceptions that occur.. ..... . then execute this block.. Exception2[... ... .. ... this may be skipped. You cannot use else clause as well along with a finally clause.ExceptionN]]]): If there is any exception from the given exception list. Example 239 ...... The syntax of the try-finally statement is this: try: You do your operations here...... Note that you can provide except clause(s)....... else: If there is no exception then execute this block..... except(Exception1[.... Due to any exception........... The except Clause with Multiple Exceptions You can also use the same except statement to handle multiple exceptions as follows: try: You do your operations here... whether the try-block raised an exception or not. Python because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.. but not both..... or a finally clause. The try-finally Clause You can use a finally: block along with a try: block........ finally: This would always be executed........................ The finally block is a place to put any code that must execute..... write("This is my test file for exception handling!!") finally: print "Going to close the file" fh. The contents of the argument vary by exception.close() except IOError: print "Error: can\'t find file or read data" When an exception is thrown in the try block. the execution immediately passes to the finally block.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data" If you do not have permission to open the file in writing mode. "w") try: fh. 240 . Argument of an Exception An exception can have an argument. You can capture an exception's argument by supplying a variable in the except clause as follows: try: You do your operations here. "w") fh. then this will produce the following result: Error: can't find file or read data Same example can be written more cleanly as follows: #!/usr/bin/python try: fh = open("testfile". which is a value that gives additional information about the problem. Python #!/usr/bin/python try: fh = open("testfile". the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement. After all the statements in the finally block are executed. . This variable receives the value of the exception mostly containing the cause of the exception.. def temp_convert(var): try: return int(var) except ValueError.... and an error location. you can have a variable follow the tuple of the exception.. except ExceptionType... Argument: print "The argument does not contain numbers\n".. temp_convert("xyz").... This tuple usually contains the error string. you can have a variable follow the name of the exception in the except statement. The general syntax for the raise statement is as follows. Example Following is an example for a single exception: #!/usr/bin/python # Define a function here.. The variable can receive a single value or multiple values in the form of a tuple.. Argument # Call above function here..... If you are trapping multiple exceptions.. If you write the code to handle a single exception. This produces the following result: The argument does not contain numbers invalid literal for int() with base 10: 'xyz' Raising an Exception You can raise exceptions in several ways by using the raise statement.. Syntax 241 . the error number. Argument: You can print value of Argument here.. Python ... User-Defined Exceptions Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. a class or an object. args [.. except "Invalid level!": Exception handling here. traceback]]] Here. For example. we must write the except clause as follows: try: Business Logic here. with an argument that is an instance of the class. The final argument. is also optional (and rarely used in practice).. and if present. the exception argument is None. an "except" clause must refer to the same exception thrown either class object or simple string. Most of the exceptions that the Python core raises are classes. 242 . Here is an example related to RuntimeError. The argument is optional. to capture above exception. if not supplied. a class is created that is subclassed from RuntimeError. NameError) and argument is a value for the exception argument. traceback. This is useful when you need to display more specific information when an exception is caught... Here. Defining new exceptions is quite easy and can be done as follows: def functionName( level ): if level < 1: raise "Invalid level!". is the traceback object used for the exception. Python raise [Exception [. level # The code below to this would not be executed # if we raise the exception Note: In order to catch an exception. Example An exception can be a string. Exception is the type of exception (For example. else: Rest of the code here... args = arg So once you defined above class. the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror. Python In the try block. class Networkerror(RuntimeError): def __init__(self.args 243 . arg): self. you can raise the exception as follows: try: raise Networkerror("Bad hostname") except Networkerror.e: print e.  Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.  Instance: An individual object of a certain class. The attributes are data members (class variables and instance variables) and methods. creating and using classes and objects are downright easy. Class variables are not used as frequently as instance variables are. is an instance of the class Circle.  Data member: A class variable or instance variable that holds data associated with a class and its objects. for example. An object obj that belongs to a class Circle. Python 18. you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts. The operation performed varies by the types of objects or arguments involved. If you do not have any previous experience with object-oriented (OO) programming. here is small introduction of Object-Oriented Programming (OOP) to bring you at speed: Overview of OOP Terminology  Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. 244 . This chapter helps you become an expert in using Python's object-oriented programming support.  Function overloading: The assignment of more than one behavior to a particular function.  Instantiation: The creation of an instance of a class. Class variables are defined within a class but outside any of the class's methods. accessed via dot notation.  Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class. Because of this. Python ─ Classes and Objects Python has been an object-oriented language since it existed. However.  Method: A special kind of function that is defined in a class definition.  Class variable: A variable that is shared by all instances of a class.  The class_suite consists of all the component statements defining class members.salary = salary Employee. Example Following is the example of a simple Python class: class Employee: 'Common base class for all employees' empCount = 0 def __init__(self. self.name.empCount def displayEmployee(self): print "Name : ". Creating Classes The class statement creates a new class definition. Salary: ". The name of the class immediately follows the keyword class followed by a colon as follows: class ClassName: 'Optional class documentation string' class_suite  The class has a documentation string.salary 245 . self. data attributes and functions. Python  Object: A unique instance of a data structure that's defined by its class.name = name self. An object comprises both data members (class variables and instance variables) and methods.  Operator overloading: The assignment of more than one function to a particular operator. which can be accessed viaClassName.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee. ".__doc__. salary): self. name.  You declare other class methods like normal functions with the exception that the first argument to each method is self. 5000) Accessing Attributes You access the object's attributes using the dot operator with object. "This would create first object of Employee class" emp1 = Employee("Zara". Creating Instance Objects To create instances of a class.empCount Now.empCount from inside the class or outside the class. Python  The variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee. you call the class using class name and pass in whatever arguments its __init__ method accepts.displayEmployee() print "Total Employee %d" % Employee. putting all the concepts together: #!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self. Python adds the self argument to the list for you. you do not need to include it when you call the methods. Class variable would be accessed using class name as follows: emp1.  The first method __init__() is a special method. name. salary): self.displayEmployee() emp2. 2000) "This would create second object of Employee class" emp2 = Employee("Manni". which is called class constructor or initialization method that Python calls when you create a new instance of this class.name = name 246 . salary "This would create first object of Employee class" emp1 = Employee("Zara". 5000) emp1. emp1. or modify attributes of classes and objects at any time: emp1.value) : to set an attribute.empCount def displayEmployee(self): print "Name : ".salary = salary Employee. del emp1.age # Delete 'age' attribute. it produces the following result: Name : Zara .Salary: 5000 Total Employee 2 You can add.name.  The setattr(obj. remove. name) : to delete an attribute. 247 .age = 7 # Add an 'age' attribute. Python self.name. If attribute does not exist. self. Salary: ". ".name) : to check if an attribute exists or not. self.displayEmployee() print "Total Employee %d" % Employee. 2000) "This would create second object of Employee class" emp2 = Employee("Manni". you can use the following functions:  The getattr(obj.empCount When the above code is executed. name[. then it would be created.displayEmployee() emp2.  The delattr(obj.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.Salary: 2000 Name : Manni .  The hasattr(obj. Instead of using the normal statements to access attributes.age = 8 # Modify 'age' attribute. default]) : to access the attribute of object. salary): self. Python hasattr(emp1. 'age') # Delete attribute 'age' Built-In Class Attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute:  __dict__: Dictionary containing the class's namespace. This attribute is "__main__" in interactive mode.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.salary 248 .name = name self. in the order of their occurrence in the base class list.  __doc__: Class documentation string or none. self. 'age'. 8) # Set attribute 'age' at 8 delattr(empl. ". For the above class let us try to access all these attributes: #!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self.name. if undefined.  __name__: Class name. name.  __module__: Module name in which the class is defined. 'age') # Returns true if 'age' attribute exists getattr(emp1. Salary: ".empCount def displayEmployee(self): print "Name : ". self. 'age') # Returns value of 'age' attribute setattr(emp1.salary = salary Employee.  __bases__: A possibly empty tuple containing the base classes. '__init__': <function __init__ at 0xb7c846bc>} Destroying Objects (Garbage Collection) Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. Employee.__doc__: Common base class for all employees Employee. An object's reference count increases when it is assigned a new name or placed in a container (list.__bases__:".__doc__:". The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.__name__:". tuple. Python print "Employee. An object's reference count changes as the number of aliases that point to it changes.__bases__: () Employee. 'empCount': 2. 'displayCount': <function displayCount at 0xb7c84994>.__doc__ print "Employee. Employee.__dict__:". count of <40> del a # Decrease ref. or dictionary). Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero.__dict__: {'__module__': '__main__'. its reference is reassigned.__name__ print "Employee. The object's reference count decreases when it's deleted with del.__name__: Employee Employee. 'displayEmployee': <function displayEmployee at 0xb7c8441c>. count of <40> 249 .__module__: __main__ Employee. Employee. it produces the following result: Employee.__module__:". a = 40 # Create object <40> b = a # Increase ref. When an object's reference count reaches zero. or its reference goes out of scope. Python collects it automatically.__dict__ When the above code is executed. Employee.__bases__ print "Employee. count of <40> c = [b] # Increase ref. count of <40> b = 100 # Decrease ref.__module__ print "Employee. '__doc__': 'Common base class for all employees'. Employee. x=0. id(pt3) # prints the ids of the obejcts del pt1 del pt2 del pt3 When the above code is executed.x = x self.__name__ print class_name. called a destructor. This method might be used to clean up any non-memory resources used by an instance. 250 . you should define your classes in separate file. count of <40> You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. it produces following result: 3083401324 3083401324 3083401324 Point destroyed Note: Ideally. id(pt2). Python c[0] = -1 # Decrease ref. y=0): self.__class__. then you should import them in your main program file using import statement. that is invoked when the instance is about to be destroyed.y = y def __del__(self): class_name = self. "destroyed" pt1 = Point() pt2 = pt1 pt3 = pt1 print id(pt1). Example This __del__() destructor prints the class name of an instance that is about to be destroyed: #!/usr/bin/python class Point: def __init( self. But a class can implement the special method __del__(). A child class can also override data members and methods from the parent... however. 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.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" 251 .parentAttr = attr def getAttr(self): print "Parent attribute :". . a list of base classes to inherit from is given after the class name: class SubClassName (ParentClass1[. Python Class Inheritance Instead of starting from scratch. Parent. Syntax Derived classes are declared much like their parent class.]): 'Optional class documentation string' class_suite Example #!/usr/bin/python class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self. ParentClass2. attr): Parent. you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name. sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.. 252 . class B: # define your calss B .  The isinstance(obj. class C(A... it produces the following result: Calling child constructor Calling child method Calling parent method Parent attribute : 200 Similar way.getAttr() # again call parent's method When the above code is executed.. Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class Overriding Methods You can always override your parent class methods.. you can drive a class from multiple parent classes as follows: class A: # define your class A ..  The issubclass(sub..setAttr(200) # again call parent's method c.. Python def childMethod(self): print 'Calling child method' c = Child() # instance of child c..parentMethod() # calls parent's method c. One reason for overriding parent's methods is because you may want special or different functionality in your subclass. B): # subclass of A and B . You can use issubclass() or isinstance() functions to check a relationships of two classes and instances...childMethod() # child calls its method c.. args. No. and Sample Call __init__ ( self [. deletes an object Sample Call : del obj __repr__( self ) 3 Evaluatable string representation Sample Call : repr(obj) 253 ... Python Example #!/usr/bin/python class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c. it produces the following result: Calling child method Base Overloading Methods Following table lists some generic functionality that you can override in your own classes: Sr. Method.] ) 1 Constructor (with any optional arguments) Sample Call : obj = className(args) __del__( self ) 2 Destructor. Description.myMethod() # child calls overridden method When the above code is executed. b) def __add__(self.b) v1 = Vector(2. You could. Python __str__( self ) 4 Printable string representation Sample Call : str(obj) __cmp__ ( self. however.other): return Vector(self.a + other. a.a = a self. self. it produces the following result: 254 . b): self. define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation: Example #!/usr/bin/python class Vector: def __init__(self. self. what happens when you use the plus operator to add them? Most likely Python will yell at you. %d)' % (self.a.a.10) v2 = Vector(5. x ) 5 Object comparison Sample Call : cmp(obj. x) Overloading Operators Suppose you have created a Vector class to represent two-dimensional vectors.-2) print v1 + v2 When the above code is executed.b + other.b = b def __str__(self): return 'Vector (%d. . Python Vector(7.._className__attrName... and those attributes then are not be directly visible to outsiders....8) Data Hiding An object's attributes may or may not be visible outside the class definition.count() counter.. in <module> print counter... If you would replace your last line as following. You need to name attributes with a double underscore prefix._JustCounter__secretCount 255 ....__secretCount counter = JustCounter() counter..__secretCount AttributeError: JustCounter instance has no attribute '__secretCount' Python protects those members by internally changing the name to include the class name. then it works for you: .. You can access such attributes as object.py".. it produces the following result: 1 2 Traceback (most recent call last): File "test.__secretCount += 1 print self..... print counter..__secretCount When the above code is executed.count() print counter. line 12.... Example #!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self. Python When the above code is executed. it produces the following result: 1 2 2 256 . The module re provides full support for Perl-like regular expressions in Python. which are listed in the table below. The match Function This function attempts to match RE pattern to string with optional flags. string. To avoid any confusion while dealing with regular expressions. These are flags modifiers. which would have special meaning when they are used in regular expression. But a small thing first: There are various characters. flags=0) Here is the description of the parameters: Parameter Description pattern This is the regular expression to be matched.error if an error occurs while compiling or using a regular expression. Here is the syntax for this function: re. Python ─ Regular Expressions A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings. Python 19. The re module raises the exception re.match(pattern. Regular expressions are widely used in UNIX world. we would use Raw Strings as r'expression'. using a specialized syntax held in a pattern. This is the string. which would be used to handle regular expressions. 257 . We would cover two important functions. which would be searched to match the pattern string at the beginning of string. You can specify different flags using bitwise OR (|). matchObj.match( r'(. Match Object Description Methods group(num=0) This method returns entire match (or specific subgroup num) groups() This method returns all matching subgroups in a tuple (empty if there weren't any) Example #!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.*) are (. Python The re. none on failure. matchObj. We usegroup(num) or groups() function of match object to get matched expression. line.group(1) print "matchObj.*?) .I) if matchObj: print "matchObj. re.M|re.group(1) : Cats matchObj.group(2) : smarter 258 .group() : Cats are smarter than dogs matchObj.group(2) else: print "No match!!" When the above code is executed.group() : ".match function returns a match object on success. it produces following result: matchObj. matchObj.group() print "matchObj.group(1) : ".group(2) : ".*'. *?) . which are listed in the table below. These are flags modifiers.*'. Here is the syntax for this function: re. You can specify different flags using bitwise OR (|). The re.*) are (.search( r'(. This is the string. We use group(num) or groups() function of match object to get matched expression.search(pattern. flags=0) Here is the description of the parameters: Parameter Description pattern This is the regular expression to be matched. Match Object Description Methods group(num=0) This method returns entire match (or specific subgroup num). none on failure. string. Python The search Function This function searches for first occurrence of RE pattern within string with optional flags. searchObj = re. This method returns all matching subgroups in a tuple (empty groups() if there weren't any). re. which is searched to match the pattern anywhere string in the string.M|re.I) 259 . Example #!/usr/bin/python import re line = "Cats are smarter than dogs".search function returns a match object on success. line. group(2) else: print "Nothing found!!" When the above code is executed.group() else: print "Nothing found!!" When the above code is executed.search( r'dogs'.group() : Cats are smarter than dogs matchObj. re. matchObj.match( r'dogs'. searchObj.group() else: print "No match!!" searchObj = re.group(2) : smarter Matching Versus Searching Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string.M|re.I) if searchObj: print "search --> searchObj.group() : ".group(1) : ". matchObj = re.group() : ". it produces the following result: 260 . searchObj. line. it produces following result: matchObj.group(1) : Cats matchObj.group() print "searchObj.M|re.group(1) print "searchObj. searchObj. searchObj. re. Python if searchObj: print "searchObj. while search checks for a match anywhere in the string (this is what Perl does by default).group() : ".group(2) : ". line.I) if matchObj: print "match --> matchObj. Example #!/usr/bin/python import re line = "Cats are smarter than dogs". Example #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re. "". string. substituting all occurrences unless max provided.sub(pattern.group() : dogs Search and Replace One of the most important re methods that use regular expressions is sub. The modifiers are specified as an optional flag. This method returns modified string. it produces the following result: Phone Num : 2004-959-559 Phone Num : 2004959559 Regular-Expression Modifiers: Option Flags Regular expression literals may include an optional modifier to control various aspects of matching. Syntax re. num # Remove anything other than digits num = re. phone) print "Phone Num : ".sub(r'#. max=0) This method replaces all occurrences of the RE pattern in string with repl.sub(r'\D'. phone) print "Phone Num : ". num When the above code is executed. Python No match!! search --> matchObj.*$'. repl. You can provide multiple 261 . "". This flag re. Python modifiers using exclusive OR (|). 262 . including a newline. re. This interpretation re.U affects the behavior of \w. $ Matches end of line. Following table lists the regular expression syntax that is available in Python: Pattern Description ^ Matches beginning of line. Interprets words according to the current locale. . Permits "cuter" regular expression syntax. (+ ? . \W. Makes $ match the end of a line (not just the end of the string) and re. Using m option allows it to match newline as well.L affects the alphabetic group (\w and \W). as well as word boundary behavior (\b and \B). You can escape a control character by preceding it with a backslash. \B. Regular-Expression Patterns Except for control characters. Interprets letters according to the Unicode character set.M makes ^ match the start of any line (not just the start of the string). \b.I Performs case-insensitive matching. * ^ $ ( ) [ ] { } | \). all characters match themselves. It ignores whitespace re. as shown previously and may be represented by one of these: Modifier Description re.S Makes a period (dot) match any character. Matches any single character except newline.X (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker. [^. If in parentheses. re{ n. m.] Matches any single character in brackets. or x options within parentheses. (?#. m. or x options within a regular expression. a| b Matches either a or b. or x options within a regular expression. m. (?: re) Groups regular expressions without remembering matched text. (?imx) Temporarily toggles on i. (?-imx) Temporarily toggles off i.. Doesn't have a range... or x options within parentheses. Python [. (?imx: re) Temporarily toggles on i. If in parentheses. (re) Groups regular expressions and remembers matched text. only that area is affected. only that area is affected. m. re{ n.. m} Matches at least n and at most m occurrences of preceding expression. 263 .} Matches n or more occurrences of preceding expression. re? Matches 0 or 1 occurrence of preceding expression.) Comment.. (?-imx: re) Temporarily toggles off i. re{ n} Matches exactly n number of occurrences of preceding expression.] Matches any single character not in brackets re* Matches 0 or more occurrences of preceding expression. (?= re) Specifies position using a pattern. re+ Matches 1 or more occurrence of preceding expression.. Python (?! re) Specifies position using pattern negation. Does not have a range. (?> re) Matches independent pattern without backtracking. \w Matches word characters. \W Matches non-word characters. \s Matches whitespace. Equivalent to [\t\n\r\f]. \S Matches non-whitespace. \d Matches digits. Equivalent to [0-9]. \D Matches non-digits. \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 non-word 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. 264 Python Regular-Expression Examples Literal characters Example Description python 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 digit Special Character Classes Example Description . Match any character except newline 265 Python \d Match a digit: [0-9] \D Match a non-digit: [^0-9] \s Match a whitespace character: [ \t\r\n\f] \S Match non-whitespace: [^ \t\r\n\f] \w Match a single word character: [A-Za-z0-9_] \W Match a non-word character: [^A-Za-z0-9_] Repetition Cases Example Description ruby? Match "rub" or "ruby": the y is optional. ruby* Match "rub" plus 0 or more ys. ruby+ Match "rub" plus 1 or more ys. \d{3} Match exactly 3 digits. \d{3,} Match 3 or more digits. \d{3,5} Match 3, 4, or 5 digits. Nongreedy repetition This matches the smallest number of repetitions: Example Description 266 Python <.*> Greedy repetition: matches "<python>perl>". <.*?> Nongreedy: matches "<python>" in "<python>perl>". Grouping with Parentheses Example Description \D\d+ No group: + repeats \d. (\D\d)+ Grouped: + repeats \D\d pair. ([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc. Backreferences This matches a previously matched group again: Example Description ([Pp])ython&\1ails Match python&pails or Python&Pails. (['"])[^\1]*\1 Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc. Alternatives Example Description python|perl Match "python" or "perl". 267 Python rub(y|le)) Match "ruby" or "ruble". Python(!+|\?) "Python" followed by one or more ! or one ? Anchors This needs to specify match position. Example Description ^Python Match "Python" at the start of a string or internal line. Python$ Match "Python" at the end of a string or line. \APython Match "Python" at the start of a string. Python\Z Match "Python" at the end of a string. \bPython\b Match "Python" at a word boundary. \brub\B \B is non-word boundary: match "rub" in "rube" and "ruby" but not alone. Python(?=!) Match "Python", if followed by an exclamation point. Python(?!!) Match "Python", if not followed by an exclamation point. Special Syntax with Parentheses Example Description R(?#comment) Matches "R". All the rest is a comment. 268 Python R(?i)uby Case-insensitive while matching "uby". R(?i:uby) Same as above rub(?:y|le)) Group only without creating \1 back reference. 269 Python 20. Python ─ CGI Programming The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA. What is CGI?  The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.  The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.  Your browser contacts the HTTP web server and demands for the URL, i.e., filename.  Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.  Web browser takes response from web server and displays either the received file or error message. However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc. 270 Python CGI Architecture The CGI architecture is as follows: Web Server Support and Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as.cgi, but you can keep your files with python extension .py as well. By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file: 271 etc. First CGI Program Here is a simple link. Before running your CGI program. we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell.py UNIX command to make file executable. Python <Directory "/var/www/cgi-bin"> AllowOverride None Options ExecCGI Order allow.py. which is linked to a CGI script called hello. make sure you have change mode of file using chmod 755 hello. #!/usr/bin/python print "Content-type:text/html\r\n\r\n" print '<html>' print '<head>' print '<title>Hello Word .deny Allow from all </Directory> <Directory "/var/www/cgi-bin"> Options All </Directory> Here. then this produces the following output: Hello Word! This is my first CGI program 272 .py. This file is kept in /var/www/cgi-bin directory and it has following content.First CGI Program</title>' print '</head>' print '<body>' print '<h2>Hello Word! This is my first CGI program</h2>' print '</body>' print '</html>' If you click hello. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen. screen. All the HTTP header will be in the following form: HTTP Field Name: Field Content For Example Content-type: text/html\r\n\r\n There are few other important HTTP headers. Python This hello. which you will use frequently in your CGI Programming. Expires: Date A valid date string is in the format 01 Jan 1998 12:00:00 GMT.. It is used by the browser to decide when a page needs to be refreshed. Last-modified: Date The date of last modification of the resource.e. 273 . You Location: URL can use this field to redirect a request to any file. Header Description A MIME string defining the format of the file being Content-type: returned. Example is Content-type:text/html The date the information becomes invalid. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. The URL that is returned instead of the URL requested. HTTP Header The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. which writes its output on STDOUT file. This script can interact with any other external system also to exchange information such as RDBMS. i.py script is a simple Python script. By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. If REMOTE_HOST this information is not available. It is available only for CONTENT_LENGTH POST requests. 274 . This REMOTE_ADDR is useful for logging or authentication. The length of the query information. Set-Cookie: String Set the cookie passed through the string. PATH_INFO The path for the CGI script. The Content-length: N browser uses this value to report the estimated download time for a file. For example. file upload. The IP address of the remote host making the request. It is name of the web browser. The User-Agent request-header field contains information HTTP_USER_AGENT about the user agent originating the request. of the data being returned. CGI Environment Variables All the CGI programs have access to the following environment variables. in bytes. The URL-encoded information that is sent with GET method QUERY_STRING request. then REMOTE_ADDR can be used to get IR address. HTTP_COOKIE Returns the set cookies in the form of key & value pair. Variable Name Description The data type of the content. Python The length. These variables play an important role while writing any CGI program. The fully qualified name of the host making the request. Used when the client is CONTENT_TYPE sending attached content to the server. 275 . Most frequently. os. Python The method used to make the request. print "<font size=+1>Environment</font><\br>".environ.environ[param]) GET and POST Methods You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. These methods are GET Method and POST Method. SERVER_NAME The server's hostname or IP Address SERVER_SOFTWARE The name and version of the software the server is running.keys(): print "<b>%20s</b>: %s<\br>" % (param. Click this link to see the result Get Environment #!/usr/bin/python import os print "Content-type: text/html\r\n\r\n". SCRIPT_NAME The name of the CGI script. browser uses two methods two pass this information to web server. The most common REQUEST_METHOD methods are GET and POST. for param in os. SCRIPT_FILENAME The full path to the CGI script. Here is a small CGI program to list out all the CGI variables. /cgi-bin/hello_get.getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" 276 . cgitb # Create instance of FieldStorage form = cgi. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.py script to handle input given by web browser. Python Passing Information using GET method: The GET method sends the encoded user information appended to the page request.test.py program using GET method. You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method.FieldStorage() # Get data from fields first_name = form. The page and the encoded information are separated by the ? character as follows: http://www.com/cgi-bin/hello.getvalue('first_name') last_name = form.py?first_name=ZARA&last_name=ALI Below is hello_get. The GET method has size limtation: only 1024 characters can be sent in a request string. Never use GET method if you have password or other sensitive information to pass to the server.py?key1=value1&key2=value2 The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Simple URL Example : Get Method Here is a simple URL. We are going to use cgi module. which passes two values to hello_get. which makes it very easy to access passed information: #!/usr/bin/python # Import modules for CGI handling import cgi. you enter First and Last Name and then click submit button to see the result. last_name) print "</body>" print "</html>" This would generate the following result: Hello ZARA ALI Simple FORM Example: GET Method This example passes two values using HTML FORM and submit button. First Name: Submit Last Name: Bottom of Form 277 .Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name. <form action="/cgi-bin/hello_get. We use same CGI script hello_get.py to handle this imput.py" method="get"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> Here is the actual output of the above form. Python print "<head>" print "<title>Hello . getvalue('first_name') last_name = form. This packages the information in exactly the same way as GET methods. last_name) print "</body>" print "</html>" Let us take again same example as above which passes two values using HTML FORM and submit button.py to handle this input.py" method="post"> First Name: <input type="text" name="first_name"><br /> Last Name: <input type="text" name="last_name" /> 278 .getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello . Below is same hello_get. This message comes into the CGI script in the form of the standard input. <form action="/cgi-bin/hello_get. We use same CGI script hello_get. Python Passing Information Using POST Method A generally more reliable method of passing information to a CGI program is the POST method. but instead of sending it as a text string after a ? in the URL it sends it as a separate message.FieldStorage() # Get data from fields first_name = form.py script which handles GET as well as POST method.Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name. #!/usr/bin/python # Import modules for CGI handling import cgi. cgitb # Create instance of FieldStorage form = cgi. Python <input type="submit" value="Submit" /> </form> Here is the actual output of the above form.cgi script to handle input given by web browser for checkbox button. You enter First and Last Name and then click submit button to see the result. #!/usr/bin/python # Import modules for CGI handling import cgi.cgi" method="POST" target="_blank"> <input type="checkbox" name="maths" value="on" /> Maths <input type="checkbox" name="physics" value="on" /> Physics <input type="submit" value="Select Subject" /> </form> The result of this code is the following form: Submit Maths Physics Bottom of Form Below is checkbox. cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields 279 . Here is example HTML code for a form with two checkboxes: <form action="/cgi-bin/checkbox. First Name: Submit Last Name: Bottom of Form Passing Checkbox Data to CGI Program Checkboxes are used when more than one option is required to be selected. Here is example HTML code for a form with two radio buttons: <form action="/cgi-bin/radiobutton. Python if form.getvalue('physics'): physics_flag = "ON" else: physics_flag = "OFF" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Checkbox .getvalue('maths'): math_flag = "ON" else: math_flag = "OFF" if form.py" method="post" target="_blank"> <input type="radio" name="subject" value="maths" /> Maths <input type="radio" name="subject" value="physics" /> Physics <input type="submit" value="Select Subject" /> </form> The result of this code is the following form: 280 .Third CGI Program</title>" print "</head>" print "<body>" print "<h2> CheckBox Maths is : %s</h2>" % math_flag print "<h2> CheckBox Physics is : %s</h2>" % physics_flag print "</body>" print "</html>" Passing Radio Button Data to CGI Program Radio Buttons are used when only one option is required to be selected. py script to handle input given by web browser for radio button: #!/usr/bin/python # Import modules for CGI handling import cgi. Python Submit Maths Physics Bottom of Form Below is radiobutton. cgitb # Create instance of FieldStorage form = cgi.getvalue('subject') else: subject = "Not set" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Radio .FieldStorage() # Get data from fields if form.Fourth CGI Program</title>" print "</head>" print "<body>" print "<h2> Selected Subject is %s</h2>" % subject print "</body>" print "</html>" Passing Text Area Data to CGI Program TEXTAREA element is used when multiline text has to be passed to the CGI Program.getvalue('subject'): subject = form. 281 . .cgi script to handle input given by web browser: #!/usr/bin/python # Import modules for CGI handling import cgi.getvalue('textcontent'): text_content = form. print "<title>Text Area .FieldStorage() # Get data from fields if form. </textarea> <input type="submit" value="Submit" /> </form> The result of this code is the following form: Submit Bottom of Form Below is textarea.py" method="post" target="_blank"> <textarea name="textcontent" cols="40" rows="4"> Type your text here.Fifth CGI Program</title>" print "</head>" print "<body>" 282 . cgitb # Create instance of FieldStorage form = cgi.. Python Here is example HTML code for a form with a TEXTAREA box: <form action="/cgi-bin/textarea.getvalue('textcontent') else: text_content = "Not entered" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>". #!/usr/bin/python # Import modules for CGI handling import cgi.getvalue('dropdown'): subject = form.py" method="post" target="_blank"> <select name="dropdown"> <option value="Maths" selected>Maths</option> <option value="Physics">Physics</option> </select> <input type="submit" value="Submit"/> </form> The result of this code is the following form: Submit Bottom of Form Below is dropdown.FieldStorage() # Get data from fields if form. cgitb # Create instance of FieldStorage form = cgi.getvalue('dropdown') else: subject = "Not entered" 283 .py script to handle input given by web browser. Here is example HTML code for a form with one drop down box: <form action="/cgi-bin/dropdown. Python print "<h2> Entered Text Content is %s</h2>" % text_content print "</body>" Passing Drop Down Box Data to CGI Program Drop Down Box is used when we have many options available but only one or two will be selected. Now. when the visitor arrives at another page on your site.  Domain: The domain name of your site. If this field is blank. Once retrieved. your server knows/remembers what was stored. For a commercial website. using cookies is the most efficient method of remembering and tracking preferences. and other information required for better visitor experience or site statistics. The browser may accept the cookie. then the cookie may only be retrieved with a secure server. commissions. How It Works? Your server sends some data to the visitor's browser in the form of a cookie. the cookie will expire when the visitor quits the browser. one user registration ends after completing many pages. no such restriction exists. If this is blank. Cookies are a plain text data record of 5 variable-length fields:  Expires: The date the cookie will expire. For example. This may be blank if you want to retrieve the cookie from any directory or page. it is stored as a plain text record on the visitor's hard drive. Python print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Dropdown Box .  Secure: If this field contains the word "secure". it is required to maintain session information among different pages. How to maintain user's session information across all the web pages? In many situations. 284 .Sixth CGI Program</title>" print "</head>" print "<body>" print "<h2> Selected Subject is %s</h2>" % subject print "</body>" print "</html>" Using Cookies in CGI HTTP protocol is a stateless protocol. the cookie is available for retrieval. purchases. If it does.  Path: The path to the directory or web page that sets the cookie. \n" print "Content-type:text/html\r\n\r\n" . From this example... #!/usr/bin/python # Import modules for CGI handling from os import environ import cgi. Domain. We use Set- Cookie HTTP header to set cookies... you must have understood how to set cookies. Python  Name=Value: Cookies are set and retrieved in the form of key and value pairs....\r\n" print "Set-Cookie:Expires=Tuesday.. It is optional to set cookies attributes like Expires.. Assuming you want to set UserID and Password as cookies.. These cookies are sent along with HTTP Header before to Content-type field..com.\r\n" print "Set-Cookie:Domain=www. Retrieving Cookies It is very easy to retrieve all the set cookies.\r\n" print "Set-Cookie:Password=XYZ123.tutorialspoint..\r\n" print "Set-Cookie:Path=/perl. Here is an example of how to retrieve cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form: key1=value1....key3=value3. and Path. 31-Dec-2007 23:12:40 GMT". It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.key2=value2.Rest of the HTML Content. cgitb 285 .. Setting the cookies is done as follows: #!/usr/bin/python print "Set-Cookie:UserID=XYZ. Setting up Cookies It is very easy to send cookies to browser. if key == "UserID": user_id = value if key == "Password": password = value print "User ID = %s" % user_id print "Password = %s" % password This produces the following result for the cookies set by above script: User ID = XYZ Password = XYZ123 File Upload Example To upload a file. split(environ['HTTP_COOKIE'].has_key('HTTP_COOKIE'): for cookie in map(strip. The input tag with the file type creates a "Browse" button. '='). value ) = split(cookie. the HTML form must have the enctype attribute set to multipart/form-data.')): (key. Python if environ. <html> <body> <form enctype="multipart/form-data" action="save_file.py" method="post"> <p>File: <input type="file" name="filename" /></p> <p><input type="submit" value="Upload" /></p> </form> </body> </html> The result of this code is the following form: File: Reset Bottom of Form 286 . '. FieldStorage() # Get filename here.file. Python Above example has been disabled intentionally to save people uploading file on our server.filename) open('/tmp/' + fn.) 287 .basename(fileitem. Here is the script save_file.enable() form = cgi. cgitb. but you can try above code with your server.write(fileitem. os import cgitb.py to handle file upload: #!/usr/bin/python import cgi.read()) message = 'The file "' + fn + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html\n <html> <body> <p>%s</p> </body> </html> """ % (message. 'wb'). fileitem = form['filename'] # Test if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid # directory traversal attacks fn = os.path. "rb") str = fo. # Actual File Content will go hear. filename=\"FileName\"\r\n\n". For example.read().txt". fo = open("foo. This HTTP header is be different from the header mentioned in previous section. "/" )) How To Raise a "File Download" Dialog Box? Sometimes.basename(fileitem.replace("\\". name=\"FileName\"\r\n". Python If you run the above script on Unix/Linux. fn = os. then you need to take care of replacing file separator as follows. then its syntax is as follows: #!/usr/bin/python # HTTP Header print "Content-Type:application/octet-stream. if you want make a FileName file downloadable from a given link. This is very easy and can be achieved through HTTP header. it is desired that you want to give option where a user can click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content.filename.close() 288 . print "Content-Disposition: attachment.path. print str # Close opend file fo. otherwise on your windows machine above open() statement should work fine. This API includes the following:  Importing the API module. Python 21. Most Python database interfaces adhere to this standard. 289 . Python ─ Database Access The Python standard for database interfaces is the Python DB-API. It implements the Python Database API v2. The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. What is MySQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python.You must download a separate DB API module for each database you need to access. if you need to access an Oracle database as well as a MySQL database.  Closing the connection We would learn all the concepts using MySQL.  Acquiring a connection with the database. so let us talk about MySQLdb module. For example. you must download both the Oracle and the MySQL database modules.0 and is built on top of the MySQL C API. Python Database API supports a wide range of database servers such as:  GadFly  mSQL  MySQL  PostgreSQL  Microsoft SQL Server 2000  Informix  Interbase  Oracle  Sybase Here is the list of available Python database interfaces: Python Database Interfaces and APIs . You can choose the right database for your application.  Issuing SQL statements and stored procedures. SEX and INCOME.2. you make sure you have MySQLdb installed on your machine. 290 . make sure of the followings:  You have created a database TESTDB.  You have created a table EMPLOYEE in TESTDB.  User ID "testuser" and password "test123" are set to access TESTDB. Just type the following in your Python script and execute it: #!/usr/bin/python import MySQLdb If it produces the following result.py".py build $ python setup. Database Connection Before connecting to a MySQL database.2. Python How do I Install MySQLdb? Before proceeding.gz $ tar -xvf MySQL-python-1.2.py install Note: Make sure you have root privilege to install above module. LAST_NAME.  This table has fields FIRST_NAME.  You have gone through MySQL tutorial to understand MySQL Basics.2. then it means MySQLdb module is not installed: Traceback (most recent call last): File "test.2 $ python setup. download it from MySQLdb Download page and proceed as follows: $ gunzip MySQL-python-1.2.tar. line 3. AGE.  Python module MySQLdb is installed properly on your machine. in <module> import MySQLdb ImportError: No module named MySQLdb To install MySQLdb module.tar $ cd MySQL-python-1. cursor() # execute SQL query using execute() method. otherwise db is set to None."testuser". before coming out. which in turn is used to execute SQL queries.0. then a Connection Object is returned and saved into db for further use. data = cursor. Database version : 5. cursor. Python Example Following is the example of connecting with MySQL database "TESTDB" #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.fetchone() print "Database version : %s " % data # disconnect from server db. Finally.close() While running this script.45 If a connection is established with the datasource.connect("localhost". db object is used to create a cursor object.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. 291 ."test123". Next. it is producing the following result in my Linux machine."TESTDB" ) # prepare a cursor object using cursor() method cursor = db. it ensures that database connection is closed and resources are released. AGE INT."testuser"."TESTDB" ) # prepare a cursor object using cursor() method cursor = db. we are ready to create tables or records into the database tables using execute method of the created cursor. LAST_NAME CHAR(20).execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL.connect("localhost". cursor.cursor() # Drop table if it already exist using execute() method. INCOME FLOAT )""" cursor. Python Creating Database Table Once a database connection is established. Example Let us create Database table EMPLOYEE: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.execute(sql) # disconnect from server db. SEX CHAR(1)."test123".close() 292 . cursor() # Prepare SQL query to INSERT a record into the database.close() Above example can be written as follows to create SQL queries dynamically: 293 . SEX. Python INSERT Operation It is required when you want to create your records into a database table."testuser". INCOME) VALUES ('Mac'.connect("localhost".execute(sql) # Commit your changes in the database db. sql = """INSERT INTO EMPLOYEE(FIRST_NAME. 'M'."TESTDB" ) # prepare a cursor object using cursor() method cursor = db. Example The following example executes SQL INSERT statement to create a record into EMPLOYEE table: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb. 2000)""" try: # Execute the SQL command cursor."test123". 20. AGE.commit() except: # Rollback in case there is any error db. 'Mohan'. LAST_NAME.rollback() # disconnect from server db. ...execute('insert into Login values("%s"... "%s")' % \ 294 ....rollback() # disconnect from server db.. AGE. 'M'.commit() except: # Rollback in case there is any error db.. 2000) try: # Execute the SQL command cursor. \ LAST_NAME. INCOME) \ VALUES ('%s'.cursor() # Prepare SQL query to INSERT a record into the database.... '%s'...connect("localhost". Python #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.... '%d' )" % \ ('Mac'.. '%d'.. user_id = "test123" password = "password" con.execute(sql) # Commit your changes in the database db. sql = "INSERT INTO EMPLOYEE(FIRST_NAME....close() Example Following code segment is another form of execution where you can pass parameters directly: .........."testuser"."test123"."TESTDB" ) # prepare a cursor object using cursor() method cursor = db. 'Mohan'.. '%c'. 20. SEX. password)) ....cursor() # Prepare SQL query to INSERT a record into the database..."test123"..  rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.... Once our database connection is established..  fetchall(): It fetches all the rows in a result set.. sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: 295 . READ Operation READ Operation on any database means to fetch some useful information from the database. Python (user_id... then it retrieves the remaining rows from the result set.......connect("localhost"."TESTDB" ) # prepare a cursor object using cursor() method cursor = db......  fetchone(): It 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.... You can use either fetchone() method to fetch single record or fetchall() method to fetch multiple values from a database table. Example The following procedure querries all the records from EMPLOYEE table having salary more than 1000: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.."testuser".. you are ready to make a query into this database.. If some rows have already been extracted from the result set. sex=%s. Here. age. 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=Mohan. sex. sex=M.lname=%s. income=2000 Update Operation UPDATE Operation on any database means to update one or more records.close() This will produce the following result: fname=Mac.income=%d" % \ (fname. Python # Execute the SQL command cursor. we increase AGE of all the males by one year. lname.execute(sql) # Fetch all the rows in a list of lists.age=%d. The following procedure updates all the records having SEX as 'M'. income ) except: print "Error: unable to fecth data" # disconnect from server db. age=20. which are already available in the database. Example #!/usr/bin/python import MySQLdb # Open database connection 296 . connect("localhost".connect("localhost"."testuser".execute(sql) # Commit your changes in the database db.cursor() 297 .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. 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 db = MySQLdb."TESTDB" ) # prepare a cursor object using cursor() method cursor = db."testuser".close() DELETE Operation DELETE operation is required when you want to delete some records from your database. Python db = MySQLdb."test123".commit() except: # Rollback in case there is any error db."TESTDB" ) # prepare a cursor object using cursor() method cursor = db."test123".rollback() # disconnect from server db. Transactions 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 in a consistent state.0 provides two methods to either commit or rollback a transaction. Example You already know how to implement transactions. Here is again similar example: 298 .close() Performing Transactions Transactions are a mechanism that ensures data consistency. the effects are persistent.  Durability: Once a transaction was committed.execute(sql) # Commit your changes in the database db. The Python DB API 2. Python # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: # Execute the SQL command cursor. even after a system failure.  Isolation: Intermediate results of a transaction are not visible outside the current transaction.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db. then use rollback() method. Here is a simple example to call commit method.rollback() Disconnecting Database To disconnect Database connection. Here is a simple example to call rollback() method. db. no change can be reverted back. db. which gives a green signal to database to finalize the changes.rollback() COMMIT Operation Commit is the operation. 299 . and after this operation. Python # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: # Execute the SQL command cursor.commit() ROLLBACK Operation If you are not satisfied with one or more of the changes and you want to revert back those changes completely.commit() except: # Rollback in case there is any error db. use close() method.execute(sql) # Commit your changes in the database db. Subclass of DatabaseError that refers to errors internal to the InternalError database module. a connection failure. or calling the fetch method for an already canceled or finished statement handle. However. your application would be better off calling commit or rollback explicitly. such as a cursor no longer being active. instead of depending on any of DB lower level implementation details. any outstanding transactions are rolled back by the DB. These errors are generally outside of the control of the Python scripter. The following table lists these exceptions. Subclass of DatabaseError for situations that would damage IntegrityError the relational integrity. Must subclass StandardError. Subclass of DatabaseError that refers to errors such as the OperationalError loss of a connection to the database. Exception Description Warning Used for non-fatal issues. such as uniqueness constraints or foreign keys. Used for errors in the database module. DatabaseError Used for errors in the database.close() If the connection to a database is closed by the user with the close() method. Error Base class for errors. A few examples are a syntax error in an executed SQL statement. The DB API defines a number of errors that must exist in each database module. 300 . Handling Errors There are many sources of errors. Must subclass Error. Must subclass Error. DataError Subclass of DatabaseError that refers to errors in the data. Must subclass StandardError. Python db. not the database InterfaceError itself. Subclass of DatabaseError that refers to trying to call NotSupportedError unsupported functionality. 301 . make sure your MySQLdb has support for that exception. Python Subclass of DatabaseError that refers to errors such as a bad ProgrammingError table name and other things that can safely be blamed on you. Your Python scripts should handle these errors. but before using any of the above exceptions. You can get more information about them by reading the DB API 2.0 specification. At a low level. and so on. This chapter gives you understanding on most famous concept in Networking . PF_X25. The identifier of a network interface: hostname A string. PF_UNIX. PF_INET. or an IPV6 address in colon (and possibly dot) notation 302 . Sockets may be implemented over a number of different channel types: Unix domain sockets. UDP. What is Sockets? Sockets are the endpoints of a bidirectional communications channel. Python also has libraries that provide higher-level access to specific application-level network protocols. Typically zero. and so on. this may be used to identify a variant of a protocol protocol within a domain and type. which can be a host name. Python 22. you can access the basic socket support in the underlying operating system. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest. Sockets have their own vocabulary: Term Description The family of protocols that is used as the transport mechanism. Python ─ Network Programming Python provides two levels of access to network services. Sockets may communicate within a process. such as FTP. a dotted-quad address. and so on. TCP. HTTP. between processes on the same machine. or between processes on different continents. which allows you to implement clients and servers for both connection-oriented and connectionless protocols.Socket Programming. The type of communications between the two endpoints. typically type SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols. domain These values are constants such as AF_INET. or the name of a service. A port port may be a Fixnum port number. This passively accept TCP client connection. port number pair) to s. which has the general syntax: s = socket.listen() This method sets up and start TCP listener. Python A string "<broadcast>". defaulting to 0.socket (socket_family. or An Integer. waiting until s. interpreted as a binary address in host byte order. as explained earlier.socket() function available in socket module.  protocol: This is usually left out. Once you have socket object. you must use the socket. 303 .bind() socket. Following is the list of functions required: Server Socket Methods Method Description This method binds address (hostname. The socket Module To create a socket. which specifies INADDR_ANY. A zero-length string. protocol=0) Here is the description of the parameters:  socket_family: This is either AF_UNIX or AF_INET. then you can use required functions to create your client or server program. socket_type.accept() connection arrives (blocking).  socket_type: This is either SOCK_STREAM or SOCK_DGRAM. s. a string containing a port number. which specifies an INADDR_BROADCAST address. Each server listens for clients calling on one or more ports. 304 .sendto() This method transmits UDP message s.recvfrom() This method receives UDP message s. we use the socket function available in socket module to create a socket object. and then returns a connection object that represents the connection to that client. Python Client Socket Methods Method Description s. Now call bind(hostname. Next. General Socket Methods Method Description s.send() This method transmits TCP message s. A socket object is then used to call other functions to setup a socket server.gethostname() Returns the hostname. This method waits until a client connects to the port you specified.connect() This method actively initiates TCP server connection. call the accept method of the returned object.recv() This method receives TCP message s. A Simple Server To write Internet servers. port) function to specify a port for your service on the given host.close() This method closes socket socket. addr c. s.connect((host.socket() # Create a socket object host = socket.accept() # Establish connection with client. you can read from it like any IO object.socket() # Create a socket object host = socket. This is very simple to create a socket client using Python's socketmodule function. port)) 305 . The following code is a very simple client that connects to a given host and port. print 'Got connection from'. while True: c.gethostname() # Get local machine name port = 12345 # Reserve a port for your service.close() # Close the connection A Simple Client Let us write a very simple client program which opens a connection to a given port 12345 and given host. Once you have a socket open. port ) opens a TCP connection to hostname on the port. Python #!/usr/bin/python # This is server.bind((host.listen(5) # Now wait for client connection. When done.connect(hosname. as you would close a file.py file import socket # Import socket module s = socket. reads any available data from the socket.py file import socket # Import socket module s = socket. remember to close it.send('Thank you for connecting') c.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. The socket. port)) # Bind to the port s. s. and then exits: #!/usr/bin/python # This is client. addr = s. py & # Once server is started run client as follows: $ python client.py to see the result.recv(1024) s. urllib. # Following would start a server in background. 48437) Thank you for connecting Python Internet modules A list of some important modules in Python Network/Internet programming: Protocol Common function Port No Python module HTTP Web pages 80 httplib.0. urllib SMTP Sending email 25 Smtplib POP3 Fetching email 110 Poplib IMAP4 Fetching email 143 Imaplib Telnet Command lines 23 telnetlib 306 .1'. Python print s.close # Close the socket when done Now run this server.py in background and then run above client. xmlrpclib NNTP Usenet news 119 Nntplib FTP File transfers 20 ftplib.0.py This would produce following result: Got connection from ('127. $ python server. Python Gopher Document transfers 70 gopherlib. SMTP. POP. It is recommended to go through the following link to find more detail: Unix Socket Programming. urllib Please check all the libraries mentioned above to work with FTP. and IMAP protocols. It is a vast subject. 307 . Further Readings This was a quick start with Socket Programming. Python Socket Library and Modules. A string with the address of the sender. Python 23. Python provides smtplib module. Here is a simple syntax to create one SMTP object. Try it once: #!/usr/bin/python import smtplib sender = 'from@fromdomain.  The message .A message as a string formatted as specified in the various RFCs. which can later be used to send an e-mail: import smtplib smtpObj = smtplib. You can specify IP address of the host or a domain name like tutorialspoint. which is typically used to do the work of mailing a message. Usually this port would be 25.com> 308 .com' receivers = ['[email protected]( [host [. which handles sending e-mail and routing e-mail between mail servers. port [. Python ─ Sending Email Simple Mail Transfer Protocol (SMTP) is a protocol.  local_hostname: If your SMTP server is running on your local machine. This is optional argument. An SMTP object has an instance method called sendmail.  The receivers . which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. then you need to specify a port. It takes three parameters:  The sender .A list of strings. one for each recipient.com'] message = """From: From Person <from@fromdomain. local_hostname]]] ) Here is the detail of the parameters:  host: This is the host running your SMTP server. Example Here is a simple way to send one e-mail using Python script. then you can specify just localhost as of this option.com.  port: If you are providing host argument. where SMTP server is listening. you have placed a basic e-mail in message. these aren't always used to route mail). and character set to send an HTML e-mail.com> Subject: SMTP e-mail test This is a test e-mail message. Even if you include HTML tags in a text message.com'. and Subject header. Example 309 . content type. While sending an e-mail message. you can specify a Mime version. separated from the body of the e-mail with a blank line. taking care to format the headers correctly. you can use smtplib client to communicate with a remote SMTP server. the from address. Unless you are using a webmail service (such as Hotmail or Yahoo! Mail). it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. your e-mail provider must have provided you with outgoing mail server details that you can supply them. If you are not running an SMTP server on your local machine. """ try: smtpObj = smtplib. as follows: smtplib.SMTP('mail.your-domain. and the destination address as parameters (even though the from and to addresses are within the e-mail itself. receivers. message) print "Successfully sent email" except SMTPException: print "Error: unable to send email" Here. To. then all the content are treated as simple text.sendmail(sender. Python To: To Person <[email protected]('localhost') smtpObj. using a triple quote. 25) Sending an HTML e-mail using Python When you send a text message using Python. To send the mail you use smtpObj to connect to the SMTP server on the local machine and then use the sendmail method along with the message. But Python provides option to send an HTML message as actual HTML message. An e-mail requires a From. Then. receivers. A final boundary denoting the e-mail's final section must also end with two hyphens. message) print "Successfully sent email" except SMTPException: print "Error: unable to send email" Sending Attachments as an E-mail To send an e-mail with mixed content requires to set Content-type header tomultipart/mixed.com> MIME-Version: 1. Try it once: #!/usr/bin/python import smtplib message = """From: From Person <[email protected]> To: To Person <[email protected](sender.</b> <h1>This is headline.0 Content-type: text/html Subject: SMTP HTML e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message. A boundary is started with two hyphens followed by a unique number. Attached files should be encoded with the pack("m") function to have base64 encoding before transmission. text and attachment sections can be specified within boundaries. Python Following is the example to send HTML content as an e-mail.</h1> """ try: smtpObj = smtplib.SMTP('localhost') smtpObj. Example 310 . which cannot appear in the message part of the e-mail. admin@gmail. "rb") filecontent = fo.0 Content-Type: multipart/mixed.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachement. which sends a file /tmp/test.com> Subject: Sending Attachement MIME-Version: 1. marker) # Define the message action part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit 311 . """ # Define the main headers.net> To: To Person <amrood.txt" # Read a file and encode it into base64 format fo = open(filename.com' reciever = 'amrood.read() encodedcontent = base64.txt as an attachment.b64encode(filecontent) # base64 sender = '[email protected]@gmail. Try it once: #!/usr/bin/python import smtplib import base64 filename = "/tmp/test. Python Following is the example. boundary=%s --%s """ % (marker. part1 = """From: From Person <me@fromdomain. filename. filename=%s %s --%s-- """ %(filename. message) print "Successfully sent email" except Exception: print "Error: unable to send email" 312 .marker) # Define the attachment section part3 = """Content-Type: multipart/mixed. name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment. marker) message = part1 + part2 + part3 try: smtpObj = smtplib. reciever. Python %s --%s """ % (body.sendmail(sender.SMTP('localhost') smtpObj. encodedcontent. the thread terminates. Python ─ Multithreading Running several threads is similar to running several different programs concurrently.  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. they care cheaper than processes. kwargs] ) This method call enables a fast and efficient way to create new threads in both Linux and Windows.start_new_thread ( function. A thread has a beginning. Starting a New Thread To spawn another thread. Here. When function returns. The method call returns immediately and the child thread starts and calls function with the passed list of agrs. an execution sequence. args is a tuple of arguments. delay): 313 . Example #!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName. args[. It has an instruction pointer that keeps track of where within its context it is currently running.  Threads sometimes called light-weight processes and they do not require much memory overhead. use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments. Python 24. and a conclusion. you need to call following method available in thread module: thread. 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. time()) ) # Create two threads as follows try: thread.sleep(delay) count += 1 print "%s: %s" % ( threadName.4 provides much more powerful. The Threading Module The newer threading module included with Python 2. ) ) thread.start_new_thread( print_time. it produces the following result: Thread-1: Thu Jan 22 15:42:17 2009 Thread-1: Thu Jan 22 15:42:19 2009 Thread-2: Thu Jan 22 15:42:19 2009 Thread-1: Thu Jan 22 15:42:21 2009 Thread-2: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:23 2009 Thread-1: Thu Jan 22 15:42:25 2009 Thread-2: Thu Jan 22 15:42:27 2009 Thread-2: Thu Jan 22 15:42:31 2009 Thread-2: Thu Jan 22 15:42:35 2009 Although it is very effective for low-level threading.start_new_thread( print_time.ctime(time. high-level support for threads than the thread module discussed in the previous section. 314 . ("Thread-1". ("Thread-2". ) ) except: print "Error: unable to start thread" while 1: pass When the above code is executed. but the thread module is very limited compared to the newer threading module. 4. time. 2. Python count = 0 while count < 5: time. which in turn calls run() method.currentThread(): Returns the number of thread objects in the caller's thread control. 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().  threading. The methods provided by the Thread class are as follows:  run(): The run() method is the entry point for a thread.activeCount(): Returns the number of thread objects that are active.  threading.  setName(): The setName() method sets the name of a thread. Example #!/usr/bin/python import threading 315 . Creating Thread Using Threading Module: To implement a new thread using the threading module. Python The threading module exposes all the methods of the thread module and provides some additional methods:  threading. you have to do the following:  Define a new subclass of the Thread class.args]) method to add additional arguments.  join([time]): The join() waits for threads to terminate. the threading module has the Thread class that implements threading.  start(): The start() method starts a thread by calling the run method. override the run(self [.  getName(): The getName() method returns the name of a thread.  Override the __init_(self [.  Then. In addition to the methods.  isAlive(): The isAlive() method checks whether a thread is still executing.enumerate(): Returns a list of all thread objects that are currently active.args]) method to implement what the thread should do when started. Thread. threadID.ctime(time. 5) print "Exiting " + self. name.name def print_time(threadName.time())) counter -= 1 # Create new threads thread1 = myThread(1.name print_time(self. delay. 1) thread2 = myThread(2.__init__(self) self.name.exit() time.counter = counter def run(self): print "Starting " + self. Python import time exitFlag = 0 class myThread (threading.start() print "Exiting Main Thread" When the above code is executed.start() thread2. "Thread-1". time. counter): while counter: if exitFlag: thread.threadID = threadID self.Thread): def __init__(self. 2) # Start new Threads thread1. "Thread-2". self. counter): threading. it produces the following result: Starting Thread-1 Starting Thread-2 316 .sleep(delay) print "%s: %s" % (threadName.name = name self.counter. the thread blocks and wait for the lock to be released. The release() method of the new lock object is used to release the lock when it is no longer required. The optional blocking parameter enables you to control whether the thread waits to acquire the lock. counter): 317 . name. threadID. Example #!/usr/bin/python import threading import time class myThread (threading. If blocking is set to 0. A new lock is created by calling theLock() method. the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired.Thread): def __init__(self. Python Exiting Main Thread Thread-1: Thu Mar 21 09:10:03 2013 Thread-1: Thu Mar 21 09:10:04 2013 Thread-2: Thu Mar 21 09:10:04 2013 Thread-1: Thu Mar 21 09:10:05 2013 Thread-1: Thu Mar 21 09:10:06 2013 Thread-2: Thu Mar 21 09:10:06 2013 Thread-1: Thu Mar 21 09:10:07 2013 Exiting Thread-1 Thread-2: Thu Mar 21 09:10:08 2013 Thread-2: Thu Mar 21 09:10:10 2013 Thread-2: Thu Mar 21 09:10:12 2013 Exiting Thread-2 Synchronizing Threads The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. The acquire(blocking) method of the new lock object is used to force threads to run synchronously. If blocking is set to 1. which returns the new lock. __init__(self) self. 3) # Free lock to release next thread threadLock.append(thread1) threads.start() # Add threads to thread list threads.acquire() print_time(self. counter): while counter: time. "Thread-2". 1) thread2 = myThread(2.sleep(delay) print "%s: %s" % (threadName. self.ctime(time.Thread. time. delay.start() thread2.append(thread2) # Wait for all threads to complete for t in threads: 318 .name # Get lock to synchronize threads threadLock. Python threading.counter.Lock() threads = [] # Create new threads thread1 = myThread(1.release() def print_time(threadName. "Thread-1".name.time())) counter -= 1 threadLock = threading.name = name self. 2) # Start new Threads thread1.threadID = threadID self.counter = counter def run(self): print "Starting " + self.  full(): the full() returns True if queue is full.  qsize() : The qsize() returns the number of items that are currently in the queue.join() print "Exiting Main Thread" When the above code is executed. otherwise.  put(): The put adds item to a queue. False. it produces the following result: Starting Thread-1 Starting Thread-2 Thread-1: Thu Mar 21 09:11:28 2013 Thread-1: Thu Mar 21 09:11:29 2013 Thread-1: Thu Mar 21 09:11:30 2013 Thread-2: Thu Mar 21 09:11:32 2013 Thread-2: Thu Mar 21 09:11:34 2013 Thread-2: Thu Mar 21 09:11:36 2013 Exiting Main Thread Multithreaded Priority Queue The Queue module allows you to create a new queue object that can hold a specific number of items. False. There are following methods to control the Queue:  get(): The get() removes and returns an item from the queue. Python t. otherwise. Example #!/usr/bin/python 319 .  empty(): The empty( ) returns True if queue is empty. "Two".release() print "%s processing %s" % (threadName. "Thread-2".Lock() workQueue = Queue. "Three".threadID = threadID self.name process_data(self.q = q def run(self): print "Starting " + self.Thread): def __init__(self. "Thread-3"] nameList = ["One". Python import Queue import threading import time exitFlag = 0 class myThread (threading. q): threading.empty(): data = q.name = name self.release() time. q): while not exitFlag: queueLock.acquire() if not workQueue.__init__(self) self. data) else: queueLock. threadID.Thread.sleep(1) threadList = ["Thread-1".get() queueLock.name. "Four". name.Queue(10) threads = [] threadID = 1 320 .name def process_data(threadName.q) print "Exiting " + self. "Five"] queueLock = threading. self. release() # Wait for queue to empty while not workQueue. Python # Create new threads for tName in threadList: thread = myThread(threadID. it produces the following result: Starting Thread-1 Starting Thread-2 321 .put(word) queueLock. workQueue) thread.start() threads. tName.acquire() for word in nameList: workQueue.join() print "Exiting Main Thread" When the above code is executed.append(thread) threadID += 1 # Fill the queue queueLock.empty(): pass # Notify threads it's time to exit exitFlag = 1 # Wait for all threads to complete for t in threads: t. Python Starting Thread-3 Thread-1 processing One Thread-2 processing Two Thread-3 processing Three Thread-1 processing Four Thread-2 processing Five Exiting Thread-3 Exiting Thread-1 Exiting Thread-2 Exiting Main Thread 322 . using DOM exclusively can really kill your resources.  Simple API for XML (SAX) : Here. XML Parser Architectures and APIs: The Python standard library provides a minimal but useful set of interfaces to work with XML. This is useful when your documents are large or you have memory limitations. This is recommended by the World Wide Web Consortium and available as an open standard. What is XML? The Extensible Markup Language (XML) is a markup language much like HTML or SGML. it parses the file as it reads it from disk and the entire file is never stored in memory. Since these two different APIs literally complement each other. On the other hand. 323 . regardless of operating system and/or developmental language. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone. SAX obviously cannot process information as fast as DOM can when working with large files. Python 25. there is no reason why you can not use them both for large projects. Python ─ XML Processing XML is a portable. open source language that allows programmers to develop applications that can be read by other applications. especially if used on a lot of small files. SAX is read-only. while DOM allows changes to the XML file. The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces. you register callbacks for events of interest and then let the parser proceed through the document.  Document Object Model (DOM) API : This is a World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. let's use a simple XML file movies. Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> 324 .xml as an input: <collection shelf="New Arrivals"> <movie title="Enemy Behind"> <type>War. Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title="Trigun"> <type>Anime. Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title="Transformers"> <type>Anime. Python For all our XML code examples. errorhandler must be a SAX ErrorHandler object. xml.ContentHandler. Here are other important methods to understand before proceeding: The make_parser Method Following method creates a new parser object and returns it. the methods startElement(tag. The methods startDocument and endDocument are called at the start and the end of the XML file.parse( xmlfile. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file.sax. The parser object created will be of the first parser type the system finds. If the parser is not in namespace mode. The ContentHandler is called at the start and end of each element. tag is the element tag. the corresponding methods startElementNS and endElementNS are called. attributes) and endElement(tag) are called. errorhandler]) Here is the detail of the parameters:  xmlfile: This is the name of the XML file to read from. and attributes is an Attributes object. Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. xml. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.  contenthandler: This must be a ContentHandler object. Python Parsing XML with SAX APIs SAX is a standard interface for event-driven XML parsing. Here. The method characters(text) is passed character data of the XML file via the parameter text. 325 . contenthandler[. The parse Method Following method creates a SAX parser and uses it to parse a document. otherwise.sax.  errorhandler: If specified.make_parser( [parser_list] ) Here is the detail of the parameters:  parser_list: The optional argument consisting of a list of parsers to use which must all implement the make_parser method. stars = "" self.format = "" self.description = "" # Call when an element starts def startElement(self. Example #!/usr/bin/python import xml. xml. contenthandler[.CurrentData = tag if tag == "movie": print "*****Movie*****" title = attributes["title"] print "Title:". errorhandler]) Here is the detail of the parameters:  xmlstring: This is the name of the XML string to read from.sax. tag. attributes): self.sax. Python The parseString Method There is one more method to create a SAX parser and to parse the specified XML string.year = "" self.  errorhandler: If specified.ContentHandler ): def __init__(self): self.sax class MovieHandler( xml.type = "" self.rating = "" self. errorhandler must be a SAX ErrorHandler object.  contenthandler: This must be a ContentHandler object.CurrentData = "" self.parseString(xmlstring. title # Call when an elements ends 326 . CurrentData == "rating": self.type = content elif self.type elif self.CurrentData == "year": print "Year:".description self. self.description = content if ( __name__ == "__main__"): # create an XMLReader parser = xml.handler.CurrentData == "year": self.CurrentData == "type": self.make_parser() # turn off namepsaces parser.year elif self. Python def endElement(self.setFeature(xml.CurrentData == "format": self.CurrentData == "stars": self.sax.format elif self.stars = content elif self. self.CurrentData == "rating": print "Rating:". content): if self.format = content elif self.rating elif self.stars elif self.CurrentData == "type": print "Type:". self. self.year = content elif self. self.rating = content elif self.CurrentData = "" # Call when a character is read def characters(self.CurrentData == "description": self.sax. 0) 327 . self.CurrentData == "format": print "Format:".feature_namespaces.CurrentData == "stars": print "Stars:". tag): if self.CurrentData == "description": print "Description:". setContentHandler( Handler ) parser.parse("movies. Action Format: DVD Rating: PG Stars: 10 Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG 328 . Thriller Format: DVD Year: 2003 Rating: PG Stars: 10 Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime.xml") This would produce following result: *****Movie***** Title: Enemy Behind Type: War. Science Fiction Format: DVD Year: 1989 Rating: R Stars: 8 Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime. Python # override the default ContextHandler Handler = MovieHandler() parser. xml") collection = DOMTree.documentElement if collection.getElementsByTagName("movie") # Print detail of each movie.dom.dom.parse("movies.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file. Python Stars: 2 Description: Viewable boredom For a complete detail on SAX API documentation.hasAttribute("title"): 329 .parser] ) function of the minidom object to parse the XML file designated by file into a DOM tree object.minidom import parse import xml. Here is the easiest way to quickly load an XML document and to create a minidom object using the xml. The sample phrase calls the parse( file [. please refer to standard Python SAX APIs. The DOM is extremely useful for random-access applications. for movie in movies: print "*****Movie*****" if movie. you have no access to another. SAX only allows you a view of one bit of the document at a time.dom. If you are looking at one SAX element.minidom. #!/usr/bin/python from xml. Parsing XML with DOM APIs The Document Object Model (DOM) is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents.getAttribute("shelf") # Get all the movies in the collection movies = collection.hasAttribute("shelf"): print "Root element : %s" % collection.minidom # Open XML document using minidom parser DOMTree = xml. Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime.data This would produce the following result: Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War.data rating = movie.childNodes[0]. Science Fiction Format: DVD Rating: R Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime.childNodes[0]. Python print "Title: %s" % movie.data description = movie.data format = movie.childNodes[0]. Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS 330 .getElementsByTagName('type')[0] print "Type: %s" % type.getElementsByTagName('format')[0] print "Format: %s" % format.childNodes[0].getElementsByTagName('rating')[0] print "Rating: %s" % rating.getAttribute("title") type = movie.getElementsByTagName('description')[0] print "Description: %s" % description. 331 . Python Rating: PG Description: Viewable boredom For a complete detail on DOM API documentation. please refer to standard Python DOM APIs. We would look this option in this chapter. Example #!/usr/bin/python import Tkinter top = Tkinter.jython. Most important are listed below:  Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.org.  Enter the main event loop to take action against each event triggered by the user.mainloop() 332 .. Creating a GUI application using Tkinter is an easy task. Python when combined with Tkinter provides a fast and easy way to create GUI applications. top. Python 26. which you can find them on the net.  JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www. All you need to do is perform the following steps:  Import the Tkinter module. Python ─ GUI Programming Python provides various options for developing graphical user interfaces (GUIs).  wxPython: This is an open-source Python interface for wxWindowshttp://wxpython.  Add one or more of the above-mentioned widgets to the GUI application. Tkinter Programming Tkinter is the standard GUI library for Python. There are many other interfaces available.Tk() # Code to add widgets will go here.org..  Create the GUI application main window. Canvas polygons and rectangles. There are currently 15 types of widgets in Tkinter. Python This would create the following window: Tkinter Widgets Tkinter provides various controls. We present these widgets as well as a brief description in the following table: Operator Description Button The Button widget is used to display buttons in your application. ovals. such as lines. The user can select multiple options at a time. labels and text boxes used in a GUI application. The Canvas widget is used to draw shapes. such as buttons. 333 . These controls are commonly called widgets. The Entry widget is used to display a single-line text field for Entry accepting values from a user. in your application. The Checkbutton widget is used to display a number of options as Checkbutton checkboxes. The Menubutton widget is used to display menus in your Menubutton application. The Radiobutton widget is used to display a number of options as Radiobutton radio buttons. The Scrollbar widget is used to add scrolling capability to various Scrollbar widgets. Text The Text widget is used to display text in multiple lines. Python The Frame widget is used as a container widget to organize other Frame widgets. such as list boxes. Toplevel The Toplevel widget is used to provide a separate window container. The Spinbox widget is a variant of the standard Tkinter Entry Spinbox widget. arranged horizontally or vertically. which can be used to select from a fixed number of values. The Label widget is used to provide a single-line caption for other Label widgets. A PanedWindow is a container widget that may contain any number PanedWindow of panes. Scale The Scale widget is used to provide a slider widget. The Menu widget is used to provide various commands to a user. Listbox The Listbox widget is used to provide a list of options to a user. 334 . The Message widget is used to display multiline text fields for Message accepting values from a user. The user can select only one option at a time. Menu These commands are contained inside Menubutton. It can also contain images. . These options can be used as key-value pairs separated by commas. fg Normal foreground (text) color. Button The Button widget is used to add buttons in a Python application. bd Border width in pixels.. 335 . bg Normal background color. These buttons can display text or images that convey the purpose of the buttons. . tkMessageBox This module is used to display message boxes in your applications. ) Parameters  master: This represents the parent window. option=value. Its primary purpose is to LabelFrame act as a spacer or container for complex window layouts. command Function or method to be called when the button is clicked.  options: Here is the list of most commonly used options for this widget. Syntax Here is the simple syntax to create this widget: w = Button ( master. You can attach a function or a method to a button which is called automatically when you click the button. Python A labelframe is a simple container widget. Default is 2. Option Description activebackground Background color when the button is under the cursor. activeforeground Foreground color when the button is under the cursor. meaning that no character of the text on the underline button will be underlined. 336 . Relief specifies the type of the border. Default is -1. the corresponding text character will be underlined. pady Additional padding above and below the text. Python font Text font to be used for the button's label. If this value is set to a positive number. Has the value ACTIVE when the mouse is over it. highlightcolor The color of the focus highlight when the widget has focus. the text lines will be wraplength wrapped to fit within this length. Default is NORMAL. Some of the values are relief SUNKEN. or RIGHT to right-justify. How to show multiple text lines: LEFT to left-justify each line. justify CENTER to center them. RAISED. image Image to be displayed on the button (instead of text). Height of the button in text lines (for textual buttons) or pixels height (for images). padx Additional padding left and right of the text. and RIDGE. Set this option to DISABLED to gray out the button and make state it unresponsive. If nonnegative. GROOVE. Width of the button in letters (if displaying text) or pixels (if width displaying an image). Ignored if the button is disabled. "Hello World") B = Tkinter. Python Methods Following are commonly used methods for this widget: Medthod Description Causes the button to flash several times between active and flash() normal colors. and returns what that function returns. Example Try the following example yourself: import Tkinter import tkMessageBox top = Tkinter.Button(top. Calls the button's callback. Leaves the button in the state it was in originally.Tk() def helloCallBack(): tkMessageBox.mainloop() When the above code is executed. invoke() Has no effect if the button is disabled or there is no callback.pack() top. text ="Hello". it produces the following result: 337 .showinfo( "Hello Python". command = helloCallBack) B. 338 . e the right side. or frames on a Canvas. RAISED. height Size of the canvas in the Y dimension. Python Canvas The Canvas is a rectangular area intended for drawing pictures or other complex layouts. cursor Cursor used in the canvas like arrow. bg Normal background color. width Size of the canvas in the X dimension. the canvas cannot be scrolled outside of confine the scrollregion. ) Parameters  master: This represents the parent window.. dot etc. circle. where w is the left side. Syntax Here is the simple syntax to create this widget: w = Canvas ( master. highlightcolor Color shown in the focus highlight.  options: Here is the list of most commonly used options for this widget.. and RIDGE. GROOVE. You can place graphics. e. Default is 2. A tuple (w. option=value. text. If true (the default). s) that defines over how large an area the scrollregion canvas can be scrolled. Some of the values are relief SUNKEN. These options can be used as key-value pairs separated by commas. n. and s the bottom. n the top. Option Description bd Border width in pixels. widgets2. Relief specifies the type of the border. . line = canvas. x1. options) oval . which can be an instance of either the BitmapImage or the PhotoImage classes. and the xscrollincrement value will be used for scrolling by scrolling units. yn. this attribute should be the . options) 339 .create_image(50. anchor=NE. y0. x1. x1. y1. yscrollincrement Works like xscrollincrement. Creates a polygon item that must have at least three vertices.create_polygon(x0. the top left and bottom right corners of the bounding rectangle for the oval.set() yscrollcommand method of the vertical scrollbar.create_arc(coord. coord = 10. It takes two pairs of coordinates.. If the canvas is scrollable.. The Canvas widget can support the following standard items: arc .gif") image = canvas. yn. options) polygon . If the canvas is scrollable. image=filename) line . xn..create_oval(x0.create_line(x0.. start=0. 240. Creates a circle or an ellipse at the given coordinates. a pieslice or a simple arc. 50.xn. oval = canvas. y0. oval = canvas. Creates a line item. but governs vertical movement. Python If you set this option to some positive dimension.. Creates an arc item. filename = PhotoImage(file = "sunshine. the canvas can be positioned only on multiples of that distance. Creates an image item. 210 arc = canvas. y1. 50. fill="blue") image . this attribute should be the . extent=150. such as when the user clicks on the arrows at the ends of a scrollbar.set() xscrollcommand method of the horizontal scrollbar. y1. which can be a chord. .. y0. mainloop() When the above code is executed. You can also display images in place of text. fill="red") C. width=300) coord = 10. 210 arc = C.Canvas(top. 340 . height=250. The user can then select one or more options by clicking the button corresponding to each option.create_arc(coord. start=0.pack() top. 50. bg="blue". Python Example Try the following example yourself: import Tkinter import tkMessageBox top = Tkinter. 240.Tk() C = Tkinter. extent=150. it produces the following result: Checkbutton The Checkbutton widget is used to display a number of options to a user as toggle buttons. bd The size of the border around the indicator. activeforeground Foreground color when the checkbutton is under the cursor. the cursor mouse cursor will change to that pattern when it is over the checkbutton. dot etc. Python Syntax Here is the simple syntax to create this widget: w = Checkbutton ( master. fg The color used to render the text.. font The font used for the text.  options: Here is the list of most commonly used options for this widget. If you set this option to a cursor name (arrow.. The foreground color used to render the text of a disabled disabledforeground checkbutton. option. ) Parameters  master: This represents the parent window. A procedure to be called every time the user changes the command state of this checkbutton. The default is a stippled version of the default foreground color. bitmap To display a monochrome image on a button. These options can be used as key-value pairs separated by commas. Default is 2 pixels. The normal background color displayed behind the label and bg indicator. 341 . Option Description activebackground Background color when the checkbutton is under the cursor. .). The color of the focus highlight when the checkbutton has the highlightcolor focus. a checkbutton's associated control variable will be offvalue set to 0 when it is cleared (off). relief=FLAT. the checkbutton does not relief stand out from its background. If you set this option to an image. With the default value. How much space to leave above and below the checkbutton pady and text. You may set this option to any of the other styles The color of the checkbutton when it is set. LEFT. Default is 1 pixel. a checkbutton's associated control variable will be onvalue set to 1 when it is set (on). or RIGHT. You can supply an alternate value for the off state by setting offvalue to that value. Default is 1 pixel. this option controls how the justify text is justified: CENTER. Default is 1. image To display a graphic image on the button. How much space to leave to the left and right of the padx checkbutton and text. Normally. You can supply an alternate value for the on state by setting onvalue to that value. but you can use state=DISABLED to gray out the control and make it state unresponsive. The default is state=NORMAL. 342 . If the cursor is currently over the checkbutton. that image will appear in selectimage the checkbutton when it is set. the state is ACTIVE. Normally. Default is selectcolor selectcolor="red". If the text contains multiple lines. Python height The number of lines of text on the checkbutton. Python The label displayed next to the checkbutton. lines are not wrapped. toggle() Clears the checkbutton if set. The control variable that tracks the current state of the checkbutton. 343 . sets it if cleared. Normally. but leaves it the way it started. Methods Following are commonly used methods for this widget: Medthod Description deselect() Clears (turns off) the checkbutton. You can set this option to a wraplength number of characters and all lines will be broken into pieces no longer than that number. and 0 means variable cleared and 1 means set. none of the characters of the text label are underlined. but see the offvalue and onvalue options above. The default width of a checkbutton is determined by the size of the displayed image or text. Flashes the checkbutton a few times between its active and normal flash() colors. Use newlines text ("\n") to display multiple lines of text. Set this option to the index of a underline character in the text (counting from zero) to underline that character. select() Sets (turns on) the checkbutton. You can set this option to a width number of characters and the checkbutton will always have room for that many characters. Normally this variable is an IntVar. With the default value of -1. You can call this method to get the same actions that would occur invoke() if the user clicked on the checkbutton to change its state. Python Example Try the following example yourself: from Tkinter import * import tkMessageBox import Tkinter top = Tkinter. \ width = 20) C1. \ onvalue = 1. variable = CheckVar1.pack() C2. height=5. text = "Music".Tk() CheckVar1 = IntVar() CheckVar2 = IntVar() C1 = Checkbutton(top. variable = CheckVar2. text = "Video". it produces the following result: Entry The Entry widget is used to accept single-line text strings from a user. \ onvalue = 1.mainloop() When the above code is executed.pack() top. \ width = 20) C2 = Checkbutton(top. offvalue = 0. height=5. 344 . offvalue = 0. . A procedure to be called every time the user changes the state command of this checkbutton. use exportselection=0. Option Description The normal background color displayed behind the label and bg indicator. dot etc. These options can be used as key-value pairs separated by commas. ) Parameters  master: This represents the parent window. To avoid this exportation.). bd The size of the border around the indicator.  options: Here is the list of most commonly used options for this widget.  If you want to display one or more lines of text that cannot be modified by the user. By default. Syntax Here is the simple syntax to create this widget: w = Entry( master. the cursor mouse cursor will change to that pattern when it is over the checkbutton. then you should use the Label widget. fg The color used to render the text. then you should use the Text widget. Python  If you want to display multiple lines of text that can be edited. . font The font used for the text.. it is exportselection automatically exported to the clipboard. option. if you select text within an Entry widget. If you set this option to a cursor name (arrow. Default is 2 pixels. 345 . set show="*". The selectborderwidth default is one pixel. you must set this option to an instance of the StringVar class. If the text contains multiple lines. the state is ACTIVE. the checkbutton does not relief stand out from its background. You may set this option to any of the other styles selectbackground The background color to use displaying selected text. To make a . Methods 346 . You can set this option to a width number of characters and the checkbutton will always have room for that many characters.password. With the default value. If the cursor is currently over the checkbutton. Python The color of the focus highlight when the checkbutton has the highlightcolor focus. selectforeground The foreground (text) color of selected text. The default is state=NORMAL. this option controls how the justify text is justified: CENTER. Normally. In order to be able to retrieve the current text from your entry textvariable widget. If you expect that users will often enter more text than the xscrollcommand onscreen size of the widget. the characters that the user types appear in the show entry. but you can use state=DISABLED to gray out the control and make it state unresponsive. LEFT. The width of the border to use around selected text. relief=FLAT. The default width of a checkbutton is determined by the size of the displayed image or text. you can link your entry widget to a scrollbar. or RIGHT. entry that echoes each character as an asterisk. s ) index. If the second argument is omitted. Shift the contents of the entry so that the character at the given index is the leftmost visible index ( index ) character. has no effect. Sets the ANCHOR index position to the character select_from ( index ) selected by index. starting with the one at index first. up to but not including the delete ( first. Python Following are commonly used methods for this widget: Medthod Description Deletes characters from the widget. end ) Sets the selection under program control. Inserts string s before the character at the given insert ( index. This method is used to make sure that the select_adjust ( index ) selection includes the character at the specified index. only the single character at position first is deleted. returns true. If there isn't currently a select_clear() selection. Has no effect if the text fits entirely within the entry. Set the insertion cursor just before the character icursor ( index ) at the given index. Clears the selection. If there is a selection. up to but not 347 . and selects that character. select_range ( start. get() Returns the entry's current text as a string. last=None ) character at position last. Selects the text starting at the start index. else returns select_present() false. or PAGES. Used to scroll the entry horizontally. what ) the size of the entry widget. The number is positive to scroll left to right.pack( side = LEFT) E1 = Entry(top.pack(side = RIGHT) top. bd =5) E1. text="User Name") L1.mainloop() When the above code is executed. to scroll by character widths. to scroll by chunks xview_scroll ( number. negative to scroll right to left. Example Try the following example yourself: from Tkinter import * top = Tk() L1 = Label(top. Selects all the text from the ANCHOR position up select_to ( index ) to but not including the character at the given index. it produces the following result: 348 . Python including the character at the end index. The start position must be before the end position. The what argument must be either UNITS. This method is useful in linking the Entry widget xview ( index ) to a horizontal scrollbar. dot etc. option. Python Frame The Frame widget is very important for the process of grouping and organizing other widgets in a somehow friendly way. height The vertical dimension of the new frame. 349 . the cursor mouse cursor will change to that pattern when it is over the checkbutton. ) Parameters:  master: This represents the parent window.). A frame can also be used as a foundation class to implement complex widgets. which is responsible for arranging the position of other widgets.. Syntax Here is the simple syntax to create this widget: w = Frame ( master.  options: Here is the list of most commonly used options for this widget. It works like a container. Option Description The normal background color displayed behind the label and bg indicator. It uses rectangular areas in the screen to organize the layout and to provide padding of these widgets. These options can be used as key-value pairs separated by commas. Default is 2 bd pixels.. . The size of the border around the indicator. If you set this option to a cursor name (arrow. highlightthickness Thickness of the focus highlight. You may set this option to any of the other styles The default width of a checkbutton is determined by the size of the displayed image or text. Example Try the following example yourself: from Tkinter import * root = Tk() frame = Frame(root) frame. Python Color of the focus highlight when the frame does not have highlightbackground focus. fg="red") redbutton. You can set this option to a width number of characters and the checkbutton will always have room for that many characters. the checkbutton does relief not stand out from its background. text="Blue". fg="blue") bluebutton.pack( side = LEFT) greenbutton = Button(frame. Color shown in the focus highlight when the frame has the highlightcolor focus. With the default value. text="Brown".pack( side = BOTTOM ) redbutton = Button(frame.pack( side = LEFT ) bluebutton = Button(frame.pack( side = LEFT ) 350 . fg="brown") greenbutton.pack() bottomframe = Frame(root) bottomframe. relief=FLAT. text="Red". . which centers the text in the available space. 351 . ) Parameters  master: This represents the parent window. it produces the following result:: Label This widget implements a display box where you can place text or images. Option Description This options controls where the text is positioned if the widget has anchor more space than the text needs.  options: Here is the list of most commonly used options for this widget. It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines. Python blackbutton = Button(bottomframe. Syntax Here is the simple syntax to create this widget: w = Label ( master. . text="Black".. option. The text displayed by this widget can be updated at any time you want. fg="black") blackbutton.pack( side = BOTTOM) root. The default is anchor=CENTER.mainloop() When the above code is executed. These options can be used as key-value pairs separated by commas. height The vertical dimension of the new frame. or RIGHT for right-justified. Default is 2 pixels. set this option to an image image object. relief The default is FLAT. If you are displaying text in this label (with the text or textvariable font option. this option specifies the color of the text. for other values. Default is 1. dot etc. If you are displaying a bitmap. bd The size of the border around the indicator. Specifies the appearance of a decorative border around the label. Extra space added above and below the text within the widget. Python The normal background color displayed behind the label and bg indicator. 352 . the font option specifies in what font that text will be displayed. If you set this option to a cursor name (arrow. If you are displaying text or a bitmap in this label.). pady Default is 1. Specifies how multiple lines of text will be aligned with respect to justify each other: LEFT for flush left. Extra space added to the left and right of the text within the padx widget. CENTER for centered (the default). Set this option equal to a bitmap or image object and the label will bitmap display that graphic. To display a static image in the label widget. this fg is the color that will appear at the position of the 1-bits in the bitmap. the mouse cursor cursor will change to that pattern when it is over the checkbutton. You can display an underline (_) below the nth letter of the text. relief=RAISED ) var. the label will be sized to fit its contents. Internal newlines ("\n") will force a line break. Example Try the following example yourself: from Tkinter import * root = Tk() var = StringVar() label = Label( root. Python To display one or more lines of text in a label widget. If this option is not width set. To slave the text displayed in a label widget to a control variable textvariable of class StringVar.set("Hey!? How are you doing?") label.mainloop() When the above code is executed. The default is underline=-1. underline counting from 0. it produces the following result: 353 . by setting this option to n. The default value. set this option to that variable. textvariable=var. You can limit the number of characters in each line by setting this wraplength option to the desired number. set this option text to a string containing the text. Width of the label in characters (not pixels!). 0. means that lines will be broken only at newlines.pack() root. which means no underlining. . Color shown in the focus highlight when the widget has the highlightcolor focus. Python Listbox The Listbox widget is used to display a list of items from which a user can select a number of items Syntax Here is the simple syntax to create this widget: w = Listbox ( master. font The font used for the text in the listbox. Default is height 10. ) Parameters  master: This represents the parent window. fg The color used for the text in the listbox. . Default is 2 pixels. 354 . Number of lines (not pixels!) shown in the listbox. option. The default relief is SUNKEN. highlightthickness Thickness of the focus highlight.  options: Here is the list of most commonly used options for this widget.. Option Description The normal background color displayed behind the label and bg indicator. These options can be used as key-value pairs separated by commas. Selects three-dimensional border shading effects. bd The size of the border around the indicator. cursor The cursor that appears when the mouse is over the listbox. This is the default. 355 . you can only select one line out of a listbox. If you want to allow the user to scroll the listbox horizontally. Python selectbackground The background color to use displaying selected text. If you want to allow the user to scroll the listbox vertically. counting from 0. EXTENDED: You can select any adjacent group of lines at once by clicking on the first line and dragging to the last line.wherever you click button 1. If nothing is selected. Methods Methods on listbox objects include: Option Description activate ( index ) Selects the line specifies by the given index. Returns a tuple containing the line numbers of the curselection() selected element or elements. yscrollcommand you can link your listbox widget to a vertical scrollbar. MULTIPLE: You can select any number of lines at once. returns an empty tuple. the selection will follow the mouse. selectmode SINGLE: You can only select one line. Determines how many items can be selected. xscrollcommand you can link your listbox widget to a horizontal scrollbar. that line is selected. and how mouse drags affect the selection: BROWSE: Normally. If you click on an item and then drag to a different line. and you can't drag the mouse. The default is 20. Clicking on any line toggles whether or not it is selected. width The width of the widget in characters. or PAGES to scroll by pages. For the what xview_scroll ( number. Use END as the insert ( index. by 356 . positions the visible part of the listbox index ( i ) so that the line containing index i is at the top of the widget. Adjust the position of the listbox so that the line see ( index ) referred to by index is visible. To make the listbox horizontally scrollable. last]. that is. Insert one or more new lines into the listbox before the line specified by index. If the second argument is omitted. Scroll the listbox so that the leftmost fraction of xview_moveto ( fraction ) the width of its longest line is outside the left side of the listbox. Python Deletes the lines whose indices are in the range delete ( first. use either UNITS to scroll by characters. Fraction is in the range [0. set the xview() command option of the associated horizontal scrollbar to this method. Return the index of the visible line closest to the nearest ( y ) y-coordinate y relative to the listbox widget. size() Returns the number of lines in the listbox. last=None ) [first. what ) argument. If possible. last=None ) argument is omitted. inclusive.1]. returns the text of the line closest to first. If the second get ( first. Returns a tuple containing the text of the lines with indices from first to last. the single line with index first is deleted. Scrolls the listbox horizontally. *elements ) first argument if you want to add new lines to the end of the listbox. Scrolls the listbox vertically.insert(3. "Perl") Lb1. or yview_scroll ( number. "C") Lb1.insert(6.1]. Fraction is in the range [0. "PHP") Lb1. Scroll the listbox so that the top fraction of the yview_moveto ( fraction ) width of its longest line is outside the left side of the listbox. by the height of the listbox. The number argument tells how many to scroll. use either UNITS to scroll by lines. "Ruby") Lb1.pack() top. "Python") Lb1. For the what argument.insert(4. Example Try the following example yourself: from Tkinter import * import tkMessageBox import Tkinter top = Tk() Lb1 = Listbox(top) Lb1. what ) PAGES to scroll by pages.insert(2. The number argument tells how many to scroll. "JSP") Lb1. To make the listbox vertically scrollable.insert(5.insert(1. set the yview() command option of the associated vertical scrollbar to this method.mainloop() 357 . that is. Python the width of the listbox. Option Description The background color when the mouse is over the activebackground menubutton. it produces the following result: MenuButton A menubutton is the part of a drop-down menu that stays on the screen all the time. These options can be used as key-value pairs separated by commas..  options: Here is the list of most commonly used options for this widget. The foreground color when the mouse is over the activeforeground menubutton. 358 . option. ) Parameters  master: This represents the parent window.. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it. . Syntax Here is the simple syntax to create this widget: w = Menubutton ( master. Python When the above code is executed. which centers the text. The size of the border around the indicator. To display a bitmap on the menubutton. The height of the menubutton in lines of text (not pixels!). height The default is to fit the menubutton's size to its contents. The normal background color displayed behind the label and bg indicator. The foreground color when the mouse is not over the fg menubutton. Color shown in the focus highlight when the widget has the highlightcolor focus. Default is 2 bd pixels. image To display an image on this menubutton. Python This options controls where the text is positioned if the widget anchor has more space than the text needs. The cursor that appears when the mouse is over this cursor menubutton. justify This option controls where the text is located when the text doesn't fill the menubutton: use justify=LEFT to left-justify 359 . The foreground color shown on this menubutton when it is disabledforeground disabled. The default is anchor=CENTER. use direction=RIGHT to display the menu to the right direction of the button. set this option to a bitmap bitmap name. Set direction=LEFT to display the menu to the left of the button. or use direction='above' to place the menu above the button. set this option to the index of that character. or justify=RIGHT to right-justify. Setting that control variable will change the displayed text. Normally. How much space to leave to the left and right of the text of padx the menubutton. set this option to the Menu object containing those choices. menubuttons respond to the mouse. Default is 1. The default relief is RAISED. set this option to the text string containing the desired text. To associate the menubutton with a set of choices. Selects three-dimensional border shading effects. 360 . Default is 1. width The width of the widget in characters. Python the text (this is the default). That menu menu object must have been created by passing the associated menubutton to the constructor as its first argument. Set state state=DISABLED to gray out the menubutton and make it unresponsive. no underline appears under the text on the underline menubutton. To underline one of the characters. use justify=CENTER to center it. The default is 20. Newlines ("\n") within the string will cause line breaks. You can associate a control variable of class StringVar with textvariable this menubutton. To display text on the menubutton. Normally. How much space to leave above and below the text of the pady menubutton. Example Try the following example yourself: from Tkinter import * import tkMessageBox import Tkinter top = Tk() mb= Menubutton ( top. relief=RAISED ) mb.menu.menu. lines are not wrapped. text="condiments". Python Normally.pack() top.menu = Menu ( mb.add_checkbutton ( label="mayo". variable=ketchVar ) mb. You can set this option to a wraplength number of characters and all lines will be broken into pieces no longer than that number.menu mayoVar = IntVar() ketchVar = IntVar() mb.add_checkbutton ( label="ketchup". tearoff = 0 ) mb["menu"] = mb. variable=mayoVar ) mb.grid() mb.mainloop() 361 . such as the OptionMenu widget. which implements a special type that generates a pop-up list of items within a selection. It is also possible to use other extended widgets to implement new types of menus. ) Parameters  master: This represents the parent window. Python When the above code is executed. Option Description The background color that will appear on a choice when it is activebackground under the mouse. Specifies the width of a border drawn around a choice when activeborderwidth it is under the mouse.. option. toplevel and pull-down..  options: Here is the list of most commonly used options for this widget. it produces the following result: Menu The goal of this widget is to allow us to create all kinds of menus that can be used by our applications. These options can be used as key-value pairs separated by commas. Syntax Here is the simple syntax to create this widget: w = Menu ( master. Default is 1 pixel. The core functionality provides ways to create three menu types: pop-up. 362 . . fg The foreground color used for choices not under the mouse. disabledforeground The color of the text for items whose state is DISABLED. cursor but only when the menu has been torn off. tearoff and the additional choices are added starting at position 1. the first position (position 0) in the list of choices is occupied by the tear-off element. and choices will be added starting at position 0. Default is 1. Normally. font The default font for textual choices. You can set this option to a procedure. a menu can be torn off. image To display an image on this menubutton. Python The foreground color that will appear on a choice when it is activeforeground under the mouse. Normally. If you want to change the title of that window. relief The default 3-D effect for menus is relief=RAISED. and that procedure postcommand will be called every time someone brings up this menu. If you set tearoff=0. set the title option to that string. the menu will not have a tear-off feature. the title of a tear-off menu window will be the same as the text of the menubutton or cascade that lead to this title menu. Specifies the color displayed in checkbuttons and selectcolor radiobuttons when they are selected. 363 . The cursor that appears when the mouse is over the choices. bg The background color for choices not under the mouse. bd The width of the border around all the choices. "checkbutton". Insert a new separator at the position specified insert_separator ( index ) by index. endindex ]) to endindex. "separator". which is entryconfig( index. "radiobutton". 364 . Allows you to modify a menu item. and change its options. Returns the index number of the given menu index(item) item label. or "tearoff". Deletes the menu items ranging from startindex delete( startindex [. type ( index ) "command". Python Methods These methods are available on Menu objects: Option Description add_command (options) Adds a menu item to the menu. add_radiobutton( options ) Creates a radio button menu item. Returns the type of the choice specified by index: either "cascade". if a radiobutton. If a checkbutton. Calls the command callback associated with the choice at position index. options ) identified by the index. Creates a new hierarchical menu by associating add_cascade(options) a given menu to a parent menu add_separator() Adds a separator line to the menu. options ) Adds a specific type of menu item to the menu. add( type. its invoke ( index ) state is toggled between set and cleared. that choice is set. add_checkbutton( options ) Creates a check button menu item. .add_separator() filemenu.add_cascade(label="File".add_command(label="Save".add_command(label="Paste". command=root.add_command(label="Cut". command=donothing) 365 . command=donothing) menubar. command=donothing) editmenu. menu=editmenu) helpmenu = Menu(menubar. command=donothing) editmenu. command=donothing) filemenu.pack() root = Tk() menubar = Menu(root) filemenu = Menu(menubar.quit) menubar.add_command(label="Save as. command=donothing) editmenu. tearoff=0) editmenu.add_command(label="Help Index".".add_separator() editmenu. command=donothing) filemenu.add_command(label="Close". text="Do nothing button") button.. command=donothing) filemenu. menu=filemenu) editmenu = Menu(menubar.add_command(label="Delete". command=donothing) filemenu.add_command(label="Undo". command=donothing) editmenu.add_command(label="Open". command=donothing) editmenu.add_command(label="Exit". Python Example Try the following example yourself: from Tkinter import * def donothing(): filewin = Toplevel(root) button = Button(filewin.add_cascade(label="Edit". tearoff=0) helpmenu.add_command(label="Copy". command=donothing) filemenu.add_command(label="New". tearoff=0) filemenu.add_command(label="Select All". except that it can also automatically wrap the text.". automatically breaking lines and justifying their contents. 366 . Its functionality is very similar to the one provided by the Label widget. command=donothing) menubar.. These options can be used as key-value pairs separated by commas. menu=helpmenu) root. maintaining a given width or aspect ratio. Python helpmenu. 2. options: Here is the list of most commonly used options for this widget.mainloop() When the above code is executed. option.. it produces the following result: Message This widget provides a multiline and noneditable object that displays texts. Syntax Here is the simple syntax to create this widget: w = Message ( master.. ) Parameters 1.add_command(label="About. .config(menu=menubar) root. master: This represents the parent window..add_cascade(label="Help". If you are displaying text in this label (with the text or textvariable font option.). the mouse cursor cursor will change to that pattern when it is over the checkbutton. To display a static image in the label widget. set this option to an image image object. or RIGHT for right-justified. dot etc. which centers the text in the available space. Set this option equal to a bitmap or image object and the label will bitmap display that graphic. If you are displaying text or a bitmap in this label. the font option specifies in what font that text will be displayed. If you set this option to a cursor name (arrow. this fg is the color that will appear at the position of the 1-bits in the bitmap. bd The size of the border around the indicator. Default is 1. If you are displaying a bitmap. 367 . Default is 2 pixels. Extra space added to the left and right of the text within the padx widget. this option specifies the color of the text. Python Option Description This options controls where the text is positioned if the widget has anchor more space than the text needs. height The vertical dimension of the new frame. CENTER for centered (the default). The default is anchor=CENTER. The normal background color displayed behind the label and bg indicator. Specifies how multiple lines of text will be aligned with respect to justify each other: LEFT for flush left. mainloop() 368 . Width of the label in characters (not pixels!). means that lines will be broken only at newlines. pady Default is 1. You can limit the number of characters in each line by setting this wraplength option to the desired number. relief=RAISED ) var. 0. Internal newlines ("\n") will force a line break. by setting this option to n. To display one or more lines of text in a label widget. textvariable=var. If this option is not width set. set this option to that variable. set this option text to a string containing the text. for other values. underline counting from 0. which means no underlining. Python Extra space added above and below the text within the widget. The default value. Example Try the following example yourself: from Tkinter import * root = Tk() var = StringVar() label = Message( root. the label will be sized to fit its contents. relief The default is FLAT. You can display an underline (_) below the nth letter of the text. To slave the text displayed in a label widget to a control variable textvariable of class StringVar.pack() root. Specifies the appearance of a decorative border around the label.set("Hey!? How are you doing?") label. The default is underline=-1. Option Description The background color when the mouse is over the activebackground radiobutton. The foreground color when the mouse is over the activeforeground radiobutton. bg The normal background color behind the indicator and label. it produces the following result: Radiobutton This widget implements a multiple-choice button. Python When the above code is executed. this anchor option specifies where the radiobutton will sit in that space. which is a way to offer many possible selections to the user and lets user choose only one of them. option. . ) Parameters  master: This represents the parent window. You can use the Tab key to switch from one radionbutton to another. In order to implement this functionality.. each group of radiobuttons must be associated to the same variable and each one of the buttons must symbolize a single value. The default is anchor=CENTER. 369 . These options can be used as key-value pairs separated by commas.  options: Here is the list of most commonly used options for this widget. If the widget inhabits a space larger than it needs.. Syntax Here is the simple syntax to create this widget: w = Radiobutton ( master. To display a graphic image instead of text for this image radiobutton. If you set this option to a cursor name (arrow. the cursor mouse cursor will change to that pattern when it is over the radiobutton. The number of lines (not pixels) of text on the radiobutton. dot etc. borderwidth Default is 2 pixels. Default is 1. How much space to leave to the left and right of the padx radiobutton and text. height Default is 1. How much space to leave above and below the radiobutton pady and text.). or RIGHT. The color of the focus highlight when the radiobutton has highlightcolor the focus. If the text contains multiple lines. Default is 1. 370 . fg The color used to render the text. this option controls how justify the text is justified: CENTER (the default). The color of the focus highlight when the radiobutton does highlightbackground not have focus. font The font used for the text. set this bitmap option to a bitmap. The size of the border around the indicator part itself. Python To display a monochrome image on a radiobutton. LEFT. set this option to an image object. A procedure to be called every time the user changes the command state of this radiobutton. If this option width is not set. You can display an underline (_) below the nth letter of the underline text. by setting this option to n. If you are using the image option to display a graphic instead of text when the radiobutton is cleared. Default is red. If the control variable is a StringVar. Python Specifies the appearance of a decorative border around the relief label. but you can set state=DISABLED to gray out the control and make it state unresponsive. Use newlines text ("\n") to display multiple lines of text. its control variable is set to its current value option. The control variable that this radiobutton shares with the variable other radiobuttons in the group. The default is state=NORMAL. Width of the label in characters (not pixels!). which means no underlining. give each radiobutton a different string value option. To slave the text displayed in a label widget to a control textvariable variable of class StringVar. you can set selectimage the selectimage option to a different image that will be displayed when the radiobutton is set. The default is underline=-1. selectcolor The color of the radiobutton when it is set. This can be either an IntVar or a StringVar. for other values. counting from 0. The label displayed next to the radiobutton. the label will be sized to fit its contents. set this option to that variable. When a radiobutton is turned on by the user. If the control variable is an IntVar. The default is FLAT. If the cursor is currently over the radiobutton. the state is ACTIVE. give each radiobutton in the group a value different integer value option. 371 . get()) label. Flashes the radiobutton a few times between its active and normal flash() colors. variable=var. Methods Methods Description deselect() Clears (turns off) the radiobutton. select() Sets (turns on) the radiobutton. means that lines will be broken only at newlines.pack( anchor = W ) R2 = Radiobutton(root. value=1. value=2.config(text = selection) root = Tk() var = IntVar() R1 = Radiobutton(root. text="Option 1". Example: Try the following example yourself: from Tkinter import * def sel(): selection = "You selected the option " + str(var. text="Option 2". 0. variable=var. You can call this method to get the same actions that would occur invoke() if the user clicked on the radiobutton to change its state. but leaves it the way it started. command=sel) R2. The default value. Python You can limit the number of characters in each line by wraplength setting this option to the desired number.pack( anchor = W ) 372 . command=sel) R1. 373 . command=sel) R3. Syntax Here is the simple syntax to create this widget: w = Scale ( master.mainloop() When the above code is executed. . text="Option 3".pack() root. value=3. ) Parameters  master: This represents the parent window. option.. it produces the following result: Scale The Scale widget provides a graphical slider object that allows you to select values from a specific scale.pack( anchor = W) label = Label(root) label..  options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. variable=var. Python R3 = Radiobutton(root. Option Description activebackground The background color when the mouse is over the scale. A procedure to be called every time the slider is moved. If you set this option to a cursor name (arrow. or the top right corner if vertical. you may not get a callback for every possible position. This procedure will be passed one argument. The way your program reads the current value shown in a scale widget is through a control variable. 374 . You can display a label within the scale widget by setting this option to the label's text. The label appears in the top label left corner if the scale is horizontal. font The font used for the label and annotations. a DoubleVar (float). The color of the focus highlight when the scale does not have highlightbackground focus. bd Default is 2 pixels. Width of the 3-d border around the trough and slider. the cursor mouse cursor will change to that pattern when it is over the scale.). If the slider is moved rapidly. A float or integer value that defines one end of the scale's from_ range. or digits a StringVar. Python The background color of the parts of the widget that are bg outside the trough. The control variable for a scale can be an IntVar. fg The color of the text used for the label and annotations. the digits option controls how many digits to use when the numeric scale value is converted to a string. If it is a string variable. The default is no label. the new scale command value. but you'll certainly get a callback when it settles. dot etc. highlightcolor The color of the focus highlight when the scale has the focus. the focus will cycle through scale widgets.0. -0. the scale will have 5 possible values: -1. Default is horizontal. For 375 .0. This option controls how long button 1 has to be held down in the trough before the slider starts moving in that direction repeatdelay repeatedly.0. Normally the slider is 30 pixels along the length of the scale. Set this option to some other value to change the smallest increment of the scale's value.5.0. Set this option to 0 to suppress that label. the user will only be able to change the scale in whole units. Specifies the appearance of a decorative border around the relief label. and +1. The default is 100 pixels.5. or the y dimension if vertical.0 and to=1. sliderlength You can change that length by setting the sliderlength option to your desired length. and the units are milliseconds. +0. if resolution from_=-1. also keyboard events. set this option to a number. This is the x dimension if the length scale is horizontal. for other values. Normally. and ticks will be displayed on multiples of that value. 0. For example. tickinterval To display periodic scale values. Set orient=HORIZONTAL if you want the scale to run along orient the x dimension. and you set resolution=0. and when state they have the focus. Normally. Set this takefocus option to 0 if you don't want this behavior.5. Default is repeatdelay=300. Normally. Normally. scale widgets respond to mouse events. or orient=VERTICAL to run parallel to the y-axis. Set state=DISABLED to make the widget unresponsive. the current value of the scale is displayed in text form by the slider (above it for horizontal scales. Python The length of the scale widget. to the left showvalue for vertical scales). The default is FLAT. Default is 15 pixels. For vertical scales.0. the right end. to=1. the to value defines the bottom of the scale.25. discussed above. The width of the trough part of the widget. 376 . the other end is defined by the from_ option. Default is 0. Python example. set ( value ) Sets the scale's value. The to value can be either greater than or to less than the from_ value. for horizontal scales. the numerical value will be converted to a string. This is the x width dimension for vertical scales and the y dimension if the scale has orient=HORIZONTAL. 0. A float or integer value that defines one end of the scale's range.75. if any. to its left if vertical.0. Control variables may be from class IntVar. The control variable for this scale. DoubleVar (float). troughcolor The color of the trough. which suppresses display of ticks. 0. or StringVar. variable In the latter case. labels will be displayed along the scale at values 0. if from_=0. and 1. These labels appear below the scale if horizontal.0. Methods Scale objects have these methods: Methods Description get() This method returns the current value of the scale.50. and tickinterval=0.25. 0.00. pack() root. it produces the following result: 377 .get()) label.mainloop() When the above code is executed.pack(anchor=CENTER) label = Label(root) label. command=sel) button.config(text = selection) root = Tk() var = DoubleVar() scale = Scale( root.pack(anchor=CENTER) button = Button(root. Python Example Try the following example yourself: from Tkinter import * def sel(): selection = "Value = " + str(var. text="Get Scale Value". variable = var ) scale. option. These options can be used as key-value pairs separated by commas. such as Listbox. The color of the slider and arrowheads when the mouse is bg not over them. elementborderwidth The default is elementborderwidth=-1. and also the width of the 3-d effects on the bd arrowheads and slider.. Option Description The color of the slider and arrowheads when the mouse is activebackground over them. The width of the borders around the arrowheads and slider. command A procedure to be called whenever the scrollbar is moved. and a 2-pixel border around the arrowheads and slider. which means to use the value of the borderwidth option. ) Parameters  master: This represents the parent window. Syntax: Here is the simple syntax to create this widget: w = Scrollbar ( master.  options: Here is the list of most commonly used options for this widget. Default is no border around the trough. Text and Canvas. Note that you can also create horizontal scrollbars on Entry widgets. Python Scrollbar This widget provides a slide controller that is used to implement vertical scrolled widgets. 378 . The cursor that appears when the mouse is over the cursor scrollbar. .. The width of the 3-d borders around the entire perimeter of the trough. troughcolor The color of the trough. This option controls how long button 1 has to be held down in the trough before the slider starts moving in that direction repeatdelay repeatedly. The color of the focus highlight when the scrollbar has the highlightcolor focus. If you set this option to 1. Python The color of the focus highlight when the scrollbar does not highlightbackground have focus. Set orient=HORIZONTAL for a horizontal scrollbar. repeatinterval repeatinterval Normally. the callback isn't called until the user releases the mouse button. Width of the scrollbar (its y dimension if horizontal. Set to 0 to highlightthickness suppress display of the focus highlight. and its width x dimension if vertical). you can tab the focus through a scrollbar widget. takefocus Set takefocus=0 if you don't want this behavior. every small drag of the slider jump causes the command callback to be called. and the units are milliseconds. Default is 1. The thickness of the focus highlight. Default is repeatdelay=300. Normally (jump=0). orient orient=VERTICAL for a vertical one. Default is 16. This option controls what happens when a user drags the slider. 379 . pack( side = LEFT. Python Methods Scrollbar objects have these methods: Methods Description Returns two numbers (a.yview ) mainloop() 380 . fill=Y ) mylist = Listbox(root.pack( side = RIGHT.set ) for line in range(100): mylist. yscrollcommand = scrollbar.config( command = mylist. To connect a scrollbar to another widget w. b) describing the current position of the slider. set w's xscrollcommand or yscrollcommand to the scrollbar's set() set ( first. The a value gives the position of the left or top edge of get() the slider.insert(END. The arguments have the same meaning as the values returned by the get() method. Example Try the following example yourself: from Tkinter import * root = Tk() scrollbar = Scrollbar(root) scrollbar. the b value gives the position of the right or bottom edge. for horizontal and vertical scrollbars respectively. fill = BOTH ) scrollbar. last ) method. "This is line number " + str(line)) mylist. and apply changes to those areas. you can embed windows and images in the text because this widget was designed to handle both plain and formatted text.. it produces the following result: Text Text widgets provide advanced capabilities that allow you to edit a multiline text and format the way it has to be displayed. option. such as changing its color and font. Python When the above code is executed. You can also use elegant structures like tabs and marks to locate specific sections of the text. Moreover. ) Parameters  master: This represents the parent window.. Option Description bg The default background color of the text widget. These options can be used as key-value pairs separated by commas.  options: Here is the list of most commonly used options for this widget. Syntax Here is the simple syntax to create this widget: w = Text ( master. 381 . . Default is 300. Default is 2 bd pixels. font The default font for text inserted into the widget. Set exportselection=0 if you don't want that behavior. Default is 1. Default insertborderwidth is 0. measured height according to the current font size. this option is just the default. The number of milliseconds the insertion cursor is off during insertofftime its blink cycle. The color of the focus highlight when the text widget does highlightbackground not have focus. The color used for text (and bitmaps) within the widget. 382 . Python The width of the border around the text widget. Set this option to zero to suppress blinking. Size of the 3-D border around the insertion cursor. Set highlightthickness highlightthickness=0 to suppress display of the focus highlight. Default is black. You fg can change the color for tagged regions. The cursor that will appear when the mouse is over the text cursor widget. insertbackground The color of the insertion cursor. The height of the widget in lines (not pixels!). The thickness of the focus highlight. Normally. text selected within a text widget is exported to exportselection be the selection in the window manager. The color of the focus highlight when the text widget has the highlightcolor focus. If you set state state=DISABLED. Default is one pixel. The size of the internal padding added above and below the pady text area. Default is 600. This option specifies how much extra vertical space is added below each line of text. This option specifies how much extra vertical space to add spacing2 between displayed lines of text when a logical line wraps. text widgets respond to keyboard and mouse events. The 3-D appearance of the text widget. Default is 0. Default is 0. Default is relief relief=SUNKEN. selectbackground The background color to use displaying selected text. Width of the insertion cursor (its height is determined by the insertwidth tallest item in its line). Python The number of milliseconds the insertion cursor is on during insertontime its blink cycle. If a line wraps. the text widget will not respond. This option specifies how much extra vertical space is put above each line of text. Default is one pixel. Normally. 383 . selectborderwidth The width of the border to use around selected text. The size of the internal padding added to the left and right padx of the text area. Default is 0. and you won't be able to modify its contents programmatically either. Default is 2 pixels. If a line wraps. set state=NORMAL to get this behavior. this space is added spacing1 only before the first line it occupies on the display. this space is added spacing3 only after the last line it occupies on the display. With the default behavior.) This method inserts strings at the specified index location. The width of the widget in characters (not pixels!)..string].endindex]) This method returns a specific character or a range of text. get(startindex [. set this xscrollcommand option to the set() method of the horizontal scrollbar. index(index) Returns the absolute value of an index based on the given index. see(index) This method returns true if the text located at the index position is visible. To make the text widget vertically scrollable. Set wrap=WORD and it will break the line after the last word wrap that will fit. any line that gets too long will be broken at any character. To make the text widget horizontally scrollable. Python tabs This option controls how tab characters position text.. set this option yscrollcommand to the set() method of the vertical scrollbar. width measured according to the current font size.endindex]) This method deletes a specific character or a range of text. insert(index [. This option controls the display of lines that are too wide. 384 . Methods Text objects have these methods: Methods & Description delete(startindex [. wrap=CHAR. .endindex] . Tabs.. Python Text widgets support three distinct helper structures: Marks. tabs(this property has the same functionality of the Text widget tabs's property). tag_config You can use this method to configure the tag properties. mark_set(mark. or a range delimited by the positions startindex and endindex. left. Tags are also used to bind event callbacks to specific ranges of text. startindex[. Tags are used to associate names to regions of text which makes easy the task of modifying the display settings of specific text areas. Following are the available methods for handling tabs: Methods and Description tag_add(tagname. If the second argument is provided. mark_gravity(mark [.gravity]) Returns the gravity of the given mark. or right). and underline(used to underline the tagged text). which include. 385 . index) Informs a new position to the given mark. and Indexes: Marks are used to bookmark positions between two characters within a given text. We have the following methods available when handling marks: Methods & Description index(mark) Returns the line and column location of a specific mark. mark_names() Returns all marks from the Text widget. the gravity is set for the given mark. mark_unset(mark) Removes the given mark from the Text widget.) This method tags either the position defined by startindex. justify(center. insert(INSERT.startindex[. "1.endindex]] ..tag_config("here". it produces the following result: 386 . background="black". foreground="blue") text.4") text.insert(END. "Hello. "Bye Bye..pack() text. "1.tag_add("here".tag_add("start".") text.tag_config("start". the given tag is removed from the provided area without deleting the actual tag definition..) After applying this method. "1.8". foreground="green") root... "1. tag_remove(tagname [... Example Try the following example yourself: from Tkinter import * def onclick(): pass root = Tk() text = Text(root) text.13") text... Python tag_delete(tagname) This method is used to delete and remove a given tag..mainloop() When the above code is executed.") text.0". background="yellow". Syntax Here is the simple syntax to create this widget: w = Toplevel ( option. and set the relief option to one of the constants. relief To get a shaded border. cursor The cursor that appears when the mouse is in this window. ) Parameters:  options: Here is the list of most commonly used options for this widget. The color used for text (and bitmaps) within the widget. These options can be used as key-value pairs separated by commas. a top-level window will have no 3-d borders around it. . They do not necessarily have a parent widget on top of them. 387 . set the bd option larger that its default value of zero. You can fg change the color for tagged regions... height Window height. Option Description bg The background color of the window. Python TopLevel Toplevel widgets work as windows that are directly managed by the window manager. font The default font for text inserted into the widget. default is 0. Set exportselection=0 if you don't want that behavior. Normally. this option is just the default. Normally. Your application can use any number of top-level windows. bd Border width in pixels. text selected within a text widget is exported to be the class_ selection in the window manager. iconify() Turns the window into an icon. withdrawn and icon. without destroying it. state() Returns the current state of the window. Methods Toplevel objects have these methods: Methods and Description deiconify() Displays the window. function) Registers a function as a callback which will be called for the given protocol. without destroying it. iconify() Turns the window into an icon. withdraw() 388 . Possible values are normal. protocol(name. transient([master]) Turns the window into a temporary(transient) window for the given master or to the window's parent. Python width The desired width of the window. iconic. after using either the iconify or the withdraw methods. frame() Returns a system-specific window identifier. when no argument is given. group(window) Adds the window to the window group administered by the given window. minsize(width. height) Defines the minimum size for this window. which control whether the window can be resized. resizable(width. Example Try following example yourself: from Tkinter import * root = Tk() top = Toplevel() top. maxsize(width.mainloop() 389 . positionfrom(who) Defines the position controller. sizefrom(who) Defines the size controller. height) Defines the resize flags. height) Defines the maximum size for this window. title(string) Defines the window title. Python Removes the window from the screen. without destroying it. These options can be used as key-value pairs separated by commas.. 390 . Option Description The color of the slider and arrowheads when the mouse is activebackground over them. option. Syntax Here is the simple syntax to create this widget: w = Spinbox( master. . Python When the above code is executed. which can be used to select from a fixed number of values.. The color of the slider and arrowheads when the mouse is bg not over them.  options: Here is the list of most commonly used options for this widget. it produces the following result: SpinBox The Spinbox widget is a variant of the standard Tkinter Entry widget. ) Parameters  master: This represents the parent window. 391 . Together with repeatinterval. Default is no border around the trough. The cursor that appears when the mouse is over the cursor scrollbar. Python The width of the 3-d borders around the entire perimeter of the trough. Default is state NORMAL. this option controls button repeatdelay auto-repeat. fg Text color. and a 2-pixel border around the arrowheads and slider. and also the width of the 3-d effects on the bd arrowheads and slider. No default value. justify Default is LEFT relief Default is SUNKEN. textvariable No default value. disabledbackground The background color to use when the widget is disabled. Both values are given in milliseconds. font The font to use in this widget. Used together with to to limit the from_ spinbox range. command A procedure to be called whenever the scrollbar is moved. The minimum value. disabledforeground The text color to use when the widget is disabled. format Format string. DISABLED. One of NORMAL. or "readonly". repeatinterval See repeatdelay. endindex]) This method deletes a specific character or a range of text. Python to See from. Used to connect a spinbox field to a horizontal scrollbar. This xscrollcommand option should be set to the set method of the corresponding scrollbar. the up and down buttons will wrap around. vcmd Same as validatecommand.endindex]) This method returns a specific character or a range of text. validate Validation mode. wrap If true. identify(x. in character units. No default value. get(startindex [. Methods Spinbox objects have these methods: Methods and Description delete(startindex [. validatecommand Validation callback. A tuple containing valid values for this widget. y) Identifies the widget element at the given location. width Widget width. Default is 20. index(index) Returns the absolute value of an index based on the given index. Overrides values from/to/increment. 392 . Default is NONE. invoke(element) Invokes a spinbox button. Python insert(index [. it produces the following result: PanelWindow A PanedWindow is a container widget that may contain any number of panes. Each pane contains one widget and each pair of panes is separated by a moveable (via mouse movements) sash. to=10) w. Example Try the following example yourself: from Tkinter import * master = Tk() w = Spinbox(master..) This method inserts strings at the specified index location. arranged horizontally or vertically. from_=0. Moving a sash causes the widgets on either side of the sash to be resized.pack() mainloop() When the above code is executed..string]. 393 . 394 . cursor The cursor that appears when the mouse is over the window.  options: Here is the list of most commonly used options for this widget. and also the width of the 3-d effects on the arrowheads bd and slider. ) Parameters  master: This represents the parent window. relief Default is FLAT.. sashrelief Default is RAISED. Python Syntax Here is the simple syntax to create this widget: w = PanedWindow( master. The width of the 3-d borders around the entire perimeter of the trough. orient Default is HORIZONTAL. Option Description The color of the slider and arrowheads when the mouse is not over bg them. handlesize Default is 8. .. height No default value. borderwidth Default is 2. option. handlepad Default is 8. and a 2-pixel border around the arrowheads and slider. These options can be used as key-value pairs separated by commas. Default is no border around the trough. sashcursor No default value. get(startindex [. the method returns a dictionary containing all current option values. Here's how to create a 3-pane widget: from Tkinter import * m1 = PanedWindow() m1. Example Try the following example yourself.pack(fill=BOTH.add(left) m2 = PanedWindow(m1. Python sashwidth Default is 2. If no options are given. orient=VERTICAL) m1. text="left pane") m1.endindex]) This method returns a specific character or a range of text. config(options) Modifies one or more widget options. showhandle No default value width No default value. Methods PanedWindow objects have these methods: Methods and Description add(child. text="top pane") 395 .add(m2) top = Label(m2. options) Adds a child window to the paned window. expand=1) left = Label(m1. . option.  options: Here is the list of most commonly used options for this widget. ) Parameters  master: This represents the parent window. 396 . These options can be used as key-value pairs separated by commas.. Syntax Here is the simple syntax to create this widget: w = LabelFrame( master. text="bottom pane") m2. Its primary purpose is to act as a spacer or container for complex window layouts.add(bottom) mainloop() When the above code is executed. it produces the following result: LabelFrame A labelframe is a simple container widget. This widget has the features of a frame plus the ability to display a label..add(top) bottom = Label(m2. Python m2. Default is 2 bd pixels. labelAnchor Specifies where to place the label. the checkbutton does relief not stand out from its background. Python Option Description The normal background color displayed behind the label and bg indicator. With the default value. Color of the focus highlight when the frame does not have highlightbackground focus. The size of the border around the indicator. dot etc. font The vertical dimension of the new frame. height The vertical dimension of the new frame. relief=FLAT. If you set this option to a cursor name (arrow. width Specifies the desired width for the window. 397 .). the cursor mouse cursor will change to that pattern when it is over the checkbutton. You may set this option to any of the other styles text Specifies a string to be displayed inside the widget. highlightthickness Thickness of the focus highlight. Color shown in the focus highlight when the frame has the highlightcolor focus. and askretryignore. Python Example Try the following example yourself. Syntax Here is the simple syntax to create this widget: tkMessageBox. Some of these functions are showinfo. text="This is a LabelFrame") labelframe.FunctionName(title. showwarning.pack(fill="both". text="Inside the LabelFrame") left. showerror. Here is how to create a labelframe widget: from Tkinter import * root = Tk() labelframe = LabelFrame(root. expand="yes") left = Label(labelframe.pack() root. message [. This module provides a number of functions that you can use to display an appropriate message. it produces the following result: tkMessageBox The tkMessageBox module is used to display message boxes in your applications. askquestion. askyesno. options]) 398 .mainloop() When the above code is executed. askokcancel. such as ABORT.  title: This is the text to be displayed in the title bar of a message box.Tk() def hello(): tkMessageBox.mainloop() 399 . Some of the options that you can use are default and parent. The parent option is used to specify the window on top of which the message box is to be displayed. command = hello) B1. The default option is used to specify the default button.Button(top. RETRY. or IGNORE in the message box.showinfo("Say Hello". Python Parameters  FunctionName: This is the name of the appropriate message box function.  message: This is the text to be displayed as a message. text = "Say Hello". "Hello World") B1 = Tkinter.pack() top. You could use one of the following functions with dialogue box:  showinfo()  showwarning()  showerror ()  askquestion()  askokcancel()  askyesno ()  askretrycancel () Example Try the following example yourself: import Tkinter import tkMessageBox top = Tkinter.  options: options are alternative choices that you may use to tailor a standard message box. and fonts are specified.such as sizes. it produces the following result: Standard Attributes Let us take a look at how some of their common attributes. and other dimensions of widgets can be described in many different units.  You can specify units by setting a dimension to a string containing a number followed by. widths.  Dimensions  Colors  Fonts  Anchors  Relief styles  Bitmaps  Cursors Dimensions Various lengths. it is assumed to be in pixels. colors. Character Description c Centimeters 400 .  If you set a dimension to an integer. Python When the above code is executed. "green". 401 . "#000fff000" is pure green.  height: Desired height of the widget. "black". and "#00ffff" is pure cyan (green plus blue).  width: Desired width of the widget. Python i Inches m Millimeters p Printer's points (about 1/72") Length Options Tkinter expresses a length as an integer number of pixels. must be greater than or equal to 1. and "magenta" will always be available.  You can also use any locally defined standard color name. "blue". "#fff" is white. and so on). "red".  highlightthickness: Width of the highlight rectangle when the widget has focus. Here is the list of common length options:  borderwidth: Width of the border which gives a three-dimensional look to the widget. The colors "white".  underline: Index of the character to underline in the widget's text (0 is the first character. 1 the second one. Colors Tkinter represents colors with strings. There are two general ways to specify colors in Tkinter:  You can use a string specifying the proportion of red. "cyan".  padX padY: Extra space the widget requests from its layout manager beyond the minimum the widget needs to display its contents in the x and y directions. For example.  wraplength: Maximum line length for widgets that perform word wrapping. green and blue in hexadecimal digits. "#000000" is black.  selectborderwidth: Width of the three-dimentional border around selected items of the widget. "yellow". . italic.. underline and overstrike.  selectbackground: Background color for the selected items of the widget. "bold italic") for a 24-point Times bold italic. "24". This can also be represented as fg. Font object Fonts You can create a "font object" by importing the tkFont module and using its Font class constructor: import tkFont font = tkFont. optionally followed by a string containing one or more of the style modifiers bold. ) 402 . followed by a size in points.  ("Times".  foreground: Foreground color for the widget.Font ( option.  activeforeground: Foreground color for the widget when the widget is active. Fonts There may be up to three ways to specify type style.  selectforeground: Foreground color for the selected items of the widget.  disabledforeground: Foreground color for the widget when the widget is disabled. Python Color options The common color options are:  activebackground: Background color for the widget when the widget is active. "16") for a 16-point Helvetica regular.  highlightbackground: Background color of the highlight region when the widget has focus.  background: Background color for the widget. Simple Tuple Fonts As a tuple whose first element is the font family. This can also be represented as bg.  highlightcolor: Foreground color of the highlight region when the widget has focus.. Example  ("Helvetica".  underline: 1 for underlined text. use -n. "roman" for unslanted. Example helv36 = tkFont.  NW  N  NE  W  CENTER  E  SW  S  SE For example. the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*- *" is the author's favorite fixed-width font for onscreen use. To get a font n pixels high. the text will be centered horizontally and vertically around the reference point. "normal" for regular weight. if you use CENTER as a text anchor.size=36.  slant: "italic" for italic. you can use any of the X font names. 0 for normal.Font(family="Helvetica". Here is list of possible constants. Python Here is the list of options:  family: The font family name as a string. Anchors Anchors are used to define where text is positioned relative to a reference point. which can be used for Anchor attribute.weight="bold") X Window Fonts If you are running under the X Window System. 403 . Use the xfontsel program to help you select pleasing fonts.  weight: "bold" for boldface. For example.  overstrike: 1 for overstruck text.  size: The font height as an integer in points. Anchor NW will position the text so that the reference point coincides with the northwest (top left) corner of the box containing the text. 0 for normal. If you create a small widget inside a large frame and use the anchor=SE option. and so on. If you used anchor=N instead.  FLAT  RAISED  SUNKEN  GROOVE  RIDGE 404 . Example The anchor constants are shown in this diagram: Relief styles The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Python Anchor W will center the text vertically around the reference point. Here is a screenshot of a row of buttons exhibiting all the possible relief styles: Here is a list of possible constants which can be used for relief attribute. the widget would be centered along the top edge. with the left edge of the text box passing through that point. the widget will be placed in the bottom right corner of the frame. pack() B3.pack() B5.pack() B4. relief=FLAT ) B2 = Tkinter. text ="RAISED". relief=SUNKEN ) B4 = Tkinter. relief=RIDGE ) B1. text ="SUNKEN".Button(top. text ="RIDGE".Tk() B1 = Tkinter.Button(top.Button(top. text ="GROOVE".pack() B2.Button(top. relief=RAISED ) B3 = Tkinter. text ="FLAT".pack() top. it produces the following result: 405 .Button(top. Python Example from Tkinter import * import Tkinter top = Tkinter. relief=GROOVE ) B5 = Tkinter.mainloop() When the above code is executed. pack() 406 . relief=RAISED.Tk() B1 = Tkinter. relief=RAISED. text ="info".pack() B2. relief=RAISED.pack() B3.Button(top.\ bitmap="error") B2 = Tkinter. relief=RAISED. relief=RAISED.\ bitmap="hourglass") B3 = Tkinter.\ bitmap="question") B5 = Tkinter. There are following type of bitmaps available:  "error"  "gray75"  "gray50"  "gray25"  "gray12"  "hourglass"  "info"  "questhead"  "question"  "warning" Example from Tkinter import * import Tkinter top = Tkinter. text ="error". text ="warning".Button(top. text ="question".Button(top.Button(top.\ bitmap="warning") B1.Button(top.pack() B4. text ="hourglass".\ bitmap="info") B4 = Tkinter. Python Bitmaps This attribute to displays a bitmap. The exact graphic may vary according to your operating system.pack() top. Here is the list of interesting ones:  "arrow"  "circle"  "clock"  "cross"  "dotbox"  "exchange"  "fleur"  "heart"  "heart"  "man"  "mouse"  "pirate" 407 .mainloop() When the above code is executed. it produces the following result: Cursors Python Tkinter supports quite a number of different mouse cursors available. Python B5. relief=RAISED. 408 . Python  "plus"  "shuttle"  "sizing"  "spider"  "spraycan"  "star"  "target"  "tcross"  "trek"  "watch" Example Try the following example by moving cursor on different buttons: from Tkinter import * import Tkinter top = Tkinter.  The pack() Method . text ="circle".Button(top.mainloop() Geometry Management All Tkinter widgets have access to specific geometry management methods.pack() B2. which have the purpose of organizing widgets throughout the parent widget area.pack() top. grid. and place. text ="plus".Tk() B1 = Tkinter.This geometry manager organizes widgets in blocks before placing them in the parent widget.\ cursor="plus") B1. relief=RAISED.Button(top.\ cursor="circle") B2 = Tkinter. Tkinter exposes the following geometry manager classes: pack. pack() bottomframe = Frame(root) bottomframe. or keeps its own minimal dimensions: NONE (default). or BOTH (fill both horizontally and vertically).  The place() Method -This geometry manager organizes widgets by placing them in a specific position in the parent widget. Y (fill only vertically). X (fill only horizontally). BOTTOM. Example Try the following example by moving cursor on different buttons: from Tkinter import * root = Tk() frame = Frame(root) frame.  fill: Determines whether widget fills any extra space allocated to it by the packer. or RIGHT.  side: Determines which side of the parent widget packs against: TOP (default). Python Tkinter pack() Method This geometry manager organizes widgets in blocks before placing them in the parent widget.This geometry manager organizes widgets in a table-like structure in the parent widget. Syntax widget. LEFT. text="Red".pack( pack_options ) Here is the list of possible options:  expand: When set to true. widget expands to fill any space not otherwise used in widget's parent. fg="red") redbutton. Python  The grid() Method .pack( side = LEFT) 409 .pack( side = BOTTOM ) redbutton = Button(frame. default 0 (leftmost column). outside v's borders. default the first row that is still empty.  ipadx.  rowspan : How many rowswidget occupies. NW. By default. horizontally and vertically. NE. and SW.mainloop() When the above code is executed. text="Brown". sticky may be the string concatenation of zero or more of N.  sticky : What to do if the cell is larger than widget.  columnspan: How many columns widgetoccupies. 410 . with sticky=''. SE. E. it produces the following result: Python Tkinter grid() Method Here is the list of possible options:  column : The column to put widget in. fg="blue") bluebutton. text="Blue". widget is centered in its cell. default 1. pady : How many pixels to pad widget. ipady : How many pixels to pad widget. W. Python greenbutton = Button(frame.pack( side = LEFT ) blackbutton = Button(bottomframe. inside widget's borders.  row: The row to put widget in. text="Black". fg="brown") greenbutton. compass directions indicating the sides and corners of the cell to which widget sticks.  padx. default 1.pack( side = LEFT ) bluebutton = Button(frame. horizontally and vertically.pack( side = BOTTOM) root. fg="black") blackbutton. S. default is NW (the upper left corner of widget)  bordermode : INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border).mainloop( ) This would produce the following result displaying 12 labels arrayed in a 3 x 4 grid: Python Tkinter place() Method This geometry manager organizes widgets by placing them in a specific position in the parent widget.  height. E. width : Height and width in pixels. 411 . text='R%s/C%s'%(r.column=c) root. Syntax widget. OUTSIDE otherwise. NE.place( place_options ) Here is the list of possible options:  anchor : The exact spot of widget other options refer to: may be N. SE.0 and 1. compass directions indicating the corners and sides of widget.c). Python Example Try the following example by moving cursor on different buttons: import Tkinter root = Tkinter. NW. borderwidth=1 ). as a fraction of the height and width of the parent widget. relwidth : Height and width as a float between 0. W.Label(root.0. or SW.Tk( ) for r in range(3): for c in range(4): Tkinter.grid(row=r. S.  relheight. 0. it produces the following result: 412 . y : Horizontal and vertical offset in pixels. height=100. Example Try the following example by moving cursor on different buttons: from Tkinter import * import tkMessageBox import Tkinter top = Tkinter. Python  relx.Button(top.showinfo( "Hello Python".place(bordermode=OUTSIDE. as a fraction of the height and width of the parent widget. "Hello World") B = Tkinter. rely : Horizontal and vertical offset as a float between 0.Tk() def helloCallBack(): tkMessageBox.pack() B.  x.mainloop() When the above code is executed. command = helloCallBack) B. width=100) top.0 and 1. text ="Hello". Python ─ Further Extensions Any code that you write using any compiled language like C.dll (for dynamically linked library). which gives you access to the internal Python API used to hook your module into the interpreter.  On Unix machines.so (for shared object). This code is considered as an "extension. you need to group your code into four part:  The header file Python.  A table mapping the names of your functions as Python developers see them to C functions inside the extension module.h. You need to follow the includes with the functions you want to call from Python. On Windows machines. Additionally. First Look at a Python Extension For your first look at a Python extension module.h You need to include Python. this usually requires installing a developer-specific package such as python2. 413 . Python 27. you typically see .  The C functions you want to expose as the interface from your module. you are going to need the Python header files.h header file in your C source file. these libraries usually end in ." A Python extension module is nothing more than a normal C library. Make sure to include Python.5-dev. Pre-Requisites for Writing Extensions To start writing your extension.  Windows users get these headers as part of the package when they use the binary Python installer. or Java can be integrated or imported into another Python script. On Unix machines.h before any other headers you might need. C++. The Header File Python.  An initialization function. it is assumed that you have good knowledge of C or C++ to write any Python Extension using C programming. Py_RETURN_NONE. return the C equivalent of Python's None value. Your C functions usually are named by combining the Python module and function names together. as shown here: static PyObject *module_func(PyObject *self. There is no such thing as avoid function in Python as there is in C. that does this for us. The Python headers define a macro. static PyObject *MyFunctionWithKeywords(PyObject *self. Each one of the preceding declarations returns a Python object. Python The C Functions The signatures of the C implementation of your functions always takes one of the following three forms: static PyObject *MyFunction( PyObject *self. PyObject *kw). If you do not want your functions to return a value. static PyObject *MyFunctionWithNoArgs( PyObject *self ). PyObject *args. PyObject *args ). } This is a Python function called func inside of the module module. They are defined as static function. 414 . */ Py_RETURN_NONE. The names of your C functions can be whatever you like as they are never seen outside of the extension module. PyObject *args) { /* Do your stuff here. You will be putting pointers to your C functions into the method table for the module that usually comes next in your source code. char *ml_doc. Python The Method Mapping Table This method table is a simple array of PyMethodDef structures. This table needs to be terminated with a sentinel that consists of NULL and 0 values for the appropriate members. That structure looks something like this: struct PyMethodDef { char *ml_name. o This flag can be bitwise OR'ed with METH_KEYWORDS if you want to allow keyword arguments into your function. Here is the description of the members of this structure:  ml_name: This is the name of the function as the Python interpreter presents when it is used in Python programs. 415 . }.  ml_meth: This must be the address to a function that has any one of the signatures described in previous seection. int ml_flags.  ml_flags: This tells the interpreter which of the three signatures ml_meth is using. which could be NULL if you do not feel like writing one. o This flag usually has a value of METH_VARARGS.  ml_doc: This is the docstring for the function. PyCFunction ml_meth. o This can also have a value of METH_NOARGS that indicates you do not want to accept any arguments. . we have following method mapping table: static PyMethodDef module_methods[] = { { "func". The Python headers define PyMODINIT_FUNC to include the appropriate incantations for that to happen for the particular environment in which we're compiling. 0. } static PyMethodDef module_methods[] = { 416 . PyObject *args) { /* Do your stuff here. The Initialization Function The last part of your extension module is the initialization function.h> static PyObject *module_func(PyObject *self. */ Py_RETURN_NONE. NULL. } Here is the description of Py_InitModule3 function:  func: This is the function to be exported. "docstring. { NULL."). METH_NOARGS.. This function is called by the Python interpreter when the module is loaded. Python Example For the above-defined function. NULL } }. Your C initialization function generally has the following overall structure: PyMODINIT_FUNC initModule() { Py_InitModule3(func. It is required that the function be named initModule.  module_methods: This is the mapping table name defined above. The initialization function needs to be exported from the library you are building. where Module is the name of the module. (PyCFunction)module_func. module_methods. Putting this all together looks like the following: #include <Python.  docstring: This is the comment you want to give in your extension. NULL }. All you have to do is use it when defining the function. Python { "func". METH_NOARGS. Python extensions!!"). Save above code in hello. PyMODINIT_FUNC initModule() { Py_InitModule3(func. "Hello. {NULL} }. helloworld_funcs. } static char helloworld_docs[] = "helloworld( ): Any message you want to put here!!\n".. { NULL. NULL }. 417 . helloworld_docs}.").h> static PyObject* helloworld(PyObject* self) { return Py_BuildValue("s". NULL. 0. We would see how to compile and install this module to be called from Python script. (PyCFunction)helloworld. NULL } }. (PyCFunction)module_func. module_methods. } Example A simple example that makes use of all the above concepts: #include <Python.c file. } Here the Py_BuildValue function is used to build a Python value. static PyMethodDef helloworld_funcs[] = { {"helloworld". METH_NOARGS. "docstring. void inithelloworld(void) { Py_InitModule3("helloworld".. "Extension module example!"). following function. use the following command. For example. For the above module.0'. you need to prepare following setup.py install On Unix-based systems.core import setup. would be defined like this: 418 .helloworld() This would produce the following result: Hello.py script: from distutils. ['hello. that accepts some number of parameters. both pure Python and extension modules. in a standard way. Python extensions!! Passing Function Parameters As you will most likely want to define functions that accept arguments. This usually is not a problem on Windows. version='1. and copies the resulting dynamic library into an appropriate directory: $ python setup. you'll most likely need to run this command as root in order to have permissions to write to the site-packages directory.c'])]) Now.py as follows. with the right compiler and linker commands and flags. you would be able to import and call that extension in your Python script as follows: #!/usr/bin/python import helloworld print helloworld. Extension setup(name='helloworld'. Python Building and Installing Extensions The distutils package makes it very easy to distribute Python modules. Modules are distributed in source form and built and installed via a setup script usually called setup. \ ext_modules=[Extension('helloworld'. Importing Extensions Once you installed your extension. you can use one of the other signatures for your C functions. which would perform all needed compilation and linking steps. } Compiling the new version of your module and importing it enables you to invoke the new function with any number of arguments of any type: module. &i. &s)) { return NULL. (PyCFunction)module_func. 0. if (!PyArg_ParseTuple(args. d=2. METH_NOARGS. NULL } }. Each argument is represented by one or more characters in the format string as follows. Python static PyObject *module_func(PyObject *self. d=2.0) module. d=2. "ids". PyObject *args) { /* Parse args and do something interesting here. } /* Do something interesting here. PyObject *args) { int i.0.0. */ Py_RETURN_NONE.func(i=1. METH_VARARGS. NULL }. module_func. The first argument to PyArg_ParseTuple is the args argument. i=1) 419 . s="three") module. s="three". The second argument is a format string describing the arguments as you expect them to appear. char *s.func(s="three". &d. { NULL. } The method table containing an entry for the new function would look like this: static PyMethodDef module_methods[] = { { "func". { "func". This is the object you will be parsing. You can use API PyArg_ParseTuple function to extract the arguments from the one PyObject pointer passed into your C function. NULL }. double d. */ Py_RETURN_NONE. NULL. static PyObject *module_func(PyObject *self.func(1. Python You can probably come up with even more variations.) This function returns 0 for errors.char* format. and a value not equal to 0 for success. l long A Python int becomes a C long.. Here format is a C string that describes mandatory and optional arguments.. u Py_UNICODE* Python Unicode without embedded nulls to C. tuple is the PyObject* that was the C function's second argument. The PyArg_ParseTuple Function Here is the standard signature for PyArg_ParseTuple function: int PyArg_ParseTuple(PyObject* tuple. s# char*+int Any Python string to C address and length. i int A Python int becomes a C int. Here is a list of format codes for PyArg_ParseTuple function: Code C type Meaning c char A Python string of length 1 becomes a C char. L long long A Python int becomes a C long long Gets non-NULL borrowed reference to Python O PyObject* argument. d double A Python float becomes a C double. Read-only single-segment buffer to C address and t# char*+int length. f float A Python float becomes a C float. s char* Python string without embedded nulls to C char*.. 420 . Read/write single-segment buffer to C address and w# char*+int length. Format end.. A Python sequence is treated as one argument per (. } return Py_BuildValue("i". Python u# Py_UNICODE*+int Any Python Unicode C address and length. Returning Values Py_BuildValue takes in a format string much like PyArg_ParseTuple does.) as per . z char* Like s. Format end.. | The following arguments are optional.. } 421 . also accepts None (sets C char* to NULL). if (!PyArg_ParseTuple(args. &b)) { return NULL. "ii". Instead of passing in the addresses of the values you are building. also accepts None (sets C char* to NULL). a + b). Here's an example showing how to implement an add function: static PyObject *foo_add(PyObject *self. you pass in the actual values. . int b. &a. z# char*+int Like s#. followed by function name for error : messages.. PyObject *args) { int a. followed by entire error message text. item. "ii". &b)) { return NULL.b) 422 . if (!PyArg_ParseTuple(args. Python This is what it would look like if implemented in Python: def add(a. &a. } return Py_BuildValue("ii". b): return (a + b. this would be cauptured using a list in Python. PyObject *args) { int a. static PyObject *foo_add_subtract(PyObject *self. a . a . } This is what it would look like if implemented in Python: def add_subtract(a. int b.b). a + b. b): return (a + b) You can return two values from your function as follows. or NULL to None. The PyObject* result is a new reference. O PyObject* Passes a Python object and INCREFs it as normal. s# char*+int C char* and length to Python string. O& convert+void* Arbitrary conversion s char* C 0-terminated char* to Python string. null-terminated string to Python Unicode. f float A C float becomes a Python float. Code C type Meaning c char A C char becomes a Python string of length 1.. d double A C double becomes a Python float. Following table lists the commonly used code strings. l long A C long becomes a Python int. The following arguments of Py_BuildValue are C values from which the result is built. u Py_UNICODE* C-wide. or NULL to None. N PyObject* Passes a Python object and steals a reference. i int A C int becomes a Python int. of which zero or more are joined into string format.. Python The Py_BuildValue Function Here is the standard signature for Py_BuildValue function: PyObject* Py_BuildValue(char* format. or NULL to None. 423 ..) Here format is a C string that describes the Python object to build. Python u# Py_UNICODE*+int C-wide string and length to Python Unicode.) as per ..'zag':42}.. [.} builds dictionaries from an even number of C values. also accepts None (sets C char* to NULL).. alternating keys and values. or NULL to None.. z# char*+int Like s#... For example."zig"... alternately keys and values.] as per . Py_BuildValue("{issi}".} as per . w# char*+int Read/write single-segment buffer to C address and length.. Builds Python dictionary from C values. also accepts None (sets C char* to NULL)."zag".23... 424 . Builds Python list from C values. Builds Python tuple from C values.42) returns a dictionary like Python's {23:'zig'.. (. Code {... z char* Like s. {. Documents Similar To Python TutorialSkip carouselcarousel previouscarousel nextSmart Formsuploaded by vijayvikramtBasicsuploaded by Kyler GreenwayPyoracle Documentationuploaded by Julian SiffertFlexfield in Reportuploaded by SuneelTejParameterizationuploaded by Xs Softzsyntax of pythonuploaded by api-251329131Chapter 10 - TDL Procedural Capabilitiesuploaded by Rajesh Kumarcs100_2015S_syllabusuploaded by philNetOI Quick Start Guideuploaded by شاہد ندیم2961-perluploaded by manjunathvrpIntroduction to ActionScript 3uploaded by Noor Dedhy2010 04 24 PSCSTA Scribblersuploaded by Hélène Martinfunction in C++uploaded by Ibrahim Abdolexical 1uploaded by Kulveer SinghHowto Cportinguploaded by Brahmanand Singh002-1 Programming Basicsuploaded by Razer CicakBYOND Guideuploaded by Alex MonteroRobot Linear Tracking Profibusuploaded by markus_stark3137Revised Report on the Algorithmic Language (ALGOL 60) - Peter Naur (Editor)uploaded by Elias SullivanAccessing Oracle Forms From Workflow(and a Nifty Personalization)uploaded by tahirghafoorBatch Manuploaded by hergamia9872solutions-to-common-sap-sd-errors.pdfuploaded by sairamas07Array Questionsuploaded by Manaswini SharmaSmart Report Frameworkuploaded by Hari Prasad Reddy ChaganurRecursion in C/C++uploaded by SaketFaq Smartforms Questionsuploaded by seventhhemanthFanuc Alarmuploaded by Ananthan MadasamyENGR-25 Lec-11 Sp12 Programming-3 Decisionsuploaded by Iman Satria1.BL229TOLL- Install Manualuploaded by goclangthangquantstratTutorial.pdfuploaded by alexa_sherpyFooter MenuBack To TopAboutAbout ScribdPressOur blogJoin our team!Contact UsJoin todayInvite FriendsGiftsSupportHelp / FAQAccessibilityPurchase helpAdChoicesPublishersLegalTermsPrivacyCopyrightSocial MediaCopyright © 2018 Scribd Inc. .Browse Books.Site Directory.Site Language: English中文EspañolالعربيةPortuguês日本語DeutschFrançaisTurkceРусский языкTiếng việtJęzyk polskiBahasa indonesiaYou're Reading a Free PreviewDownloadClose DialogAre you sure?This action might not be possible to undo. Are you sure you want to continue?CANCELOK


Comments

Copyright © 2024 UPDOCS Inc.