KEMBAR78
PYTHON | PDF
0% found this document useful (0 votes)
242 views461 pages

PYTHON

how to program in python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
242 views461 pages

PYTHON

how to program in python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 461
programming language tutorialspoint SIMPLY EASYLEARNIN G www.tulorlialspoint.com [F} het0s://wwwfacebook.com/tutorialspointindia 3 pttps://twitter.com/tutorialspoint 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 2014 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 contact@tutorialspoint.com, bees ou Python Prerequisites. Disclaimer & Copyright... Table of Contents, 1. OVERVIEW... History of Python. Python Features.. 2. ENVIRONMENT .nsssnstnsressne Local Environment Setup. Getting Python. Instaling Python.. Setting up PATH . Setting path at Unix/Linu Setting path at Windows.. Python Environment Variables.. Running Python. 3. BASICSYNTAX. First Python Program .. Lines and indentation.. ‘Mult-Line Statements... Comments in Python... Using Blank Lines Waiting for the User ‘Multiple Statements on a Single Line. ‘Multiple Statement Groups 2s Suites. ‘Command Line Arguments. ‘Accessing Command-Line Arguments.. Parsing Command-Line Arguments aetopt.getopt method... Exception getopt.Getoptérror: VARIABLE TYPES. ‘Assigning Values to Variable ‘Multiple Assignment . Standard Data Types . Python Numbers. Python strings. Python Lists. Python Tuples Python Dictionary. Data Type Conversion BASIC OPERATORS....ssesnnnnnn ‘Types of Operators Python Arithmetic Operators Python Comparison Operators. Python Assignment Operators Python Bitwise Operators Opesoraispon: Python Logical Operators. Python Membership Operators. Python Identity Operators. Python Operators Precedence. 6, DECISION MAKING. If statement I..else Statement ‘The elf Statement. Single Statement Suites. 7. Loops While Loop.. The Infinite Loop - - 37 Using else Statement with Loops .. Single Statement Suites. For Loo} erating by Sequence Index. Using else Statement with Loops Nested Loops . Loop Control Statements. Break Statement. Continue Statement... ~ ~ 6a ass Statement. 8. NUMBERS. ‘Number Type Conversion.. Random Number Functions. Tiganometie Function v Opesoraispon: Python ‘Mathematical Constants. 9, STRINGS. ‘Accessing Values in Strings Updating Strings. Escape Characters . String Special Operators. String Formatting Operator. - - 7 Triple Quotes . Unicode String. Built-in String Methods. Python Lists. - - - wa ‘Accessing Values in List, Updating Lists Deleting List Elements... Basic List Operations... Indexing, Slicing, and Matrixes. ‘Built-in List Functions and Methods. 11. TUPLES... ‘Accessing Values in Tuples. Updating Tuples: Deleting Tuple Element: Basic Tuples Operations Indexing, Slicing, and Matries. ‘No Enclosing Detimiters: ‘Built-in Tuple Functions. v Operoratsnon: Python 12, DICTIONARY snsnnninnnnnnnninininnnnnnnnnnnnnnins 3 ‘Accessing Values in Dictionary Updating Dictiona Delete Dictionary Elements.. Properties of Dictionary Keys. in Dictionary Functions and Methods... 13. DATE AND TIME. What is Tek... What is TimeTuple? Getting Current Time. nm Getting Formatted Time. mn Getting Calendar for a Month . nm The time Mode ono an The colendar Module Other Modules a 14. FUNCTIONS... Passing by Reference Versus Passing by Value. Function Arguments. Required Arguments Keyword Arguments. Default Arguments. Variable Length Arguments.. ‘The Anonymous Function: ‘The return Statement. Opesoraispon: Scope of Variables. Global vs. Local variables: 15. MODULES.. ‘The import Statement... Locating Modules: - - 205 ‘The PYTHONPATH Variable. "Namespaces and Scopin The d Function. ‘The globols{) and locals) Functions. ‘The reload{) Function. Packages in Python 16. FILES VO. Printing tothe Screen... Reading Keyboard input. ‘The raw_input Function ‘The input Function, Opening and Closing Files. ‘The open Function The file Object Attributes. The close() Method. Reading and Writing Files. ‘The write() Method. ‘The read{) Method. Fle Postion. vi Opesoraispon: Python Renaming and Deleting Files ‘The rename() Method. ‘The remove() Method... Directories in Python.. File and Directory Related Methods 17. EXCEPTIONS What is Exception?. Handling an Exceptio ‘The except Clause with No Exceptions. ‘The except Clause with Multiple Exceptions... The tryfinally Clause. ‘Argument of an Exception, Raising an Exceptior User-Defined Exceptions. 18. CLASSES AND OBJECTS Overview of OOP Terminology. Creating Classes Creating instance Objects. ‘Accessing Attributes Built-in Class Attributes. Destroying Objects (Garbage Collection). ‘las inheritance vii tutorialspoint Python Overriding Methods... 270 ‘Base Overloading Methods.. am Overloading Operators... am Data Hiding 272 28 25 a Search and Replace nnn 278 Regular-Exprestion Modifiers: Option Flags. 23 ‘Regular-Expression Patterns Regular-Expression Example Grouping with Parentheses. Backreferences.. 20. Web Server Support and Configuration.. First G1 Program. HTTP Header. - ~ ~ 290 C61 Environment Variable GET and POST Methods. Passing Information using GET method: Simple URL Example : Get Method. ‘Simple FORM Example: GET Metho Opesoraispon: Passing Information Using POST Mothod. Passing Checkbox Data to CGI Program.. Passing Radio Button Data to CGI Program ... Passing Text Area Data to CGI Program.. Passing Drop Down Box Data to CGI Using Cookies in Ca How it Works?. Setting up Cookies. Retrievine Cookies. File Upload Example How To Raise a "File Download! Dialog Box?. 21. DATABASE ACCESS. What is MySqLdb?. How do | install MySQLab? . Database Connection w. (Creating Database Table 7 . a1 INSERT Operation. [READ Operation Update Operation. DELETE Operation .. ROLLBACK Operation wn. Disconnecting Database Handling Errors 22, NETWORK PROGRAMMING. Opesoraispon: What ie Sockets? ‘The socket Module. Server Socket Methods Client Socket Methods. General Socket Methods A Simple Server A Simole client. ~ see ~ 225 Python internet modules. Further Readings 23, SENDING EMAIL. Sending an HTML e-mail using Python. Sending Attachments as an E-mail 28, MULTITHREADING ....0 sce 3M ‘Starting a New Threa ‘The Threading Module: Creating Thread Using Threading Module: ‘Synchronizing Threads ‘Multithreaded Priority Queue 25. XML PROCESSING... What is XML? XML Parser Architectures and APIs Parsing XML with SAX API ‘The make_parser Method ‘The parse Method. ‘The parseString Method. Parsing XML with DOM API Operoratsnon: 26. GUI PROGRAMMING. Tkinter Programming -.. ‘Thinter Widgets. . 7 7 386 Geometry Management. 27. FURTHER EXTENSIONS. Pre-Requisites for Writing Extensions. First Look at a Python Extension ‘The Header File Python.h . ‘The initialization Function. xii GD tutorialspoint 1. OVERVIEW Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. + Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. + Python is Intera You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. + Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects. + 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. 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 Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmaliTalk, Unix shell, and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress. Python Features Python's features include: + Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Opereniatensrs Python 2 Facy-ta-raads Duthan cada ic mara clearly defined and visible tn the avec + Easy-to-maintain: Python's source code is fairly easy-to-maintain. + Abroad standard library: Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. + Interactive Mode: Python has support for an interactive mode which allows interactive testing and debugging of snippets of code. + Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. + Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. + Databases: Python provides interfaces to all major commercial databases. + GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. + Scalable: Python provides a better structure and support for large programs than shell scripting. Apart from the above-mentioned features, Python has a big list of good features, 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. ‘+ It provides very high-level dynamic data types and supports dynamic type checking. + IT supports automatic garbage collection. + It can be easily integrated with C, C++, COM, Activex, CORBA, and Java. Opesoratsncne 2. ENVIRONMENT Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment. Local Environment Setup Open a terminal window and type "python" to find out if it is already installed and which version is installed. ‘+ Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.) ‘+ Win 9x/NT/2000 ‘+ Macintosh (Intel, PPC, 68K) + os/2 ‘+ DOS (multiple versions) + PalmOS + Nokia mobile phones ‘+ Windows CE ‘+ Acorn/RISC OS + BeOS + Amiga + VMS/OpenvMS © QNK + VxWorks + Psion + Python has also been ported to the Java and .NET virtual machines Getting Python The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python: http:/www.python.ora/. ‘You can download Python documentation from www.python.ora/doc/. The documentation is available in HTML, PDF, and PostScript formats. Python Installing Python Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. 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. + Open a Web browser and go to http:/www.python.orgidownload!. + Follow the link to download zipped source code available for Unix/Linux. + Download and extract files. ‘+ Editing the Modules/Setup file if you want to customize some options. + run /configure script + make + make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonxXx where XX is the version of Python. Windows Installation Here are the steps to install Python on Windows machine. ‘+ Open a Web browser and go to http:/hwww.python.oraidownload/ + Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. + To use this installer python-xYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. + Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Macintosh Installation Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current 4 *. 5 a Python version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available. Jack Jansen maintains it and you can have full access to the entire documentation at his website - htipvhwwcwi nU~jackimacoythonhiml. You can find complete installation details for Mac OS installation. Setting up PATH Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case- sensitive; Windows is not). In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. 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 bash shell (Linux): type export ATH="$PATH:/usr/local/bin/python" and press Enter. + In the sh or ksh shell: type PATH="$PATH:/usr/local/bin/python" and press Enter. * Note: /ust/local/bin/python is the path of the Python directory Setting path at Windows To add the Python directory to the path for a particular session in Windows: At the command prompt: type path Y%path%;C: \Python and press Enter. Note: C:\Python is the path of the Python directory Opeseratsrcne Python Python Environment Variables Here are important environment variables, which can be recognized by Python: Variable Description PYTHONPATH _It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. PYTHONSTARTUP It contains the path of an initialization file containing Python source code, It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. PYTHONCASEOK Its used in Windows to instruct Python to find the first case- insensitive match in an import statement. Set this variable to any value to activate it. PYTHONHOME It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. Running Python There are three different ways to start Python: (1) Interactive Interpreter You can start Python from Unix, DOS, or any other system that provides you a ‘command-line interpreter or shell window. Enter python the command line. Start coding right away in the interactive interpreter. Tanvthan i male/niane python? # Unix/Linux 6 Opereniatensrs Python ci>python # windows /D08 Here is the list of all the available command line options: Option Description -d It provides debug output. It generates optimized bytecode (resulting in .pyo files). Do not run import site to look for Python paths on startup. verbose output (detailed trace on import statements). disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6. -ccmd run Python script sent in as cmd string file run Python script from given file (2) Script from the Command-line ‘A Python script can be executed at command line by invoking the interpreter on your application, as in the following: $python script. py # Unix/Linuxor python% script.py # Unix/Linuxor C:>python script.py # Windows /D0S Note: Be sure the file permission mode allows execution. (3) Integrated Development Environment You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. + Unix: IDLE is the very first Unix IDE for Python. + Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI. Opereniatensrs Python + Macintosh: The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine. Note: All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux We already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online. point 3. BASIC SYNTAX The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. First Python Program Let us execute programs in different modes of programming. Interactive Mode Programmin, Invoking the interpreter without passing a script file as a parameter brings up the following promy $ python Python 2.4.3 (#1, Nov 11 220, 13:34:43) [occ 4.1.2 20080704 (Red Hat 4.1.2-48)] on Linux2 Type "help", “copyright”, “credits” or “License” for more information. >>> Type the following text at the Python prompt and press the Enter: >>> print “Hello, Python!"; If vou are runnina new version of Pvthon. then vou need to use orint statement with parenthesis as in print ("Hello, Python!" produces the following result: However in Python version 2.4.3, this Hello, Python! Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no. longer active. Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file: print "Hello, Python!"; Opeseratsrcne Python We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows: $ python test.py This produces the following result: Hello, Python! Let us try another way to execute a Python script. Here is the modified test.py file: #1 /usr/bin/python print "Hello, Python!"; We assume that you have Python interpreter available in /ust/bin directory. Now, try to run this program as follows: $ chmod +x test.py —# This is to make file executable $./test.py This produces the following result: Hello, Python! Python Identifiers ‘A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python isa case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. Here are naming conventions for Python identifiers: ‘+ Class names start with an uppercase letter. All other identifiers start with a lowercase letter. ‘+ Starting an identifier with a single leading underscore indicates that the identifier is private. Opereniatensrs 10 Python ‘+ Starting an identifier with two leading underscores indicates a strongly private identifier, + If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. Python Keywords The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. 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. Blocks of code are denoted by line indentation, which is rigidly enforced. Opereniatensrs 1 Python The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example: if True: print "True" else: print “False” However, the following block generates an error: if True: print “Answer” print "True" else: print “answer’ print "False" Thus, 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. Just make sure you understood various blocks even if they are without braces. #1/usr/bin/python import sys try # open file stream file = open(file_nane, except T0Error: print “There was an error writing to", file_name 12 Opeseratsrcne Python sys.exit() print “Enter '", file_finish, print “* When finished while file_text I= filefinish: file_text = rau_input("Enter text: ") if file_text file_finish: # close the file fille.close break file.write(file_text) file.write(*\n") file.close() file_name = raw_input("Enter filename: if len(file_name) == 0: print “Next time please enter something’ sys.exit() try: file = open(File_name, "r*) except 10Error: print “There was an error reading file” sys.exit() file_text = file.read() file.close() print file_text Opereniatensrs Multi-Line Statements 13 Python ‘Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example: total = itemone + \ item_two + \ item_three Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example: days = ['Monday’, ‘Tuesday’, ‘Wednesday", ‘Thursday’, ‘Friday"] Quotation in Python Python accepts single ("), double (") and triple ("" or ""*) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal: word = “word” sentence his is a sentence.” paragraph = """This is a paragraph. It is made up of multiple lines and sentences Comments in Python ‘A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. #1 /usr/bin/ python # First comment if Opereniatensrs Python print “Hello, Python!"; # second comment This produces the following result: Hello, 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 conment. # This is a comment, too. # This is a conment, too. # I said that already. Using Blank Lines Aline containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement. Waiting for the User The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action: #1/usr/bin/python raw_input("\n\nPress the enter key to exit.") Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application. 15 Opeseratsrcne Python Multiple Statements on a Single Line The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon: import sys; x = ‘foo"y sys.stdout.write(x + "\n") Multiple Statement Groups as Suites ‘A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. 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. 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. Python enables you to do this with -h: $ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -¢ cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -£ 5 Agnore environment variables (such as PYTHONPATH) ch__ pnint this help message and exit 16 Opeseratsrcne Python [etc. ] You can also program your script in such a way that it should accept various options. Accessing Command-Line Arguments Python provides a getopt module that helps you parse command-line options and arguments. $ python test.py argl arg? arg3 The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes: ‘*sys.argv is the list of command-line arguments. ‘+ len(sys.argv) is the number of command-line arguments. Here sys.argv[0] is the program i.e. script name. Example Consider the following script test.py: #1/usr/bin/python import sys print ‘Number of arguments:', len(sys.argv), ‘arguments." print ‘Argument List:', str(sys.argv) Now run above script as follows: $ python test.py argl arg? arg3 This produces the following result: Number of arguments: 4 arguments. Argument List: ['test.py’, ‘argi', ‘arg2", ‘arg3'] 7 Opereniatensrs Python NOTE: As mentioned above, first argument is always script name and it is also being counted in number of arguments. Parsing Command-Line Arguments Python provided a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command line argument parsing getopt getopt method This method parses command line options and parameter list. Following is simple syntax for this method: getopt .getopt(args, options[, long_options]) Here is the detail of the parameters: ‘+ args: This is the argument list to be parsed. ns: This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:). + long_options: This is optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign To accept only long options, options should be an empty string. + This method returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped. + Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.9., ) or two hyphens for long options (e.g., '--long-option’), Exception getopt.GetoptError: This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. ‘The argument to the exception is a string indicating the cause of the error. The attributes msg and opt give the error message and related option. Opeseratsrcne 18 Python 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. Usage of the script is as follows: usage: test.py -i -o Here is the following script to test.py: #!/usr/bin/ python import sys, getopt def main(argv): inputfile = outputfile = try opts, args = getopt .getopt(argv, "hizo:", ["iFilen","oFile="]) except getopt.GetoptError: print ‘test.py -i cinputfile> -o ’ sys.exit(2) for opt, arg in opts: if opt print ‘test.py -i -o * sys.exit() elif opt in (" ) “sifile"): inputfile = arg elif opt in ») “s-ofile"): outputfile = arg print ‘Input file is “', inputfile print ‘Output file is "', outputfile 1s Qereriatenore Python if _name__ == "_main_' main(sys.argv[1:]) Now, run above script as follows: $ test.py -h usage: test.py -i -o $ test.py -i BMP -0 usage: test.py -i -o $ test.py -i inputfile Input file is " inputfile Output file is 20 4. VARIABLE TYPES Variables are nothing but reserved memory locations to store values. This means when you create a variable, you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. ‘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. For example: #1/usr/bin/python counter = 100 # An integer assignment miles = 1000.0 # A floating point name John" # A string print counter print miles print name Here, 100, 1000.0, and "John" are_ = the_~-—values_-—_ assigned to counter, miles, and name variables respectively. This produces the following result: 100 1000.0 21 Opeseratsrcne Python Multiple Assignment Python allows you to assign a single value to several variables simultaneously. For example: Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example: a, by c= 4, 2, “john® Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c Standard Data Types The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them, Python has five standard data types: * Numbers © String © List = Tuple + Dictionary Python Numbers Number data types store numeric values. Number objects are created when you assign a value to them. For example: var2 = 10 You can also delete the reference to a number object by using the del statement. The syntax of the del statement is: Opereniatensrs 22 Python del vara[,var2{,var3[..--)varn}]]] You can delete a single object or multiple objects by using the del statement. For example: del var del var_a, var_b Python supports four different numerical types: ‘+ int (signed integers) ‘+ long (long integers, 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 Jong Float complex 10 51924361L 00 3.14) 100 0193231, 1520 45) 786 ona. 219 9.322¢-36) 080 (0xDEFABCECBDAECBFBAE! 323+018 876) -0490 535633629843. -90. ~.6545+0) -0x260—-052318172735L -32,54e100 3e+26) 0x69 -4721885298529L 702-612 4.53e-7} 23 Opesoratsncne Python ‘+ Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L. + Acomplex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x is the real part and b is the imaginary part of the complex number. Python Strings Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at O in the beginning of the string and working their way from -1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example: #1 /usr/bin/ python str = ‘Hello World!" print ste # Prints complete string print str[@] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to Sth print ste[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! 4 le Mo World! Hello World!Hello World! 24 Opeseratsrcne Python Hello World!TEST Python Lists Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ({]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging toa list can be of different data type. 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. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example: #!1/usr/bin/python list = [ ‘abed', 786 , 2.23, ‘john’, 70.2 ] tinylist = [123, ‘john'] print list # Prints complete list print list[e] # 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: [‘abed", 786, 2.23, ‘john’, 70.200000000000003] abed (786, 2.23] [2.23, "john", 70.200000000000003] [123, "john", 123, ‘John"] 25 Opeseratsrcne Python ['abed', 786, 2.23, ‘John', 70,200000¢00000003, 123, ‘john'] Python Tuples A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read- only lists. For example: #1/usr/bin/ python tuple = ( ‘abcd", 786 , 2.23, ‘john’, 70.2 ) tinytuple = (123, ‘john') print tuple # Prints complete list print tuple[@] # Prints first element of the list prant tupieia:3) # PrANTs e1ements startang trom zna ti11 sra 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: (abed", 786, 2.23, ‘John’, 70.200000000000003) abcd (786, 2.23) (2.23, "john", 70.200000000000003) (223, "john", 123, *john*) (abed', 786, 2.23, ‘john’, 78.20¢000000000003, 123, ‘john‘) 26 Opereniatensrs Python The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists: #1/usr/bin/ python tuple (tabed", 786 , 2.23, ‘John’, 70.2 ) list = [ ‘abed', 786 , 2.23, ‘john’, 70.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list Python Dictionary Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and acresced rising satiare hraras (11) For examnie: #1/usr/bin/ python dict = dict[‘one'] = “This is on dict[2] = "This is two" tinydict = {‘name': ‘john’, ‘code’ :6734, ‘dept’: ‘sales'} print dict[‘one'] # Prints value for ‘one’ key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values This produces the following result: Opeseratsrcne 27 Python This is one This is two {'dept': ‘sales’, ‘code’: 6734, ‘name’: ‘john'} ['dept', ‘code’, ‘name*] Usales', 6734, ‘john’ Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order”; they are simply unordered. Data Type Conversion ‘Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value. Function int(x [,base]) long(x [,base] ) float(x) complex(real Limag]) str(x) repr(x) eval(str) tuple(s) Description Converts x to an integer. base specifies the base if x is a string. Converts x to a long integer. base specifies the base if x is a string. Converts x to a floating-point number. Creates a complex number. Converts object x to a string representation. Converts object x to an expression string. Evaluates a string and returns an object. Converts s to a tuple. 28 Opeseratsrcne list(s) set(s) dict(d) frozenset(s) chr(x), unichr(x) Python Converts s toa list. Converts s to a set. Creates a dictionary. d must be a sequence of (key, value) tuples. Converts s to a frozen set. Converts an integer to a character. 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. oct(x) Converts an integer to an octal string. 29 tutorialspoint Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operators Python language supports the following types of operators. + 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, then Operator Description Example + Addition Adds values on either side of the operator. a+b=30 - Subtraction Subtracts right hand operand from left hand operand. * Multiplication Multiplies values on either side of the operator _a * b = 200 30 Opereniatensrs Python / Division Divides left hand operand by right hand b/a operand % Modulus Divides left hand operand by right hand b%a= operand and returns remainder ** Exponent Performs exponential (power) calculation on a**b =10 to the Ws Floor Division - The division of operands where 9//2 = 4 and the result is the quotient in which the digits 9.0//2.0 after the decimal point are removed. Example Assume variable a holds 10 and variable b holds 20, then: #1 /usr/bin/ python print "Line 1 - Value of c is ", ¢ print “Line 2 - Value of c is", ¢ print “Line 3 - Value of ¢ is ", ¢ ceasb print “Line 4 - Value of c is", ¢ Geren Python print “Line 5 - Value of ¢ is", ¢ b c= arb print “Line 6 - Value of ¢ is", ¢ a=10 bes c= a//b print “Line 7 - Value of c is ", ¢ When you execute the above program, it produces the following result: Line 1 - Value of ¢ is 31 Line 2 - Value of ¢ is 11 Line 3 - Value of ¢ is 210 Line 4 - Value of ¢ is 2 Line 5 - Value of ¢ is 1 Line 6 - Value of ¢ is 8 Line 7 - Value of ¢ is 2 Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then 32 Python Example <> If the values of two operands are equal, then the condition becomes true. If values of two operands are not equal, then condition becomes true. If values of two operands are not equal, then condition becomes true. If the value of left operand is greater than the value of right operand, then condition becomes true. If the value of left operand is less than the value of right operand, condition becomes true. If the value of left operand is greater than or equal to the value of right ‘operand, then condition becomes true. If the value of left operand is less than ‘or equal to the value of right operand, then condition becomes true. Example Assume variable a holds 10 and variable b holds 20, then: (2 ==b) is not true. b) is true. (a <> b) is true. This is similar to != operator. (a > b) is not true. (a = b) is not true. (a <= b) is true. #!/usr/bin/ python 33 Python if (a b): print “Line 1 - else: print “Line 1 - if (al=b): print “Line 2 - else: print “Line if (aod print “Line else: print "Line 3 - if (acd): print “Line else: print “Line 4 - if (a>b): print “Line 5 - else: print ine 5 - is is is is is is is is is equal to b" not equal to b* not equal to b* equal to b" not equal to b” equal to b" less than b" not less than b" greater than b* not greater than b’ 34 Python b = 20; if (aceb): 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" 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 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 35 @Mrrorisiapoint Python + It adds right operand to the left operand c += a is equivalent Add AND and assign the result to left operand toc=c+a It subtracts right operand from the left c -= a is equivalent operand and assign the result to left toc=c-a operand Subtract AND It multiplies right operand with the left c *= a is equivalent Multiply ano OPetand and assign the result to left toc=c*a operand i It divides left operand with the right a is equivalent iia AND ooerend and assign the result to left toc=c/a %= It takes modulus using two operands and c %= a is equivalent Modulus AND 2859" the result to left operand toc=c%a oe Performs exponential (power) calculation Exponent AND Briones and assign value to the left We It performs floor division on operators and c //= a is equivalent Floor Division _255!9" value to the left operand toc=c//a Example ‘Assume variable a holds 10 and variable b holds 20, then: #1 /usr/bin/python Opeseratsrcne so Python print “Line 1 ctsa print "Line 2 print “Line 3 clea print “Line 4 c #2 c%&a print “Line 5 print “Line 6 cs print “Line 7 Value of ¢ Value of ¢ Value of c value of ¢ Value of ¢ Value of ¢ Value of ¢ is is is is is When you execute the above program, it produces the following result: Line 1 - Value of c is 31 Line 2 - Value of ¢ is 52 Line 3 - Value of ¢ is 1092 Lane 4 - value ot ¢ as 52 Line 5 - Value of ¢ is 2 37 Opeseratsrcne Python Line 6 - Value of ¢ is 2097152 Line 7 - Value of ¢ 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 alb = 0011 1101 a%b = 0011 0001 ~a = 11000011 There are following Bitwise operators supported by Python language Operator Description Example & Operator copies a bit to the result if it (a &b) = 12 exists in both operands. Binary AND (means 0000 1100) | Binary OR It copies a bit if it exists in either (a |b) = 61 eperand (means 0011 1101) * Binary XOR It copies the bit if it is set in one (a * b) = 49 (means operand but not both. 0011 0001) ~ It is unary and has the effect of (~a ) = -61 (means Binary Ones ‘flipping’ bits. Complement Opereniatensrs << Binary Left Shift >> Binary Right Shift The left operands value is moved left by the number of bits specified by the right operand. The left operands value is moved right by the number of bits specified by the right operand. 1100 0011 in 2's complement form due to a signed binary number. 38 Python a<<2=240 (means 1111 0000) a>>2=15 (means 0000 1111) Example #1/usr/bin/python a= 60 # 60 = 0011 1100 b= #13 = 0000 1101 « c= aad; #12 = 0900 1100 print “Line 1 - Value of ¢ is", ¢ c=albs # 61 = 0011 1101 print “Line 2 - Value of c is ", ¢ cu ards # 49 = 0011 0901 print “Line 3 - Value of ¢ is ", ¢ c a3 # -61 = 1100 e011 print “Line 4 - Value of c is ", ¢ crac 25 # 248 = 1111 e988 print “Line 5 - Value of ¢ is", ¢ Opereniatensrs Python c= a >> 25 #15 = ee00 1111 print “Line 6 - Value of ¢ is ", ¢ When you execute the above program it produces the following result: Line 1 - Value of ¢ is 12 Line 2 - Value of c is 61 Line 3 - Value of ¢ is 49 Line 4 - Value of ¢ is -61 Line 5 - Value of ¢ is 240 Line 6 - Value of ¢ 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. Logical AnD Becomes true. 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 °P°T Opeseratsrcne Python Membership Operators 40 Python 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 in Evaluates to true if it finds a variable in the specified sequence and false otherwise. not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. Example Example x iny, here in results in a 1 if x is a member of sequence y. x not in y, here not in results in a 1 if x is not a member of sequence y. #1 /usr/bin/ python 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: 41 Opereniatensrs Python 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 Python Identity Operators Identity operators compare the memory locations of two objects. There are two Identity operators as explained below: Operator Description is Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. is not Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. Example Example x Is y, here is results in 1 If id(x) equals id(y). x is not y, here is not results in 1 if id(x) is not equal to id(y). #1 /usr/bin/ python Opereniatensrs 42 Python a= 20 b = 20 if (aisb): print “Line 1 - a and b have same identity" else: print “Line 1 - a and b do not have same identity" if ( ida) 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 (aisb): print “Line 3 - a and b have same identity" else: print “Line 3 - a and b do not have same identity” if (a is not b ): print “Line 4 - a and b do not have same identity" else: print "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 2 - a and b have same identity Opeseratsrcne 43 Python Line 3 - a and b do not have same identity Line 4 - a and b do not have same identity Python Operators Precedence The following table lists all operators from highest precedence to lowest. Operator ™ Exponentiation (raise to the power) wt Ccomplement, unary plus and minus (method names for the last two are +@ and -@) */%// Multiply, divide, modulo and floor division + Addition and subtraction p> << Right and left bitwise shift & Bitwise ‘AND’ al Bitwise exclusive *OR' and regular ‘OR’ Comparison operators Equality operators Assignment operators is is not Identity operators in not in Membership operators , ee 44 Python not or and Logical operators Operator precedence affects how an expression is evaluated. For example, x = 7 + 3 + 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Example #1 /usr/bin/ python e=(atb)tesd #( 30°15) /5 print “Value of (a+b) *c/dis*, e e=((a+b)te)/d #0415) /5 print “Value of ((a +b) *c)/dis", e e@= (a+b) *(c/d); — # (38) * (15/5) print "Value of (a+b) * (c/d) is", e e=at(b*c)/d5 # 20 + (150/5) print "Value of a+ (b*c)/dis", e When you execute the above program, it produces the following result: Opesoratsncne 45 Python Value of (a+b) *c /d is 90 value of ((a +b) * c) / d is 98 Value of (a +b) * (c / d) is 98 Value of a+ (b * c) / d is 50 46 6. DECISION MAKING Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as ‘outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE Following is the general form of a typi the programming languages: If condition is true otherwise. ical decision making structure found in most of I condition is false vy Python programming language assumes any non-zero and non-null values as TRUE, and if itis either zero or null, then it is assumed as FALSE value. Python programming language pr statements. Click the following links Statement if statements Opeseratsrcne if...else statements rovides following types of decision making to check their detail. Description if statement consists of a boolean expression followed by one or more statements. 47 Python if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE nested if statements You can use one if or else if statement inside another if or else if statement(s) Let us go through each decision making briefly: If Statement It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison. Syntax if expression: statement(s) If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed. Flow condition Is true condition is false 48 Opereniatensrs Python eaanipre #1 /usr/bin/ python var1 = 108 if vara: print “1 - Got a true expression value" print var2 var2 = @ if var2: print "2 - Got a true expression value" print var2 print “Good bye!" ‘When the above code is executed, it produces the following result: 1 - Got a true expression value 100 Good bye! If...else Statement An else statement can be combined with an if statement. 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. The else statement is an optional statement and there could be at most only one else statement following if. Syntax The syntax of the /f..else statement is: if expression 49 Opereniatensrs Python statement (s) else: statement (s) Flow Diagram Hf condition is true If condition] ba Example #!/usr/bin/ python vari = 100 if vara: print = Got a true expression value" print vari else: print ~ Got a false expression value” print vari var2 = @ 50 Qoerertecs Python if var2: print "2 - Got a true expression value" print var2 else: = Got a false expression value’ print print var2 print "Good bye!" When the above code is executed, it produces the following result 1 - Got a true expression value 100 2 - Got a false expression value ° Good bye! 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, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. Syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement (s) 51 ts =a Python else: statement(s) Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows: Example #1/usr/bin/ python var = 100 if var == 200: print "1 - Got a true expression value" print var elif var == 150: print "2 - Got a true expression value" print var elif var == 100: print "3 - Got a true expression value" print var else: print "4 - Got a false expression value" print var print “Good bye!" When the above code is executed, it produces the following result: 3 - Got a true expression value 100 pow eye 52 Qoerertecs Python 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, Here is an example of a one-line if clause: #1 /usr/bin/ python if ( var == 100 ) : print “Value of expression is 100" print “Good bye!" When the above code is executed, it produces the following result: Value of expression is 100 Good bye! 53 Gyesoriatercine 7. LOOPS In general, statements are executed sequentially: The first statement in a function is, executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement: Python programming language provides following types of loops to handle looping requirements. Loop Type Description Repeats a statement or aroun of statements while a aiven while loop condition is TRUE. It tests the condition before executing the loop body. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Opereniatensrs for loop. 54 Python You can use one or more loop inside any another while, for nested loo — or do..while loop. While Loop ‘Awhile loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax The syntax of a while loop in Python programming language is: while expression: statement(s) Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. In Python, 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. Python uses indentation as its method of grouping statements. Flow Diagram 55 Python dh expressions starement(s) Heondition is tue i. condition] is false ;— Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example #!/usr/bin/ python count = @ while (count < 9): print ‘The count is:', count count = count +1. print "Good bye!" When the above code is executed, it produces the following result: The count is: @ The count is: 1 The count is: 2 Opeseratsrcne Python 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, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9, With each iteration, the current value of the index count is displayed and then increased by 1. The Infinite Loop ‘A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop. ‘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. #1 /usr/bin/ python var = 1 while var == 1: # This constructs an infinite loop nun = raw_input ("Enter a number :") print "You entered: ", num print “Good bye!" When the above code is executed, it produces the following result: Enter a number :20 57 Opereniatensrs Python 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", line 5, in «nodule> num = ran_input("Enter a nunber :") Keyboardinterrupt ‘Above example goes in an infinite loop and you need to use CTRL+C to exit the program. Using else Statement with Loops Python supports to have an else statement associated with a loop statement. + If the else statement is used with a for loon. the else statement is executed when the loop has exhausted iterating the list. + Ifthe else statement is used with a while loop, the else statement is executed when the condition becomes false. 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, otherwise else statement gets executed. #1 /usr/bin/ python count = @ while count < 5: print count, " is less than 5 count = count +1 else: 58 Opereniatensrs Python print count, " is not less than 5" When the above code is executed, it produces the following result: @ is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 As less than 5 5 is not less than 5 Single Statement Suites Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header. Here is the syntax and example of a one-line while clause: #1/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. For Loop It has the ability to iterate over the items of any sequence, such as a list or a string. Syntax Opeseratsrcne 59 Python for iterating var in sequence: statements (s) If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating var, and the statement(s) block is executed until the entire sequence is exhausted. for iterating_varin sequence : statement(s) Hfno more item in sequence Next item from sequence Example #!/usr/bin/ python for letter in ‘Python’: # First Example print ‘Current Letter :', letter fruits = [‘banana’, ‘apple’, ‘mango" ] for fruit in fruits: # Second Exanple print ‘Current fruit :', fruit 60 Opereniatensrs Python 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 : 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. Following is a simple example: #1 /usr/bin/ python fruits = ['banana', ‘apple’, ‘mango"] for index in range(len(fruits)): print ‘Current fruit :', fruits[index] print “Good bye!" When the above code is executed, it produces the following result: Current fruit : banana Opereniatensrs 61 Python Current fruit : apple Current fruit : mango Good bye! Here, we took the assistance of the len() built-in function, 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. Using else Statement with Loops Python supports to have an else statement associated with a loop statement. + If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. + Ifthe else statement is used with a while loop, the else statement is executed when the condition becomes false. The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20. #1 /usr/bin/ python for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if numa ito determine the first factor j-nun/i to calculate the second factor print "Xd equals %d * Xd" % (num, i,j) break #to move to the next number, the #first FOR else: # else part of the loop print num, ‘is a prime number’ ‘When the above code is executed, it produces the following result: 10 equals 2 * 5 62 Opeseratsrcne Python 21 is a prime nunber 12 equals 2 * 6 13 is a prime number 14 equals 2* 7 15 equals 3 * 5 46 equals 2* 8 17 is a prime nunber 18 equals 2* 9 19 is a prime nunber Nested Loops Python programming language allows to use one loop inside another loop. 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. For example a for loop can be inside a while loop or vice versa. Opeseratsrcne 63 Python Example The following program uses a nested for loop to find the prime numbers from 2 to ion: #1 /usr/bin/python while(i < 108): j-2 while(j <= (4/3): if not(i%j): break jeje if (J > 4/4) + print i, * is prime isiea print "Good bye!" When the above code is executed, it produces following result: 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 Opereniatensrs or Python 37 an 43 a7 53 59 61 67 7 3 79 83 89 97 is is is is is is is is is is is prime prime prime prime prime prime prime prime prime prime prime prime prime prime Good bye! Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. Control Statement break statement Description Terminates the loop statement and transfers execution to the statement immediately following the loop. Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 65 Opereniatensrs Python ass statement The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. Let us go through the loop control statements briefly: Break Statement It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block. ‘Syntax ‘The syntax for a break statement in Python is as follows: break Flow Diagram I condition fs true Hf condition Is false 66 Python Example #1 /usr/bin/ python for letter in ‘python’ # First Example if letter == ‘h': break print ‘Current Letter :', letter var = 10 # Second Example while var > print ‘Current variable value :', var var var -1 if var == 5: break print “Good bye!" 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 Current variable value : 7 Current variable value : 6 Good bye! 67 Opereniatensrs Python Continue Statement It returns the control to the beginning of the while loop. 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. Syntax continue Flow Diagram pon If condition is tru oer I condition Is false Example #1 /usr/bin/ python for letter in ‘Python’ # First Example if letter continue print ‘Current Letter :*, letter 68 Opeseratsrcne Python var = 10 # Second Exanple while var > @: var = var -1 if var 5: continue print ‘Current variable value :', 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 : 0 Current Letter : n Current variable value : 9 Current variable value : & Current variable value : 7 Current variable value : 6 Current variable value Current variable value : 3 Current variable value : 2 Current variable value : 1 Current variable value : 0 Good bye! Pass Statement It is used when a statement is required syntactically but you do not want any command or code to execute. Opereniatensrs 69 Python The pass statement is a null operation; nothing happens when it executes. The passis also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): Syntax pass Example #!/usr/bin/ python for letter in ‘python’: if letter pass print ‘This is pass block’ print ‘Current Letter :*, letter print “Good bye ‘When the above code is executed, it produces following result: Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : 0 Current Letter : n Good bye! 70 8. NUMBERS Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object. Number objects are created when you assign a value to them. For example: var = 1 var2 18 You can also delete the reference to a number object by using the del statement. The syntax of the del statement is: del var4[,var2[,var3[....,varN]]]] You can delete a single object or multiple objects by using the del statement. For example: del var del var_a, var_b Python supports four different numerical types: + int (signed integers): They are often called just integers or ints, are positive or negative whole numbers with no decimal point. + long (long integers): Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L. + float (floatina naint real values) : Also called floats. thev renresent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10? = 250). complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming, 71 Opeseratsrcne Python Examples Here are some examples of numbers: int Long float complex 10 51924361L 0.0 3.14j 100 -0x19323L 15.20 45) -786 0122L a3 9.322e-36j 080 OxDEFABCECBDAECBFBAEL 32.3+e18 876) -0490 5356336298431 -90. -.6545+0) -0x260 -052318172735L -32.54e100 3e+26) 0x69 ~4721885298529L 70.2-E12 4.53e-7j Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L. ‘A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the compres univer. Number Type Conversion Python converts numbers internally in an expression containing mixed types to a ‘common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter. + Type int(x) to convert x to a plain integer. + Type long(x) to convert x to a long integer. ‘+ Type float(x) to convert x to a floating-point number. + Type complex(x) to convert x to a complex number with real part x and imaginary part zero. Opeseratsrcne 72 Python + Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions Mathematical Functions Python includes following functions that perform mathematical calculations. Function Returns ( description ) abst The absolute value of x: the (positive) distance between x and zero. The ceiling of x: the smallest integer not less than x -Lifxy The exponential of x: e* The absolute value of x. The floor of x: the largest integer not greater than x The natural logarithm of x, for x> 0 The base-10 logarithm of x for x> 0. The largest of its arguments: the value closest to positive infinity The smallest of its arguments: the value closest to negative infinity The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float. The value of x**y. 73 Opereniatensrs Python found(x Ln) x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(- 0.5) is -1.0. Sart) ‘The square root of x for x > 0 Random Number Functions Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used. Function shoice(sea) Description ‘A random item from a list, tuple, or string fandrange ([starL|stop step) A randomly selected element from range(start, stop, random) step) Arandom float r, such that 0 is less than or equal to rand ris less than 1 seed) Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. shuffie(Ist)_ Randomizes the items of a list in place. Returns None. uuniform(x. v) Arandom float r, such that x is less than or equal to r and ris less than y Trigonometric Functions Python includes following functions that perform trigonometric calculations. Function Description acos(x) Return the arc cosine of x, in radians. 74 Opereniatensrs sintx) tanix rees(x Python Return the arc sine of x, in radians. Return the arc tangent of x, in radians. Return atan(y / x), in radians. Return the cosine of x radians. Return the Euclidean norm, sqrt(x*x + y*y). Return the sine of x radians. Return the tangent of x radians. Converts angle x from radians to degrees. Converts angle x from degrees to radians. Mathematical Constants The module also defines two mathematical constants: Constants Description pi ‘The mathematical constant pi. e ‘The mathematical constant e. 75 point 9. STRINGS Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to 2 variable. For example: vart "Hello World!" var2 ‘python Programming” Accessing Values in Strings Python does not support a character type; these are treated as strings of length one, thus also considered a substring, To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example: #1/usr/bin/ python var1 = ‘Hello World!" var2 "python Programming” print “vari[a]: “, var1[@] print “var2[1:5]: ", var2[1:5] When the above code is executed, it produces the following result: vari{o]: var2[1:5]: ytho You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example: Opereniatensrs 76 Python #1/usr/bin/ python vari = ‘Hello World!" print "Updated String :- ", var[:6] + ‘Python’ When the above code is executed, it produces the following result: Updated String :- Hello Python Escape Characters Following table is a list of escape or non-printable characters that can be represented with backslash notation. ‘An escape character gets interpreted; in a single quoted as well as double quoted strings. Backslash notation \a \b \ox \cx \e \f \M-\C-x \n \nan Ng \s \t Ww Hexadecimal Description character 0x07 Bell or alert oxos Backspace Control-x Control-x Oxib Escape Ox0c Formfeed Meta-Control-x Ox0a Newline Octal notation, where n is in the range 0.7 7 Python Oxod Carriage return 0x20 Space ox09 Tab oxob Vertical tab \x Character x \xnn Hexadecimal notation, where n is in the range 0.9, af, or AF String Special Operators Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then: Operator Description Example + Concatenation - Adds values on either sideof a + b will give the operator HelloPython * Repetition - Creates new strings, a*2 will give -HelloHello concatenating multiple copies of the same string a Slice - Gives the character from the given a[1] will givee index C2] Range Slice - Gives the characters from the [1:4] will give ell given range in Membership - Returns true if a character H in a will give 1 exists in the given string not in Membership - Returns true if a character M not in awill give 1 does not exist in the given string 78 Opeseratsrcne Python oR Raw String - Suppresses actual meaning of print r'\n' prints \n Escape characters. The syntax for raw strings and print R'\n’prints \n is exactly the same as for normal strings with the exception of the raw string operator, the letter “r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. Format - Performs String formatting See at next section String Formatting Operator ‘One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example: #1/usr/bin/ python print "My name is Xs and weight is %d kg!" % (‘Zara', 21) When the above code is executed, 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 %e character %s string conversion via str() prior to formatting %i signed decimal integer %d signed decimal integer %u unsigned decimal integer 79 Opereniatensrs %0 Python octal integer %X %e %E %f %g %G hexadecimal integer (lowercase letters) hexadecimal integer (UPPERcase letters) exponential notation (with lowercase 'e’) ‘exponential notation (with UPPERcase 'E') floating point real number the shorter of %f and %e the shorter of %f and %E Other supported symbols and functionality are listed in the following table: Symbol (var) Functionality argument specifies width or precision left justification display the sign leave a blank space before a positive number add the octal leading zero ( '0' ) or hexadecimal leading 'Ox' or ‘OX’, depending on whether 'x' or 'X' were used. pad from left with zeros (instead of spaces) "%%' leaves you with a single literal '%' mapping variable (dictionary arguments) 80 Opereniatensrs Python mn m is the minimum total width and n is the number of digits to display after the decimal point (if appl.) Triple Quotes Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes. #1 /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. NEWLINEs within the string, whether explicitly given like ‘this within the brackets [ \n ], or just a NEWLINE within ‘the variable assignment will also show up. print para_str; When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n); this is @ 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. NENLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within 81 Opeseratsrcne Python the variable assignment will also show up. Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote It: #1 /usr/bin/ python print 'C:\\nowhere* When the above code is executed, it produces the following result: C:\nowhere Now let's make use of raw string. 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: C:\\nowhere Unicode String Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following: #!/usr/bin/ python print u'Hello, world!’ When the above code is executed, it produces the following result Hello, world! As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r. 82 Muroriaispoine

You might also like