P.VIJAYABABU

[email protected]

2017

Python Programming Language

BY

P.VIJAYABABU PH NO: 9985333934 EMAIL: [email protected] Python Programming Language

UNIT -1

History of Python: The name Python was selected from "Monty Python’s Flying Circus" which was a British sketch comedy series created by the comedy group Monty Python and Broad cast by the BBC from 1969 to 1974. Python was created in the early 1990s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in Netherlands. Python was created as a successor of a language called ABC (All Basic Code) and released publicly in1991. Guido remains Python’s principal author, although it includes many contributions from active user community. Between 1991 and 2001 there are several versions released, current stable release is 3.2. In 2001 the Python Software Foundation (PSF) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Corporation is a sponsoring member of the PSF.All most all Python releases are Open Source. What is Python: Python is an open source, object-oriented, high-level powerful programming Language. Developed by Guido van Rossum in the early 1990s. Named after Monty Python Python runs on many UNIX variants, on the Mac, and on Windows 2000 and Later.

Available for download from http://www.python.org. Python programs are composed of modules Modules contain statements Statements contain expressions Expressions create and process objects which means it can be used to build Features of Python: Open source : Python is publicly available open source software, any one can use source code that doesn't’t cost anything. Easy-to-learn : Popular (scripting/extension) language, clear and easy syntax, no type declarations, automatic memory management, high-level data types and operations, design to read (more English like syntax) and write (shorter code compared to C, C++,and Java) fast. High-level Language: High-level language (closer to human) refers to the higher level of Concept from machine language (for example assembly languages). Python is an example of a high-level language like C, C++, Perl, and Java with low-level optimization. Portable: High level languages are portable, which means they are able to run across all major hardware and software platforms with few or no change in

VIJAY Page 2 Python Programming Language source code. Python is portable and can be used on Linux, Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400 and many more. Object-Oriented : Python is a full-featured object-oriented programming language, with features such as classes, inheritance, objects, and overloading. Python is Interactive :Python has an interactive console where you get a Python prompt (command line) and interact with the interpreter directly to write and test your programs. This is useful for mathematical programming. Interpreted : Python programs are interpreted, takes source code as input, and then compiles (to portable byte-code) each statement and executes it immediately. No need to compiling or linking Extendable : Python is often referred to as a “glue” language, meaning that it is capable to work in mixed-language environment. The Python interpreter is easily extended and can add a new built-in function or modules written in C/C++/Java code. Libraries : Databases, web services, networking, numerical packages, graphical user interfaces, 3D graphics, others. Supports :Support from online Python community.

Need of Python programming: Python is a general-purpose language, which means it can be used to build just about anything, which will be made easy with the right tools/libraries. Professionally, Python is great for backend web development, data analysis, artificial intelligence, and scientific computing. Many developers have also used Python to build productivity tools, games, and desktop apps, so there are plenty of resources to help you learn how to do those as well . Major uses of Python: System utilities (system admin tools, command line programs). Web Development. Graphical User Interfaces (Tkinter, gtk, Qt). Internet scripting. Embedded scripting. Database access and programming. Game programming. Rapid prototyping and development. Distributed programming Applications of Python: Web Development: Yahoo Maps, Yahoo Groups, Google, Zope Corporation, Ultra seek, Linux Weekly News, Elastic Hosts Cloud Servers, Mojam.com, hunch, Shopzilla, Movieplayer.it, and Multiplayer. It.

Games: Battlefield 2, Crystal Space, Star Trek Bridge Commander, The Temple of Elemental Evil, Vampire: The Masquerade: Bloodlines, Civilization 4, QuArK (Quake Army Knife)

VIJAY Page 3 Python Programming Language

Graphics: Industrial Light & Magic, Walt Disney Feature Animation, HKS, Inc. (ABAQUS/CAE), RoboFog, Caligari Corporation, Blender 3D, Jasc Software, Paint Shop Pro. Financial: Altos Investment Management, ABN AMRO Bank, Treasury Systems, Belloc Credit Union, Journyx Timesheet and Resource Management Software.

Science: National Weather Service, Radar Remote Sensing Group, Applied Maths, Biosoft, The National Research Council of Canada, Los Alamos National Laboratory (LANL) Theoretical Physics Division, AlphaGene, Inc., LLNL, NASA, Swedish Meteorological and Hydrological Institute (SMHI), Environmental Systems Research Institute (ESRI), Objexx Engineering, Nmag Computational Micromagnetics Electronic Design Automation : Ciranova, Productivity Design Tools, Object Domain, Pardus, Red Hat, SGI, Inc., MCI Worldcom, Nokia,

Education : University of California, Irvine, Smeal College of Business, The Pennsylvania State University, New Zealand Digital Library, IT Certification Exam preparation, SchoolTool,

Business Software : Raven Bear Systems Corporation, Thawte Consulting, Advanced Management Solutions Inc., IBM, Arakn, RealNetworks, dSPACE, Escom, TheTiny Company, Nexedi, Piensa Technologies - Bufete Consultor de Mexico, Nektra, WuBook.

Role of Interpreter of Python: The word "interpreter" can be used in a variety of different ways when discussing Python. Sometimes interpreter refers to the Python REPL (Read– Eval–Print Loop), the interactive prompt you get by typing python at the command line. Sometimes people use "the Python interpreter" more or less interchangeably with "Python" to talk about executing Python code from start to finish. There are four steps that python takes when you hit return: lexing, parsing, compiling, and interpreting. Lexing is breaking the line of code you just typed into tokens. The parser takes those tokens and generates a structure that shows their relationship to each other (in this case, an Abstract Syntax Tree). The compiler then takes the AST and turns it into one (or more) code objects. Finally, the interpreter takes each code object executes the code it represents.

Basics of Python Programming Using the REPL(Shell): A Read-Eval-Print Loop (REPL) is a simple, interactive computer programming environment. The term 'REPL' is usually used to refer to a LISP interactive environment but can be applied to command line shells and similar environments for programming languages like Python, Ruby etc.

VIJAY Page 4 Python Programming Language

Python IDLE: Interactive Mode Let us assume that we've already installed Python (here we installed Python 3.2 on a standard pc with windows 7 OS). Click on start button and find Python 3.2 tab in installed programs. Now clicking on Python 3.2 tab you can see the Python program development tool named IDLE (Python GUI). To start IDLE click on IDLE (Python GUI) icon, you will see a new window opens up and the cursor is waiting beside '>>>' sign which is called command prompt. This mode is called interactive mode as you can interact with IDLE directly, you type something (single unit in a programming language) and press enter key Python will execute it, but you cannot execute your entire program here. At the command prompt type copyright and press enter key Python executes the copyright information. Now Python is ready to read new command. Let's execute the following commands one by one.

Command -1 : print("Hello World")

Command -2 : primt("Hello World")

The first command is correct and but the second one has a syntax error, here is the response from Python.

Python line structure: A Python program is divided into a number of logical lines and every logical line is terminated by the token NEWLINE. A logical line is created from one or more physical lines. A line contains only spaces, tabs, formfeeds possibly a comment, is known as a blank line, and Python interpreter ignores it. A physical line is a sequence of characters terminated by an end-of-line sequence (in windows it is called CR LF or return followed by a linefeed and in Unix, it is called LF or linefeed). See the following example.

Comments in Python: A comment begins with a hash character(#) which is not a part of the string literal and ends at the end of the physical line. All characters after the # character up to the end of the line are part of the comment and the Python interpreter ignores them. See the following example. It should be noted that Python has no multi- lines or block comments facility.

Joining two lines: When you want to write a long code in a single line you can break the logical line in two or more physical lines using backslash character(\). Therefore when a physical line ends with a backslash characters(\) and not a part of a string literal or comment then it can join another physical line. See the following example.

VIJAY Page 5 Python Programming Language

Multiple statements on a single line: You can write two separate statements into a single line using a semicolon (;) character between two line.

Running Python Scripts

Python IDLE: Development mode At first, start with a new window. Clicking on "New window" under file menu a new window will come. Type print "Hello World" in the new window.

Let's save (Save command is located under the File menu) the file now. We save the Program as helloworld.py under E:/python-programs folder. To run the program select Run menu. Python Variables: A variable is a memory location where a programmer can store a value. Example : roll_no, amount, name etc. Value is either string, numeric etc. Example : "Sara", 120, 25.36 Variables are created when first assigned. Variables must be assigned before being referenced. The value stored in a variable can be accessed or updated later. No declaration required The type (string, int, float etc.) of the variable is determined by Python The interpreter allocates memory on the basis of the data type of a variable. Variable name rules: Must begin with a letter (a - z, A - B) or underscore (_) Other characters can be letters, numbers or _ Case Sensitive Can be any (reasonable) length There are some reserved words which you cannot use as a variable name Because Python uses them for other things.

Python Assignment statements: The assignment statement creates new variables and gives them values. Basic Assignment statement in Python is : Syntax = Where the equal sign (=) is used to assign value (right side) to a variable name (left side). See the following statements : view plaincopy to clipboardprint? 1. >>> Item_name = "Computer" #A String 2. >>> Item_qty = 10 #An Integer 3. >>> Item_value = 1000.23 #A floating point

VIJAY Page 6 Python Programming Language

4. >>> print(Item_name) 5. Computer 6. >>> print(Item_qty) 7. 10 8. >>> print(Item_value) 9. 1000.23 10. >>> One thing is important, assignment statement read right to left only. Example : a = 12 is correct, but 12 = a does not make sense to Python, which creates a syntax error. Check it in Python Shell. view plaincopy to clipboardprint? 1. >>> a = 12 2. >>> 12 = a 3. SyntaxError: can't assign to literal 4. >>>

Multiple Assignment: The basic assignment statement works for a single variable and a single expression. You can also assign a single value to more than one variables simultaneously. Syntax var1=var2=var3...varn= = Example : x = y = z = 1 Now check the individual value in Python Shell. view plaincopy to clipboardprint? 1. >>> x = y = z = 1 2. >>> print(x) 3. 1 4. >>> print(y) 5. 1 6. >>> print(z) 7. 1 8. >>> Here is an another assignment statement where the variables assign many values at the same time. Syntax , , ..., = , , ..., Example : x, y, z = 1, 2, "abcd" In the above example x, y and z simultaneously get the new values 1, 2 and "abcd". view plaincopy to clipboardprint? VIJAY Page 7 Python Programming Language

1. >>> x,y,z = 1,2,"abcd" 2. >>> print(x) 3. 1 4. >>> print(y) 5. 2 6. >>> print(z) 7. abcd You can reuse variable names by simply assigning a new value to them : view plaincopy to clipboardprint? 1. >>> x = 100 2. >>> print(x) 3. 100 4. >>> x = "Python" 5. >>> print(x) 6. Python 7. >>> Swap variables: Python swap values in a single line and this applies to all objects in python. Syntax var1, var2 = var2, var1 Python Programming Language Unit-1 13 Example : view plaincopy to clipboardprint? 1. >>> x = 10 2. >>> y = 20 3. >>> print(x) 4. 10 5. >>> print(y) 6. 20 7. >>> x, y = y, x 8. >>> print(x) 9. 20 10. >>> print(y) 11. 10 12. >>> Local and global variables in python: In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global. Example :

1. var1 = "Python" 2. def func1(): 3. var1 = "PHP" 4. print("In side func1() var1 = ",var1) 5. VIJAY Page 8 Python Programming Language

6. def func2(): 7. print("In side func2() var1 = ",var1) 8. func1() 9. func2() Output : In side func1() var1 = PHP In side func2() var1 = Python You can use a global variable in other functions by declaring it as global keyword : Example : 1. def func1(): 2. global var1 3. var1 = "PHP" 4. print("In side func1() var1 = ",var1) 5. 6. def func2(): 7. print("In side func2() var1 = ",var1) 8. func1() 9. func2() Output : In side func1() var1 = PHP In side func2() var1 = PHP

Python Reserved words/ Key words: The following identifiers are used as reserved words of the language, and cannot be used as ordinary identifiers.

False None True And As class continue def del el if finally for from global or is lambda nonlocal not yield return try while with Assert

else import pass Break except

in raise

Input and Output functions: Python provides numerous built-in functions that are readily available to us at the python prompt. Some of the functions like input() and print() are widely used for standard input and output operations respectively. Let us see the output section first. Python Output Using print() function

VIJAY Page 9 Python Programming Language

We use the print() function to output data to the standard output device (screen). print('This sentence is output to the screen') # Output: This sentence is output to the screen a = 5 print('The value of a is', a) # Output: The value of a is 5 In the second print() statement, we can notice that a space was added between the string and the value of variable a.This is by default, but we can change it. The actual syntax of the print() function is print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout(screen). Here is an example to illustrate this. print(1,2,3,4) # Output: 1 2 3 4 print(1,2,3,4,sep='*') # Output: 1*2*3*4 print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4&

Output formatting: Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object. > x = 5; y = 10 > print('The value of x is {} and y is {}'.format(x,y)) The value of x is 5 and y is 10 Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index) print('I love {0} and {1}'.format('bread','butter')) # Output: I love bread and butter print('I love {1} and {0}'.format('bread','butter')) # Output: I love butter and bread We can even use keyword arguments to format the string. > print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name ='John')) Hello John, Goodmorning We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this. > x = 12.3456789

VIJAY Page 10 Python Programming Language

> print('The value of x is %3.2f' %x) The value of x is 12.35 > print('The value of x is %3.4f' %x) The value of x is 12.3457

Python Input:

Up till now, our programs were static. The value of variables were defined or hard coded into the source code. To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is input([prompt]) where prompt is the string we wish to display on the screen. It is optional. > num = input('Enter a number: ') Enter a number: 10 > num '10' Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions. > int('10') 10 > float('10') 10.0 This same operation can be performed using the eval() function. But it takes it further. It can evaluate even expressions, provided the input is a string > int('2+3') Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in ValueError: invalid literal for int() with base 10: '2+3' > eval('2+3') 5

Indentation: Python uses whitespace (spaces and tabs) to define program blocks whereas other languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block must be the indented same amount. In the following program, the block statements have no indentation.

VIJAY Page 11 Python Programming Language

Here is an program with an indentation of a single space + a single tab.

VIJAY Page 12 Python Programming Language

UNIT -2 Data types: Numbers: Numbers are created by numeric literals. Numeric objects are immutable, which means when an object is created its value cannot be changed. Python has three distinct numeric types: integers, floating point numbers, and complex numbers. Integers represent negative and positive integers without fractional parts whereas floating point numbers represents negative and positive numbers with fractional parts. In addition, Booleans are a subtype of plain integers.

See the following statements in Python shell.

Mathematically, a complex number (generally used in engineering) is a number of the form A+Bi where i is the imaginary number. Complex numbers have a real and imaginary part. Python supports complex numbers either by

VIJAY Page 13 Python Programming Language specifying the number in (real + imagJ) or (real + imagj) form or using a built-in method complex(x, y). See the following statements in Python Shell.

Boolean (bool): The simplest build-in type in Python is the bool type, it represents the truth values False and True. See the following statements in Python shell.

Strings: In Python, a string type object is a sequence (left-to- right order) of characters. Strings start and end with single or double quotes Python strings are immutable. Single and double quoted strings are same and you can use a single quote with in a string when it is surrounded by double quote and vice versa. Declaring a string is simple, see the following statements.

VIJAY Page 14 Python Programming Language

Special characters in strings: The backslash (\) character is used to introduce a special character. See the following table. Escape sequence Meaning \n Newline \t Horizontal Tab \\ Backslash \' Single Quote \" Double Quote See the following statements on special characters.

VIJAY Page 15 Python Programming Language

What is an operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called operator. Python language supports the following types of operators. Arithmetic Operators Comparison (i.e., Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators Let's 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 a + b will give 30 side of the operator

- Subtraction - Subtracts right hand a - b will give -10 operand from left hand operand * either side of the operator a * b will give 200

/ Division - Divides left hand operand by b / a will give 2 right hand operand ** Exponent - Performs exponential a**b will give 10 to the (power) calculation on operators power 20 % Modulus - Divides left hand operand by b % a will give 0 right hand operand and returns remainder // Floor Division - The division of 9//2 is equal to 4 and operands where the result is the 9.0//2.0 is quotient in which the digits after equal to 4.0 the decimal point are removed. VIJAY Page 16 Python Programming Language

VIJAY Page 17 Python Programming Language

Python Bitwise Operators: Bitwise operator works on bits and perform 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

VIJAY Page 18 Python Programming Language

There are following Bitwise operators supported by Python language Binary AND Operator copies a bit a & b) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if (a | b) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the (a ^ b) will give 49 which is 0011 bit if it is set in one operand but 0001 not both. ~ Binary Ones Complement (~a ) will give -61 which is 1100 0011 Operator is unary and has the in 2's complement form due to a efect of 'flipping' bits. signed binary number << Binary Left Shift Operator. The a << 2 will give 240 which is 1111 left 0000 operands value is moved left by the number of bits specified by the right operand >> Binary Right Shift Operator. The a >> 2 will give 15 which is 0000 left operands value is moved right 1111 by the number of bits specified by the right operand.

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 Called Logical AND operator. If (a and b) is true both the operands are true then then condition becomes true. OR Called Logical OR Operator. If (a or b) is true any of the two operands are non zero then then condition becomes true. NOT Called Logical NOT Operator. not(a and b) is false. Use to Reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

VIJAY Page 19 Python Programming Language

Python Identity Operators: Identity operators compare the memory locations of two objects. There are two Identity operators explained below: Operator Description Example Evaluates to true if the variables x is y, here is results in 1 if id(x) on either side of the operator Equals id(y). IS point to the same object and false otherwise IS NOT Evaluates to false if the variables x is not y, here is not results in on either side of the operator 1 if id(x) is not equal to id(y). point to the same object and true otherwise if statement The Python if statement is same as it is with other programming languages. It Executes a set of statements conditionally, based on the value of a logical expression. Here is the general form of a one way if statement. Syntax: if expression : statement_1 statement_2 .... In the above case, expression specifies the conditions which are based on Boolean expression. When a Boolean expression is evaluated it produces either a value of true or false. If the expression evaluates true the same amount of indented statement(s) following if will be executed. This group of the statement(s) is called a block. if .. else statement In Python if .. else statement, if has two blocks, one following the expression and other following the else clause. Here is the syntax.

VIJAY Page 20 Python Programming Language

Syntax: if expression : statement_1 statement_2 .... else : statement_3 statement_4 .... In the above case if the expression evaluates to true the same amount of indented statements(s) following if will be executed and if the expression evaluates to false the same amount of indented statements(s) following else will be executed. See the following example. The program will print the second print statement as the value of a is 10. 1. a=10 2. if(a>10): 3. print("Value of a is greater than 10") 4. else : 5. print("Value of a is 10") Output : Value of a is 10 FLOW CHART:

if .. elif .. else statement Sometimes a situation arises when there are several conditions. To handle the situation Python allows adding any number of elif clause after an if and before an else clause. Here is the syntax.

VIJAY Page 21 Python Programming Language

Syntax: if expression1 : statement_1 statement_2 .... elif expression2 : statement_3 statement_4 .... elif expression3 : statement_5 statement_6 ...... else : statement_7 statement_8 In the above case Python evaluates each expression (i.e. the condition) one by one and if a true condition is found the statement(s) block under that expression will be executed. If no true condition is found the statement(s) block under else will be executed. In the following example, we have applied if, series of elif and else to get the type of a variable. 1. var1 = 1+2j 2. if (type(var1) == int): 3. print("Type of the variable is Integer") 4. elif (type(var1) == float): 5. print("Type of the variable is Float") 6. elif (type(var1) == complex): 7. print("Type of the variable is Complex") 8. elif (type(var1) == bool): 9. print("Type of the variable is Bool") 10. elif (type(var1) == str): 11. print("Type of the variable is String") 12. elif (type(var1) == tuple): 13. print("Type of the variable is Tuple") 14. elif (type(var1) == dict): 15. print("Type of the variable is Dictionaries") 16. elif (type(var1) == list): 17. print("Type of the variable is List") 18. else: 19. print("Type of the variable is Unknown") Output : Type of the variable is Complex

VIJAY Page 22 Python Programming Language

Nested if .. else statement In general nested if-else statement is used when we want to check more than one condition. Conditions are executed from top to bottom and check each condition whether it evaluates to true or not. If a true condition is found the statement(s) block associated with the condition executes otherwise it goes to next condition. Here is the syntax : Syntax: if expression1 : if expression2 : statement_3 statement_4 .... else : statement_5 statement_6 .... else : statement_7 statement_8 In the above syntax expression1 is checked first, if it evaluates to true then the program control goes to next if - else part otherwise it goes to the last else statement and executes statement_7, statement_8 etc.. Within the if - else if expression2 evaluates true then statement_3, statement_4 will execute otherwise statement_5, statement_6 will execute. See the following example. 1. age = 38 2. if (age >= 11): 3. print ("You are eligible to see the Football match.") 4. if (age <= 20 or age >= 60): 5. print("Ticket price is $12") 6. else: 7. print("Tic kit price is $20") 8. else: 9. print ("You're not eligible to buy a ticket.") Output : You are eligible to see the Football match. Tic kit price is $20 In the above example age is set to 38, therefore the first expression (age >= 11) Evaluates to True and the associated print statement prints the string "You are eligible to see the Football match". There after program control goes to next if statement and the condition ( 38 is outside <=20 or >=60) is matched and prints "Tic kit price is $12".

VIJAY Page 23 Python Programming Language

FLOW CHART:

Use the and operator in an if statement 1. #create two boolean objects 2. 3. x = False 4. y = True 5. 6. #The validation will be True only if all the expressions generate a value True 7. if x and y: 8. print('Both x and y are True') 9. else: 10. print('x is False or y is False or both x and y are False') Output : x is False or y is False or both x and y are False Use the in operator in an if statement 1. #create a string 2. s = 'jQuery' 3. #create a list 4. l = ['JavaScript', 'jQuery', 'ZinoUI'] 5. 6. # in operator is used to replace various expressions that use the or operator 7. if s in l: 8. print(s + ' Tutorial') 9. VIJAY Page 24 Python Programming Language

10. #Alternate if statement with or operator 11. 12. if s == 'JavaScript' or s == 'jQuery' or s == 'ZinoUI': 13. print(s + ' Tutorial') Output : jQuery Tutorial jQuery Tutorial

Write an if-else in a single line of code 1. #create a integer 2. n = 150 3. print(n) 4. 5. #if n is greater than 500, n is multiplied by 7, otherwise n is divided by 7 6. result = n * 7 if n > 500 else n / 7 7. print(result) Output : 150 21.428571428571427 Define a negative if If a condition is true the not operator is used to reverse the logical state, then logical not operator will make it false. 1. #create a integer 2. x = 20 3. print(x) 4. 5. #uses the not operator to reverse the result of the logical expression 6. 7. if not x == 50: 8. print('the value of x different from 50') 9. else: 10. print('the value of x is equal to 50') Output : 20 the value of x different from 50 for loop Like most other languages, Python has for loops, but it differs a bit from other like C or Pascal. In Python for loop is used to iterate over the items of any sequence including the Python list, string, tuple etc. The for loop is also used to access elements from a container (for example list, string, tuple) using built-in function range().

Syntax for variable_name in sequence : statement_1 statement ……

VIJAY Page 25 Python Programming Language

Example: Python for loop 1. >>> #The list has four elements, indices start at 0 and end at 3 2. >>> color_list = ["Red", "Blue", "Green", "Black"] 3. >>> for c in color_list: 4. print(c) 5. 6. Red 7. Blue 8. Green 9. Black 10. >>> In the above example color_list is a sequence contains a list of various color names.When the for loop executed the first item (i.e. Red) is assigned to the variable c. After this, the print statement will execute and the process will continue until we rich the end of the list.

Python for loop and range() function The range() function returns a list of consecutive integers. The function has one, two or three parameters where last two parameters are optional. It is widely used in for loops. Here is the syntax. range(a) range(a,b) range(a,b,c) range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1. Syntax for in range(): Example : 1. >>> for a in range(4): 2. print(a) 3. 4. 0 5. 1 6. 2 7. 3 8. >>> range(a,b) : Generates a sequence of numbers from a to b excluding b, incrementing by 1. Syntax for "variable" in range("start_number", "end_number"): Example : 1. >>> for a in range(2,7): 2. print(a) 3. 4. 2

VIJAY Page 26 Python Programming Language

5. 3 6. 4 7. 5 8. 6 9. >>> range(a,b,c) : Generates a sequence of numbers from a to b excluding b, incrementing by c. Example : 1. >>> for a in range(2,19,5): 2. print(a) 3. 4. 2 5. 7 6. 12 7. 17 8. >>> Python for loop : Iterating over tuple, list, dictionary Example : Iterating over tuple The following example counts the number of even and odd numbers from a series of numbers. 1. numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple 2. count_odd = 0 3. count_even = 0 4. for x in numbers: 5. if x % 2: 6. count_odd+=1 7. else: 8. count_even+=1 9. print("Number of even numbers :",count_even) 10. print("Number of odd numbers :",count_odd) Output : Number of even numbers : 4 Number of odd numbers : 5 In the above example a tuple named numbers is declared which holds the integers 1 to 9. The best way to check if a given number is even or odd is to use the modulus operator (%). The operator returns the remainder when dividing two numbers. Modulus of 8 % 2 returns 0 as 8 is divided by 2, therefore 8 is even and modulus of 5 % 2 returns 1 therefore 5 is odd. The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item in the tuple and the process will continue until we rich the end of the tuple. When it is true count_even increase by one otherwise count_odd is increased by one. Finally, we print the number of even and odd numbers through print statements. Example : Iterating over list

VIJAY Page 27 Python Programming Language

In the following example for loop iterates through the list "datalist" and prints each item and its corresponding Python type. 1. datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], 2. {"class":'V', "section":'A'}] 3. for item in datalist: 4. print ("Type of ",item, " is ", type(item)) Output : Type of 1452 is Type of 11.23 is Type of (1+2j) is Type of True is Type of w3resource is Type of (0, -1) is Type of [5, 12] is Type of {'section': 'A', 'class': 'V'} is Example : Iterating over dictionary In the following example for loop iterates through the dictionary "color" through its keys and prints each key. 1. >>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"} 2. >>> for key in color: 3. print(key) 4. 5. c2 6. c1 7. c3 8. >>>

1. >>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"} 2. >>> for value in color.values(): 3. print(value) 4. 5. Green 6. Red 7. Orange 8. >>> You can attach an optional else clause with for statement, in this case, syntax will be - for variable_name in sequence : statement_1 statement_2 .... else : statement_3 statement_4 .... VIJAY Page 28 Python Programming Language

The else clause is only executed after completing the for loop. If a break statement executes in first program block and terminates the loop then the else clause does not execute.

While loop Loops are used to repeatedly execute a block of program statements. The basic loop structure in Python is while loop. Here is the syntax. Syntax : while (expression) : statement_1 statement_2 .... The while loop runs as long as the expression (condition) evaluates to True and execute the program block. The condition is checked every time at the beginning of the loop and the first time when the expression evaluates to False, the loop stops without executing any remaining statement(s). The following example prints the digits 0 to 4 as we set the condition x < 5. 1. x = 0; 2. while (x < 5): 3. print(x) 4. x += 1 Output : 0 1 2 3 4

One thing we should remember that a while loop tests its condition before the body of the loop (block of program statements) is executed. If the initial test returns false, the body is not executed at all. For example the following code never prints out anything since before executing the condition evaluates to false. 1. x = 10; 2. while (x < 5): 3. print(x) 4. x += 1

VIJAY Page 29 Python Programming Language

FLOW CHART :

The following while loop is an infinite loop, using True as the condition: 1. x = 10; 2. while (True): 3. print(x) 4. x += 1

Flowchart :

Python: while and else statement There is a structural similarity between while and else statement. Both have a block of statement(s) which is only executed when the condition is true. The difference is that block belongs to if statement executes once whereas block belongs to while statement executes repeatedly. You can attach an optional else clause with while statement, in this case, syntax will be -

VIJAY Page 30 Python Programming Language while (expression) : statement_1 statement_2 ...... else : statement_3 statement_4 ...... The while loop repeatedly tests the expression (condition) and, if it is true, executes the first block of program statements. The else clause is only executed when the condition is false it may be the first time it is tested and will not execute if the loop breaks, or if an exception is raised. If a break statement executes in first program block and terminates the loop then the else clause does not execute. In the following example, while loop calculates the sum of the integers from 0 to 9 and after completing the loop, else statement executes. 1. x = 0; 2. s = 0 3. while (x < 10): 4. s = s + x 5. x = x + 1 6. else : 7. print('The sum of first 9 integers : ',s) Output : The sum of first 9 integers : 45 FLOW CHART:

Example: while loop with if-else and break statement 1. x = 1; 2. s = 0 3. while (x < 10): 4. s = s + x 5. x = x + 1 6. if (x == 5): 7. break 8. else : 9. print('The sum of first 9 integers : ',s) 10. print('The sum of ',x,' numbers is :',s) Output :

VIJAY Page 31 Python Programming Language

The sum of 5 numbers is : 10 In the above example the loop is terminated when x becomes 5. Here we use break statement to terminate the while loop without completing it, therefore program control goes to outside the while - else structure and execute the next print statement

FLOW CHART:

break statement: The break statement is used to exit a for or a while loop. The purpose of this statement is to end the execution of the loop (for or while) immediately and the program control goes to the statement after the last statement of the loop. If there is an optional else statement in while or for loop it skips the optional clause also. Here is the syntax. Syntax while (expression1) : statement_1 statement_2 ...... if expression2 : break for variable_name in sequence : statement_1 statement_2 if expression3 : break

VIJAY Page 32 Python Programming Language

Example : break in for loop In the following example for loop breaks when the count value is 5. The print statement after the for loop displays the sum of first 5 elements of the tuple numbers. 1. numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple 2. num_sum = 0 3. count = 0 4. for x in numbers: 5. num_sum = num_sum + x 6. count = count + 1 7. if count == 5: 8. break 9. print("Sum of first ",count,"integers is : ", num_sum) Output: Sum of first 5 integers is : 15 Example : break in while loop In the following example while loop breaks when the count value is 5. The print statement after the while loop displays the value of num_sum (i.e. 0+1+2+3+4). 1. num_sum = 0 2. count = 0 3. while(count<10): 4. num_sum = num_sum + count 5. count = count + 1 6. if count== 5: 7. break 8. print("Sum of first ",count,"integers is : ", num_sum)

Output: Sum of first 5 integers is : 10 continue statement The continue statement is used in a while or for loop to take the control to the top of the loop without executing the rest statements inside the loop. Here is a simple example. 1. for x in range(6): 2. if (x == 3 or x==6): 3. continue 4. print(x) Output : 0 1 2 4 5 In the above example, the for loop prints all the numbers from 0 to 6 except 3 and 6 as the continue statement returns the control of the loop to the top Python Pass statement It is used when a statement is required syntactically but you do not want any

VIJAY Page 33 Python Programming Language command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is 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/py for letter in 'Python': if letter == 'h': 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 : o Current Letter : n Good bye!

VIJAY Page 34 Python Programming Language

UNIT -3

DATA STRUCTURES Lists A list is a container which holds comma-separated values (items or elements) between square brackets where items or elements need not all have the same type. In general, we can define a list as an object that contains multiple data items (elements). The contents of a list can be changed during program execution. The size of a list can also change during execution, as elements are added or removed from it. Note: There are much programming languages which allow us to create arrays, which are objects similar to lists. Lists serve the same purpose as arrays and have many more built-in capabilities. Traditional arrays cannot be created in Python.

Examples of lists : numbers = [10, 20, 30, 40, 50] names = ["Sara", "David", "Warner", "Sandy"] student_info = ["Sara", 1, "Chemistry"] operations on lists : Create a Python list List indices Add an item to the end of the list Insert an item at a given position Modify an element by using the index of the element Remove an item from the list Remove all items from the list Slice Elements from a List Remove the item at the given position in the list, and return it Return the index in the list of the first item whose value is x Return the number of times 'x' appear in the list Sort the items of the list in place Reverse the elements of the list in place Return a shallow copy of the list Search the Lists and find elements Lists are mutable Convert a list to a tuple in python? How to use the double colon [ : : ]? Find largest and the smallest items in a list Compare two lists in Python? Nested lists in Python How can I get the index of an element contained in the list? Using Lists as Stacks Using Lists as Queues Python List Exercises VIJAY Page 35 Python Programming Language

Create a Python list 1. >>> my_list1 = [5, 12, 13, 14] # the list contains all integer values 2. >>> print(my_list1) 3. [5, 12, 13, 14] 4. >>> my_list2 = ['red', 'blue', 'black', 'white'] # the list contains all string 5. values 6. >>> print(my_list2) 7. ['red', 'blue', 'black', 'white'] 8. >>> my_list3 = ['red', 12, 112.12] # the list contains a string, an integer and 9. a float values 10. >>> print(my_list3) 11. ['red', 12, 112.12] 12. >>> A list without any element is called an empty list. See the following statements.

1. >>> my_list=[] 2. >>> print(my_list) 3. [] 4. >>> Use + operator to create a new list that is a concatenation of two lists and use * operator to repeat a list. See the following statements. 1. >>> color_list1 = ["White", "Yellow"] 2. >>> color_list2 = ["Red", "Blue"] 3. >>> color_list3 = ["Green", "Black"] 4. >>> color_list = color_list1 + color_list2 + color_list3 5. >>> print(color_list) 6. ['White', 'Yellow', 'Red', 'Blue', 'Green', 'Black'] 7. >>> number = [1,2,3] 8. >>> print(number[0]*4) 9. 4 10. >>> print(number*4) 11. [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] 12. >>>

List indices List indices work the same way as string indices, list indices start at 0. If an index has a positive value it counts from the begriming and similarly it counts backward if the index has a negative value. As positive integers are used to index from the left end and negative integers are used to index from the right end, so every item of a list gives two alternatives indices. Let create a list called color_list with four items. color_list=["RED", "Blue", "Green", "Black"] Item RED Blue Green Black Index (from left) 0 1 2 3 Index (from right) -4 -3 -2 -1 If you give any index value which is out of range then interpreter creates an error message. VIJAY Page 36 Python Programming Language

See the following statements.

1. >>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements 2. indices start at 0 and end at 3 3. >>> color_list[0] # Return the First Element 4. 'Red' 5. >>> print(color_list[0],color_list[3]) # Print First and Last Elements 6. Red Black 7. >>> color_list[-1] # Return Last Element 8. 'Black' 9. >>> print(color_list[4]) # Creates Error as the indices is out of range 10. Traceback (most recent call last): 11. File "", line 1, in 12. IndexError: list index out of range 13. >>> Add an item to the end of the list 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.append("Yellow") 5. >>> print(color_list) 6. ['Red', 'Blue', 'Green', 'Black', 'Yellow'] 7. >>>

Insert an item at a given position 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.insert(2, "White") #Insert an item at third position 5. >>> print(color_list) 6. ['Red', 'Blue', 'White', 'Green', 'Black'] 7. >>> Modify an element by using the index of the element 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list[2]="Yellow" #Change the third color 5. >>> print(color_list) 6. ['Red', 'Blue', 'Yellow', 'Black'] 7. >>> Remove an item from the list 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.remove("Black") 5. >>> print(color_list) 6. ['Red', 'Blue', 'Green'] Remove all items from the list. 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list)

VIJAY Page 37 Python Programming Language

3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.clear() 5. >>> print(color_list) 6. [] 7. >>> List Slices Lists can be sliced like strings and other sequences. Syntax : sliced_list = List_Name[startIndex:endIndex] This refers to the items of a list starting at index startIndex and stopping just before index end Index. The default values for list are 0 (startIndex) and the end (endIndex) of the list. If you omit both indices, the slice makes a copy of the original list. See the following statements.

1. >>> color_list=["Red", "Blue", "Green", "Black"] # The list have four elements 2. indices start at 0 and end at 3 3. >>> print(color_list[0:2]) # cut first two items 4. ['Red', 'Blue'] 5. >>> print(color_list[1:2]) # cut second item 6. ['Blue'] 7. >>> print(color_list[1:-2]) # cut second item 8. ['Blue']

9. >>> print(color_list[:3]) # cut first three items 10. ['Red', 'Blue', 'Green'] 11. >>> print(color_list[:]) # Creates copy of original list 12. ['Red', 'Blue', 'Green', 'Black'] 13. >>> Remove the item at the given position in the list, and return it 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.pop(2) # Remove second item and return it 5. 'Green' 6. >>> print(color_list) 7. ['Red', 'Blue', 'Black'] 8. >>> Return the index in the list of the first item whose value is x 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.index("Red") 5. 0 6. >>> color_list.index("Black") 7. 3 8. >>> Return the number of times 'x' appear in the list. 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list)

VIJAY Page 38 Python Programming Language

3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list=["Red", "Blue", "Green", "Black", "Blue"] 5. >>> print(color_list) 6. ['Red', 'Blue', 'Green', 'Black', 'Blue'] 7. >>> color_list.count("Blue") 8. 2 9. >>> Sort the items of the list in place. 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.sort(key=None, reverse=False) 5. >>> print(color_list) 6. ['Black', 'Blue', 'Green', 'Red'] 7. >>> Reverse the elements of the list in place 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.reverse() 5. >>> print(color_list) 6. ['Black', 'Green', 'Blue', 'Red'] 7. >>> Return a shallow copy of the list. 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.copy() 5. ['Red', 'Blue', 'Green', 'Black'] 6. >>> Search the Lists and find Elements 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.index("Green") 5. 2 6. >>>

Lists are Mutable Items in the list are mutable i.e. after creating a list you can change any item in the list. See the following statements. 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list[0]) 3. Red 4. >>> color_list[0]="White" # Change the value of first item "Red" to "White" 5. >>> print(color_list) 6. ['White', 'Blue', 'Green', 'Black'] 7. >>> print(color_list[0]) 8. White

VIJAY Page 39 Python Programming Language

9. >>>

1. >>> tupl=[1, 2, 3, 4] 2. >>> print(tupl) 3. [1, 2, 3, 4] 4. >>> listx=list(tupl) 5. >>> print(listx) 6. [1, 2, 3, 4] 7. >>> How to use the double colon [ : : ]? 1. >>> listx=[1, 5, 7, 3, 2, 4, 6] 2. >>> print(listx) 3. [1, 5, 7, 3, 2, 4, 6] 4. >>> sublist=listx[2:7:2] #list[start:stop:step], #step specify an increment 5. between the elements to cut of the list. 6. >>> print(sublist) 7. [7, 2, 6] 8. >>> sublist=listx[::3] #returns a list with a jump every 2 times. 9. >>> print(sublist

10. [1, 3, 6] 11. >>> sublist=listx[6:2:-2] #when step is negative the jump is made back 12. >>> print(sublist) 13. [6, 2] 14. >>> Find the largest and the smallest item in a list 1. >>> listx=[5, 10, 3, 25, 7, 4, 15] 2. >>> print(listx) 3. [5, 10, 3, 25, 7, 4, 15] 4. >>> print(max(listx)) # the max() function of built-in allows to know the highest 5. value in the list. 6. 25 7. >>> print(min(listx)) #the min() function of built-in allows to know the lowest 8. value in the list. 9. 3 10. >>> Compare two lists in Python 1. >>> listx1, listx2=[3, 5, 7, 9], [3, 5, 7, 9] 2. >>> print (listx1 == listx2) 3. True 4. >>> listx1, listx2=[9, 7, 5, 3], [3, 5, 7, 9] #create two lists equal, but unsorted. 5. >>> print(listx1 == listx2) 6. False 7. >>> listx1, listx2 =[2, 3, 5, 7], [3, 5, 7, 9] #create two different list 8. >>> print(listx1 == listx2) 9. False 10. >>> print(listx1.sort() == listx2.sort()) #order and compare 11. True 12. >>>

VIJAY Page 40 Python Programming Language

Nested lists in Python 1. >>> listx = [["Hello", "World"], [0, 1, 2, 3, 4, 5]] 2. >>> print(listx) 3. [['Hello', 'World'], [0, 1, 2, 3, 4, 5]] 4. >>> listx = [["Hello", "World"], [0, 1, 2, 3, 3, 5]] 5. >>> print(listx) 6. [['Hello', 'World'], [0, 1, 2, 3, 3, 5]] 7. >>> print(listx[0][1]) #The first [] indicates the index of the outer list. 8. World 9. >>> print(listx[1][3]) #the second [] indicates the index nested lists. 10. 3 11. >>> listx.append([True, False]) #add new items 12. >>> print(listx) 13. [['Hello', 'World'], [0, 1, 2, 3, 3, 5], [True, False]] 14. >>> listx[1][2]=4 15. >>> print(listx) 16. [['Hello', 'World'], [0, 1, 4, 3, 3, 5], [True, False]] #update value items 17. >>> How can I get the index of an element contained in the list? 1. >>> listy = list("HELLO WORLD") 2. >>> print(listy) 3. ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D'] 4. >>> index = listy.index("L") #get index of the first item whose value is passed as par ameter 5. >>> print(index) 6. 2 7. >>> index = listy.index("L", 4) #define the index from which you want to search 8. >>> print(index) 9. 9 10. >>> index = listy.index("O", 3, 5) #define the segment of the list to be searched 11. >>> print(index) 12. 4 13. >>> Using Lists as Stacks 1. >>> color_list=["Red", "Blue", "Green", "Black"] 2. >>> print(color_list) 3. ['Red', 'Blue', 'Green', 'Black'] 4. >>> color_list.append("White") 5. >>> color_list.append("Yellow") 6. >>> print(color_list) 7. ['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow'] 8. >>> color_list.pop() 9. 'Yellow' 10. >>> color_list.pop() 11. 'White' 12. >>> color_list.pop() 13. 'Black' 14. >>> color_list 15. ['Red', 'Blue', 'Green'] 16. >>>

VIJAY Page 41 Python Programming Language

Using Lists as Queues 1. >>> from collections import deque 2. >>> color_list = deque(["Red", "Blue", "Green", "Black"]) 3. >>> color_list.append("White") # White arrive 4. >>> print(color_list) 5. deque(['Red', 'Blue', 'Green', 'Black', 'White']) 6. >>> color_list.append("Yellow") # Yellow arrive 7. >>> print(color_list) 8. deque(['Red', 'Blue', 'Green', 'Black', 'White', 'Yellow']) 9. >>> color_list.popleft() # The first to arrive now leaves 10. 'Red' 11. >>> print(color_list) 12. deque(['Blue', 'Green', 'Black', 'White', 'Yellow']) 13. >>> color_list.popleft() # The second to arrive now leaves 14. 'Blue' 15. >>> print(color_list) 16. deque(['Green', 'Black', 'White', 'Yellow']) 17. >>> print(color_list) # Remaining queue in order of arrival 18. deque(['Green', 'Black', 'White', 'Yellow’])

19. >>> Tuples A tuple is a container which holds a series of comma-separated values (items or elements) between parentheses such as an (x, y) co-ordinate. Tuples are like lists, except they are immutable (i.e. you cannot change its content once created) and can hold mix data types. Tuples play a sort of "struct" role in Python -- a convenient way to pass around a little logical, fixed size bundle of values. Operations on tuple : Create a tuple How to get an item of the tuple in Python? How to know if an element exists within a tuple in Python? List to tuple Unpack a tuple in several variables Add item in Python tuple! Clone a tuple In Python how to know the number of times an item has repeated Remove an item from a tuple Slice a tuple How to get the index of an item of the tuple in Python? The size of a tuple How operators + and * are used with a Python tuple? Slice of a tuple using step parameter. Modify items of a tuple Create a tuple? To create a tuple, just list the values within parenthesis separated by commas. The "empty" tuple is just an empty pair of parenthesis 1. >>> #create an empty tuple 2. >>> tuplex = () 3. >>> print (tuplex) 4. ()

VIJAY Page 42 Python Programming Language

5. >>> #create a tuple with different data types 6. >>> tuplex = ('tuple', False, 3.2, 1) 7. >>> print (tuplex) 8. ('tuple', False, 3.2, 1) 9. >>> #create a tuple with numbers, notation without parenthesis 10. >>> tuplex = 4, 7, 3, 8, 1 11. >>> print (tuplex) 12. (4, 7, 3, 8, 1) 13. >>> #create a tuple of one item, notation without parenthesis 14. >>> tuplex = 4, 15. >>> print (tuplex) 16. (4,) 17. >>> #create an empty tuple with tuple() function built-in Python 18. >>> tuplex = tuple() 19. >>> print (tuplex) 20. () 21. >>> #create a tuple from a iterable object 22. >>> tuplex = tuple([True, False]) 23. >>> print (tuplex) 24. (True, False) 25. >>>

How to get an item of the tuple in Python? 1. >>> #create a tuple 2. >>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e") 3. >>> print(tuplex) 4. ('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e') 5. >>> #get item (4th element)of the tuple by index 6. >>> item = tuplex[3] 7. >>> print(item) 8. e 9. >>> #get item (4th element from last)by index negative 10. >>> item1 = tuplex[-4] 11. >>> print(item1) 12. u 13. >>> How to know if an element exists within a tuple in Python? 1. >>> #create a tuple 2. >>> tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e") 3. >>> print(tuplex) 4. ('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e') 5. >>> #use in statement 6. >>> print("r" in tuplex) 7. True 8. >>> print(5 in tuplex) 9. False 10. >>> List to tuple 1. >>> #create list 2. >>> listx = [5, 10, 7, 4, 15, 3]

VIJAY Page 43 Python Programming Language

3. >>> print(listx) 4. [5, 10, 7, 4, 15, 3] 5. >>> #use the tuple() function built-in Python, passing as parameter the list 6. >>> tuplex = tuple(listx) 7. >>> print(tuplex) 8. (5, 10, 7, 4, 15, 3) 9. >>> Unpack a tuple in several variables 1. >>> #create a tuple 2. >>> tuplex = 4, 8, 3 3. >>> print(tuplex) 4. (4, 8, 3) 5. >>> n1, n2, n3 = tuplex 6. >>> #unpack a tuple in variables 7. >>> print(n1 + n2 + n3) 8. 15 9. >>> #the number of variables must be equal to the number of items of the tuple 10. >>> n1, n2, n3, n4 = tuplex 11. Traceback (most recent call last): 12. File "", line 1, in 13. ValueError: need more than 3 values to unpack 14. >>>

Add item in Python tuple! 1. >>> #create a tuple 2. >>> tuplex = (4, 6, 2, 8, 3, 1) 3. >>> print(tuplex) 4. (4, 6, 2, 8, 3, 1) 5. >>> #tuples are immutable, so you can not add new elements 6. >>> #using merge of tuples with the + operator you can add an element and it will create a new tuple 7. >>> tuplex = tuplex + (9,) 8. >>> print(tuplex) 9. (4, 6, 2, 8, 3, 1, 9) 10. >>> #adding items in a specific index 11. >>> tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5] 12. >>> print(tuplex) 13. (4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3) 14. >>> #converting the tuple to list 15. >>> listx = list(tuplex) 16. >>> #use different ways to add items in list 17. >>> listx.append(30) 18. >>> tuplex = tuple(listx) 19. >>> print(tuplex) 20. (4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30) 21. >>> VIJAY Page 44 Python Programming Language

Clone a tuple 1. >>> from copy import deepcopy 2. >>> #create a tuple 3. >>> tuplex = ("HELLO", 5, [], True) 4. >>> print(tuplex) 5. ('HELLO', 5, [], True) 6. >>> #make a copy of a tuple using deepcopy() function 7. >>> tuplex_clone = deepcopy(tuplex) 8. >>> tuplex_clone[2].append(50) 9. >>> print(tuplex_clone) 10. ('HELLO', 5, [50], True) 11. >>> print(tuplex) 12. ('HELLO', 5, [], True) 13. >>> In Python how to know the number of times an item has repeated 1. >>> #create a tuple 2. >>> tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 3. >>> print(tuplex) 4. (2, 4, 5, 6, 2, 3, 4, 4, 7) 5. >>> #return the number of times it appears in the tuple. 6. >>> count = tuplex.count(4) 7. >>> print(count) 8. 3 9. >>> count = tuplex.count(7) 10. >>> print(count) 11. 1 12. >>> count = tuplex.count(5) 13. >>> print (count) 14. 1 15. >>> Remove an item from a tuple 1. >>> #create a tuple 2. >>> tuplex = "w", 3, "d", "r", "e", "s", "l" 3. >>> print(tuplex) 4. ('w', 3, 'd', 'r', 'e', 's', 'l') 5. >>> #tuples are immutable, so you can not remove elements 6. >>> #using merge of tuples with the + operator you can remove an item and it will create a new tuple 7. >>> tuplex = tuplex[:2] + tuplex[3:] 8. >>> print(tuplex) 9. ('w', 3, 'r', 'e', 's', 'l') 10. >>> #converting the tuple to list 11. >>> listx = list(tuplex) 12. >>> #use different ways to remove an item of the list 13. >>> listx.remove("l") 14. >>> #converting the tuple to list 15. >>> tuplex = tuple(listx) 16. >>> print(tuplex) 17. ('w', 3, 'r', 'e', 's') 18. >>>

VIJAY Page 45 Python Programming Language

Slice a tuple 1. >>> #create a tuple 2. >>> tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1) 3. >>> #used tuple[start:stop] the start index is inclusive and the stop index 4. >>> _slice = tuplex[3:5] 5. #is exclusive. 6. >>> print(_slice) 7. (5, 4) 8. >>> #if the start index isn't defined, is taken from the beg inning of the tuple. 9. >>> _slice = tuplex[:6] 10. >>> print(_slice) 11. (2, 4, 3, 5, 4, 6) 12. >>> #if the end index isn't defined, is taken until the end of the tuple 13. >>> _slice = tuplex[5:] 14. >>> print(_slice) 15. (6, 7, 8, 6, 1) 16. >>> #if neither is defined, returns the full tuple 17. >>> _slice = tuplex[:] 18. >>> print(_slice) 19. (2, 4, 3, 5, 4, 6, 7, 8, 6, 1) 20. >>> #The indexes can be defined with negative values 21. >>> _slice = tuplex[-8:-4] 22. >>> print(_slice) 23. (3, 5, 4, 6) 24. >>> ind the index of an item of the tuple 1. >>> #create a tuple 2. >>> tuplex = tuple("index tuple") 3. >>> print(tuplex) 4. ('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e') 5. >>> #get index of the first item whose value is passed as parameter 6. >>> index = tuplex.index("p") 7. >>> print(index) 8. 8 9. >>> #define the index from which you want to search 10. >>> index = tuplex.index("p", 5) 11. >>> print(index) 12. 8 13. >>> #define the segment of the tuple to be searched 14. >>> index = tuplex.index("e", 3, 6) 15. >>> print(index) 16. 3 17. >>> #if item not exists in the tuple return ValueError Exception 18. >>> index = tuplex.index("y") 19. Traceback (most recent call last): 20. File "", line 1, in 21. ValueError: tuple.index(x): x not in tuple 22. >>> VIJAY Page 46 Python Programming Language

The size of a tuple 1. >>> tuplex = tuple("w3resource") #create a tuple 2. >>> print(tuplex) 3. ('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e') 4. >>> #use the len() function to known the lenght of tuple. 5. >>> print(len(tuplex)) 6. 10 7. >>> How operators + and * are used with a Python tuple? 1. 5, #create a tuple 2. >>> #The * operator allow repeat the items in the tuple 3. >>> print(tuplex * 6) 4. (5, 5, 5, 5, 5, 5) 5. >>> #create a tuple with repeated items. 6. >>> tuplex = (5, 10, 15) * 4 7. >>> print(tuplex) 8. (5, 10, 15, 5, 10, 15, 5, 10, 15, 5, 10, 15) 9. >>> #create three tuples 10. >>> tuplex1 = (3, 6, 9, 12, 15) 11. >>> tuplex2 = ("w", 3, "r", "s", "o", "u", "r", "c", "e") 12. >>> tuplex3 = (True, False) 13. >>> #The + operator allow create a tuple joining two or more tuples 14. >>> tuplex = tuplex1 + tuplex2 + tuplex3 15. >>> print(tuplex) 16. (3, 6, 9, 12, 15, 'w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e', True, False) 17. >>> Slice of a tuple using step parameter 1. >>> #create a tuple 2. >>> tuplex = tuple("HELLO WORLD") 3. >>> print(tuplex) 4. ('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D') 5. >>> #step specify an increment between the elements to cut of the tuple 6. >>> _slice = tuplex[2:9:2] #tuple[start:stop:step] 7. >>> print(_slice) 8. ('L', 'O', 'W', 'R') 9. >>> #returns a tuple with a jump every 3 items. 10. >>> _slice = tuplex[::4] 11. >>> print(_slice) 12. ('H', 'O', 'R') 13. >>> #when step is negative the jump is made back 14. >>> _slice = tuplex[9:2:-4] 15. >>> print(_slice) 16. ('L', ' ') 17. >>> #when step is negative the jump is made back 18. >>> _slice = tuplex[9:2:-3] 19. >>> print(_slice) 20. ('L', 'W', 'L') 21. >>> VIJAY Page 47 Python Programming Language

Modify items of a tuple 1. >>> #create a tuple 2. >>> tuplex = ("w", 3, "r", [], False) 3. >>> print(tuplex) 4. ('w', 3, 'r', [], False) 5. >>> #tuples are immutable, so you can not modify items which are also immutable, as str, boolean, numbers etc. 6. >>> tuplex[3].append(200) 7. >>> print(tuplex) 8. ('w', 3, 'r', [200], False) 9. >>>

Sets A set object is an unordered collection of distinct hash able objects. It is commonly used in membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Sets support x in the set, Len(set), and for x in set like other collections. Set is an unordered collection and does not record element position or order of insertion. Sets do not support indexing, slicing, or other sequence-like behavior. There are currently two built-in set types, set, and frozen set. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozen set type is immutable and hash able — its contents cannot be altered after it is created; it can, therefore, be used as a dictionary key or as an element of another set.

Operations on Sets Create a set in Python Iteration Over Sets Add member(s) in Python set Remove item(s) from Python set Intersection of sets Union of sets set difference in Python Symmetric difference issubset and issuperset Shallow copy of sets Clear sets Create a set in Python 1. >>> #A new empty set 2. >>> setx = set() 3. >>> print(setx) 4. set() 5. >>> #A non empty set 6. >>> n = set([0, 1, 2, 3, 4, 5]) 7. >>> print(n) 8. {0, 1, 2, 3, 4, 5} 9. >>>

VIJAY Page 48 Python Programming Language

Iteration Over Sets

We can move over each of the items in a set using a loop. However, since sets are unordered, it is undefined which order the iteration will follow. 1. >>> num_set = set([0, 1, 2, 3, 4, 5]) 2. >>> for n in num_set: 3. print(n) 4. 5. 0 6. 1 7. 2 8. 3 9. 4 10. 5 11. >>> Add member(s) in Python set 1. >>> #A new empty set 2. >>> color_set = set() 3. >>> #Add a single member 4. >>> color_set.add("Red") 5. >>> print(color_set) 6. {'Red'} 7. >>> #Add multiple items 8. >>> color_set.update(["Blue", "Green"]) 9. >>> print(color_set) 10. {'Red', 'Blue', 'Green'} 11. >>> Remove item(s) from Python set pop(), remove() and discard() functions are used to remove individual item from a Python set. See the following examples : pop() function : 1. >>> num_set = set([0, 1, 2, 3, 4, 5]) 2. >>> num_set.pop() 3. 0 4. >>> print(num_set) 5. {1, 2, 3, 4, 5} 6. >>> num_set.pop() 7. 1 8. >>> print(num_set) 9. {2, 3, 4, 5} 10. >>> remove() function : 1. >>> num_set = set([0, 1, 2, 3, 4, 5]) 2. >>> num_set.remove(0) 3. >>> print(num_set) 4. {1, 2, 3, 4, 5} 5. >>> VIJAY Page 49 Python Programming Language

Union of sets discard() function : 1. >>> num_set = set([0, 1, 2, 3, 4, 5]) 2. >>> num_set.discard(3) 3. >>> print(num_set) 4. {0, 1, 2, 4, 5} 5. >>> Intersection of sets In mathematics, the intersection A ∩ B of two sets A and B is the set that contains all elements of A that also belong to B (or equivalently, all elements of B that also belong to A), but no other elements. 1. >>> #Intersection 2. >>> setx = set(["green", "blue"]) 3. >>> sety = set(["blue", "yellow"]) 4. >>> setz = setx & sety 5. >>> print(setz) 6. {'blue'} 7. >>>

In set theory, the union (denoted by ∪) of a collection of sets is the set of all distinct Elements in the collection. It is one of the fundamental operations through which sets can be combined and related to each other.

1. >>> #Union 2. >>> setx = set(["green", "blue"]) 3. >>> sety = set(["blue", "yellow"]) 4. >>> seta = setx | sety 5. >>> print (seta) 6. {'yellow', 'blue', 'green'} 7. >>> Set difference 1. >>> setx = set(["green", "blue"]) 2. >>> sety = set(["blue", "yellow"]) 3. >>> setz = setx & sety 4. >>> print(setz) 5. {'blue'} 6. >>> #Set difference 7. >>> setb = setx - setz 8. >>> print(setb) 9. {'green'} 10. >>> Symmetric difference 1. >>> setx = set(["green", "blue"]) 2. >>> sety = set(["blue", "yellow"]) 3. >>> #Symmetric difference 4. >>> setc = setx ^ sety 5. >>> print(setc) 6. {'yellow', 'green'} 7. >>>

VIJAY Page 50 Python Programming Language issubset and issuperset 1. >>> setx = set(["green", "blue"]) 2. >>> sety = set(["blue", "yellow"]) 3. >>> issubset = setx <= sety 4. >>> print(issubset) 5. False 6. >>> issuperset = setx >= sety 7. >>> print(issuperset) 8. False 9. >>> Shallow copy of sets 1. >>> setx = set(["green", "blue"]) 2. >>> sety = set(["blue", "green"]) 3. >>> #A shallow copy 4. >>> setd = setx.copy() 5. >>> print(setd) 6. {'blue', 'green'} 7. >>> Clear sets 1. >>> setx = set(["green", "blue"]) 2. >>> #Clear AKA empty AKA erase 3. >>> sete = setx.copy() 4. >>> sete.clear() 5. >>> print(sete) 6. set() 7. >>>

Dictionary Python dictionary is a container of the unordered set of objects like lists.The objects are surrounded by curly braces { }. The items in a dictionary are a comma-separated list of key: value pairs where keys and values are Python data type. Each object or value accessed by key and keys are unique in the dictionary. As keys are used for indexing, they must be the immutable type (string, number, or tuple). You can create an empty dictionary using empty curly braces. Operations on Dictionaries: Create a new dictionary in Python Get value by key in Python dictionary Add key/value to a dictionary in Python Iterate over Python dictionaries using for loops Remove a key from a Python dictionary Sort a Python dictionary by key Find the maximum and minimum value of a Python dictionary Concatenate two Python dictionaries into a new one Test whether a Python dictionary contains a specific key Find the length of a Python dictionary Python Dictionary - Exercises, Practice, Solution VIJAY Page 51 Python Programming Language

Create a new dictionary in Python 1. >>> #Empty dictionary 2. >>> new_dict = dict() 3. >>> new_dict = {} 4. >>> print(new_dict) 5. {} 6. >>> #Dictionary with key-vlaue 7. >>> color = {"col1" : "Red", "col2" : "Green", "col3" : "Orange" } 8. >>> color 9. {'col2': 'Green', 'col3': 'Orange', 'col1': 'Red'} 10. >>> Get value by key in Python dictionary 1. >>> #Declaring a dictionary 2. >>> dict = {1:20.5, 2:3.03, 3:23.22, 4:33.12} 3. >>> #Access value using key 4. >>> dict[1] 5. 20.5 6. >>> dict[3] 7. 23.22 8. >>> #Accessing value using get() method 9. >>> dict.get(1) 10. 20.5 11. >>> dict.get(3) 12. 23.22 13. >>> Add key/value to a dictionary in Python 1. >>> #Declaring a dictionary with a single element 2. >>> dic = {'pdy1':'DICTIONARY'} 3. >>>print(dic) 4. {'pdy1': 'DICTIONARY'} 5. >>> dic['pdy2'] = 'STRING' 6. >>> print(dic) 7. {'pdy1': 'DICTIONARY', 'pdy2': 'STRING'} 8. >>> 9. >>> #Using update() method to add key-values pairs in to dictionary 10. >>> d = {0:10, 1:20} 11. >>> print(d) 12. {0: 10, 1: 20} 13. >>> d.update({2:30}) 14. >>> print(d) 15. {0: 10, 1: 20, 2: 30} 16. >>>

Iterate over Python dictionaries using for loops Code: 1. d = {'Red': 1, 'Green': 2, 'Blue': 3} 2. for color_key, value in d.items(): 3. print(color_key, 'corresponds to ', d[color_key]) VIJAY Page 52 Python Programming Language

Output: >>> Green corresponds to 2 Red corresponds to 1 Blue corresponds to 3 >>> Remove a key from a Python dictionary Code: 1. myDict = {'a':1,'b':2,'c':3,'d':4} 2. print(myDict) 3. if 'a' in myDict: 4. del myDict['a'] 5. print(myDict) Output: >>> {'d': 4, 'a': 1, 'b': 2, 'c': 3} {'d': 4, 'b': 2, 'c': 3} >>> Sort a Python dictionary by key Code: 1. color_dict = {'red':'#FF0000', 2. 'green':'#008000', 3. 'black':'#000000', 4. 'white':'#FFFFFF'} 5. 6. for key in sorted(color_dict): 7. print("%s: %s" % (key, color_dict[key])) Output: >>> black: #000000 green: #008000 red: #FF0000 white: #FFFFFF >>> Find the maximum and minimum value of a Python dictionary Code: 1. my_dict = {'x':500, 'y':5874, 'z': 560} 2. 3. key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) 4. key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) 5. 6. print('Maximum Value: ',my_dict[key_max]) 7. print('Minimum Value: ',my_dict[key_min]) Output: >>> Maximum Value: 5874 Minimum Value: 500 >>> VIJAY Page 53 Python Programming Language

Concatenate two Python dictionaries into a new one Code: 1. dic1={1:10, 2:20} 2. dic2={3:30, 4:40} 3. dic3={5:50,6:60} 4. dic4 = {} 5. for d in (dic1, dic2, dic3): dic4.update(d) 6. print(dic4) Output: >>> {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} >>> Test whether a Python dictionary contains a specific key Code: 1. fruits = {} 2. fruits["apple"] = 1 3. fruits["mango"] = 2 4. fruits["banana"] = 4 5. 6. # Use in. 7. if "mango" in fruits: 8. print("Has mango") 9. else: 10. print("No mango") 11. 12. # Use in on nonexistent key. 13. if "orange" in fruits: 14. print("Has orange") 15. else: 16. print("No orange") Output >>> Has mango No orange >>> Find the length of a Python dictionary Code: 1. fruits = {"mango": 2, "orange": 6} 2. 3. # Use len() function to get the length of the dictionary 4. print("Length:", len(fruits)) Output: >>> Length: 2 VIJAY Page 54 Python Programming Language

Sequences: The most basic data structure in Python is the sequence. Sequence Types -- str, unicode, list, tuple, buffer, xrange There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.

Operation Result Notes x in s True if an item of s is equal to x, else False (1) x not in s False if an item of s is equal to x, else True s + t the concatenation of s and t (6) s * n , n * n shallow copies of s concatenated s s[i] i'th item of s, origin 0 (3) s[i:j] slice of s from i to j (3), (4) s[i:j:k] slice of s from i to j with step k (3), (5) len(s) length of s min(s) smallest item of s max(s) largest item of s

Notes: (1) When s is a string or Unicode string object the in and not in operations act like a substring test. In Python versions before 2.3, x had to be a string of length 1. In Python 2.3 and beyond, x may be a string of any length. (2) Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider: > lists = [[]] * 3 > lists [[], [], []] > lists[0].append(3) > lists [[3], [3], [3]] What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of listsmodifies this single list. You can create a list of different lists this way: > lists = [[] for i in range(3)] > lists[0].append(3) > lists[1].append(5) > lists[2].append(7) > lists [[3], [5], [7]] VIJAY Page 55 Python Programming Language

(3) If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0. (4) The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty. (5) The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping whenj is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become ``end'' values (which end depends on the sign of k). Note, k cannot be zero. If k is none, it is treated like 1.

(6) If s and t are both strings, some Python implementations such as CPython can Usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This Optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations. Changed in version 2.4: Formerly, string concatenation never occurred in-place. Comprehensions Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced list comprehensions and Python 3.0 comes with dictionary and set comprehensions.

List Comprehensions A list comprehension consists of the following parts: An Input Sequence. A Variable representing members of the input sequence. An Optional Predicate expression. An Output Expression producing elements of the output list from members of the Input Sequence that satisfy the predicate. Say we need to obtain a list of all the integers in a sequence and then square them: a_list = [1, ‘4’, 9, ‘a’, 0, 4] squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ] print squared_ints # [ 1, 81, 0, 16 ] VIJAY Page 56 Python Programming Language

The iterator part iterates through each member e of the input sequence a_list. The predicate checks if the member is an integer. If the member is an integer then it is passed to the output expression, squared, to become a member of the output list. Much the same results can be achieved using the built in functions, map, filter and the Anonymous lambda function. The filter function applies a predicate to a sequence: filter(lambda e: type(e) == types.IntType, a_list) Map modifies each member of a sequence: map(lambda e: e**2, a_list) The two can be combined: map(lambda e: e**2, filter(lambda e: type(e) == types.IntType, a_list)) The above example involves function calls to map, filter, type and two calls to lambda. Function calls in Python are expensive. Furthermore the input sequence is traversed through twice and an intermediate list is produced by filter. The list comprehension is enclosed within a list so, it is immediately evident that a list is being produced. There is only one function call to type and no call to the cryptic lambda instead the list comprehension uses a conventional iterator, an expression and an if expression for the optional predicate

Nested Comprehensions An identity matrix of size n is an n by n square matrix with ones on the main diagonal and zeros elsewhere. A 3 by 3 identity matrix is:

In python we can represent such a matrix by a list of lists, where each sub-list represents a row. A 3 by 3 matrix would be represented by the following list:

[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ] VIJAY Page 57 Python Programming Language

The above matrix can be generated by the following comprehension: [ [ 1 if item_idx == row_idx else 0 for item_idx in range(0, 3) ] for row_idx in range(0, 3) ] Techniques Using zip() and dealing with two or more elements at a time: ['%s=%s' % (n, v) for n, v in zip(self.all_names, self)] Multiple types (auto unpacking of a tuple): [f(v) for (n, f), v in zip(cls.all_slots, values)] A two-level list comprehension using os.walk() : # Comprehensions/os_walk_comprehension.py import os restFiles = [os.path.join(d[0], f) for d in os.walk(".") for f in d[2] if f.endswith(".rst")] for r in restFiles: print(r)

Set Comprehensions Set comprehensions allow sets to be constructed using the same principles as list Comprehensions, the only difference is that resulting sequence is a set. Say we have a list of names. The list can contain names which only differ in the case used to represent them, duplicates and names consisting of only one character. We are only interested in names longer then one character and wish to represent all names in the same format: The first letter should be capitalised, all other characters should be lower case.

Given the list: names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob' ] We require the set: { 'Bob', 'John', 'Alice' } Note the new syntax for denoting a set. Members are enclosed in curly braces. The following set comprehension accomplishes this: { name[0].upper() + name[1:].lower() for name in names if len(name) > 1 }

Dictionary Comprehensions Say we have a dictionary the keys of which are characters and the values of which map to the number of times that character appears in some text. The dictionary currently distinguishes between upper and lower case characters. We require a dictionary in which the occurrences of upper and lower case characters are combined: mcase = {'a':10, 'b': 34, 'A': 7, 'Z':3} mcase_frequency = { k.lower() : mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() } # mcase_frequency == {'a': 17, 'z': 3, 'b': 34} VIJAY Page 58 Python Programming Language

UNIT -4 Functions: A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user- defined functions. Defining a Function You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these Parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Syntax: def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example: Here is the simplest form of a Python function. This function takes a string as input parameter and prints it on standard screen. def printme( str ):

"This prints a passed string into this function" print str return Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function: #!/usr/bin/python # Function definition is here def printme( str ):

VIJAY Page 59 Python Programming Language

"This prints a passed string into this function" print str; return; # Now you can call printme function printme("I'm first call to user defined function!"); printme("Again second call to the same function"); When the above code is executed, it produces the following result: I'm first call to user defined function! Again second call to the same function Pass by reference vs 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, the change also reflects back in the calling function. For example: #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function. #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return

# Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]

VIJAY Page 60 Python Programming Language

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. Here, the number of arguments in the function call should match exactly with the function definition. To call the function printme(), you definitely need to pass one argument, otherwise it would give 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; return; # Now you can call printme function printme(); When the above code is executed, it produces the following result: Traceback (most recent call last): File "test.py", line 11, in printme(); TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments: Keyword arguments are related to the function calls. When you use keyword Arguments in a function call, the caller identifies the arguments by the parameter 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. 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; return; # Now you can call printme function printme( str = "My string"); When the above code is executed, it produces the following result:

VIJAY Page 61 Python Programming Language

My string Following example gives more clear picture. Note, here order of the parameter does not matter.

#!/usr/bin/python # Function definition is here def printinfo( name, age ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo function printinfo( age=50, name="miki" ); When the above code is executed, 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. Following example gives an idea on default arguments; it would print default age if it is not passed: #!/usr/bin/python # Function definition is here def printinfo( name, age = 35 ): "This prints a passed info into this function" print "Name: ", name; print "Age ", age; return; # Now you can call printinfo function printinfo( age=50, name="miki" ); printinfo( name="miki" ); When the above code is executed, it produces the following result: Name: miki Age 50 Name: miki Age 35 Variable-length arguments: You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. The general syntax for a function with non-keyword variable arguments is this: def function name([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that will hold the values of all Non keyword variable arguments. This tuple remains empty if no additional

VIJAY Page 62 Python Programming Language arguments are specified during the function call. Following is a simple example: #!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return;

# Now you can call printinfo function printinfo( 10 ); printinfo( 70, 60, 50 ); When the above code is executed, it produces the following result: Output is: 10 Output is: 70 60 50

The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. An anonymous function cannot be a direct call to print because lambda requires an expression. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax: The syntax of lambda functions contains only a single statement, which is as follows: lambda [arg1 [,arg2,.....argn]]:expression Following is the example to show how lambda form of function works: #!/usr/bin/python # Function definition is here

VIJAY Page 63 Python Programming Language sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) When the above code is executed, it produces the following result: Value of total : 30 Value of total : 40

The return Statement: The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. All the above examples are not returning any value, but if you like you can return a value from a function as follows: #!/usr/bin/python

# Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total When the above code is executed, 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. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables Global vs. Local variables: Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example: #!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ):

VIJAY Page 64 Python Programming Language

# Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total When the above code is executed, it produces the following result: Inside the function local total : 30 Outside the function global total : 0 Modules: A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. Example: The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py def print_func( par ): print "Hello : ", 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. The import has the following syntax: import module1[, module2[,... moduleN] When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module hello.py, you need to put the following command at the top of the script: #!/usr/bin/python # Import module support import support # Now you can call defined function that module as follows support.print_func("Zara") When the above code is executed, it produces the following result: Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

VIJAY Page 65 Python Programming Language

The from...import Statement Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax: from mod name import name1[, name2[, ... nameN]] For example, to import the function fibonacci from the module fib, 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. The from...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; however, this statement should be used sparingly. Locating Modules: When you import a module, the Python interpreter searches for the module in the following sequences:

The current directory. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.

The PYTHONPATH Variable: The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. Here is a typical PYTHONPATH from a Windows system: set PYTHONPATH=c:\python20\lib; 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. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions. Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.

VIJAY Page 66 Python Programming Language

Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem. #!/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. The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example: #!/usr/bin/python

# Import built-in module math import math content = dir(math) print content; When the above code is executed, it produces the following result: ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded. 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, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be

VIJAY Page 67 Python Programming Language extracted using the keys() function

The reload() Function: When the module is imported into a script, the code in the top-level portion of a module is executed only once. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this: reload(module_name) Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following: reload(hello) Packages: pip is the preferred installer program. Starting with Python 3.4, it is included by default with the Python binary installers. A virtual environment is a semi-isolated Python environment that allows packages to be installed for use by a particular application, rather than being installed system wide. venv is the standard tool for creating virtual environments, and has been part of Python since Python 3.3. Starting with Python 3.4, it defaults to installing pip into all created virtual environments. virtualenv is a third party alternative (and predecessor) to venv. It allows virtual environments to be used on versions of Python prior to 3.4, which either don’t provide venv at all, or aren’t able to automatically install pip into created environments. The Python Packaging Index is a public repository of open source licensed packages made available for use by other Python users. the Python Packaging Authority are the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation, and issue trackers on both GitHub and BitBucket. distutils is the original build and distribution system first added to the Python standard library in 1998. While direct use of distutils is being phased out, it still laid the foundation for the current packaging and distribution infrastructure, and it not only remains part of the standard library, but its name lives on in other ways (such as the name of the mailing list used to coordinate Python packaging standards development). Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6. Changed in version 3.5: The use of venv is now recommended for creating virtual environments.

VIJAY Page 68 Python Programming Language

Basic usage The standard packaging tools are all designed to be used from the command line. The following command will install the latest version of a module and its dependencies from the Python Packaging Index: python -m pip install SomePackage Note For POSIX users (including Mac OS X and Linux users), the examples in this guide assume the use of a virtual environment. For Windows users, the examples in this guide assume that the option to adjust the system PATH environment variable was selected when installing Python. It’s also possible to specify an exact or minimum version directly on the command line. When using comparator operators such as >, < or some other special character which get interpreted by shell, the package name and the version should be enclosed within double quotes: python -m pip install SomePackage==1.0.4 # specific version python -m pip install "SomePackage>=1.0.4" # minimum version Normally, if a suitable module is already installed, attempting to install it again will have no effect. Upgrading existing modules must be requested explicitly: python -m pip install --upgrade SomePackage More information and resources regarding pip and its capabilities can be found in the Python Packaging User Guide. Creation of virtual environments is done through the venv module. Installing packages into an active virtual environment uses the commands shown above. How do I ...? These are quick answers or links for some common tasks. ... install pip in versions of Python prior to Python 3.4? Python only started bundling pip with Python 3.4. For earlier versions, pip needs to be “bootstrapped” as described in the Python Packaging User Guide. ... install packages just for the current user? Passing the --user option to python -m pip install will install a package just for the current user, rather than for all users of the system

... install scientific Python packages? A number of scientific Python packages have complex binary dependencies, and aren’t currently easy to install using pip directly. At this point in time, it will often be easier for users to install these packages by other means rather than attempting to install them with pip. ... work with multiple versions of Python installed in parallel?¶ On Linux, Mac OS X, and other POSIX systems, use the versioned Python commands in combination with the -m switch to run the appropriate copy ofpip: python2 -m pip install SomePackage # default Python 2 python2.7 -m pip install SomePackage # specifically Python 2.7 python3 -m pip install SomePackage # default Python 3 python3.4 -m pip install SomePackage # specifically Python 3.4 Appropriately versioned pip commands may also be available.

VIJAY Page 69 Python Programming Language

On Windows, use the py Python launcher in combination with the -m switch: py -2 -m pip install SomePackage # default Python 2 py -2.7 -m pip install SomePackage # specifically Python 2.7 py -3 -m pip install SomePackage # default Python 3 py -3.4 -m pip install SomePackage # specifically Python 3.4

VIJAY Page 70 Python Programming Language

UNIT -5

Defining a class In object oriented programming classes and objects are the main features. A class creates a new data type and objects are instances of a class which follows the definition given inside the class. Here is a simple form of class definition. class Student: Statement-1 Statement-1 ...... Statement-n A class definition started with the keyword 'class' followed by the name of the class and a colon. The statements within a class definition may be function definitions, data members or other statements. When a class definition is entered, a new namespace is created, and used as the local scope. Creating a Class Here we create a simple class using class keyword followed by the class name (Student) which follows an indented block of segments (student class, roll no., name). view plaincopy to clipboardprint? 1. #studentdetails.py 2. class Student: 3. stu_class = 'V' 4. stu_roll_no = 12 5. stu_name = "David" Class Objects There are two kind of operations class objects supports : attribute references and instantiation. Attribute references use the standard syntax, obj.name for all attribute references in Python. Therefore if the class definition (add a method in previous example) look like this view plaincopy to clipboardprint? 1. #studentdetails1.py 2. class Student: 3. """A simple example class""" 4. stu_class = 'V' 5. stu_roll_no = 12 6. stu_name = "David" 7. def messg(self): 8. return 'New Session will start soon.' then Student.stu_class, Student.stu_roll_no, Student.stu_name are valid attribute reference and returns 'V', 12, 'David'. Student.messg returns a function object. In Python self is a name for the first argument of a method

VIJAY Page 71 Python Programming Language which is different from ordinary function. Rather than passing the object as a parameter in a method the word self refers to the object itself. For example if a method is defined as avg(self, x, y, z), it should be called as a.avg(x, y, z). See the output of the attributes in Python Shell.

__doc__ is also a valid attribute which returns the docstring of the class. __init__ method There are many method names in Python which have special importance. A class may define a special method named __init__ which does some initialization work and serves as a constructor for the class. Like other functions or methods __init__ can take any number of arguments. The __init__ method is run as soon as an object of a class is instantiated and class instantiation automatically invokes __init__() for the newly-created class instance. See the following example a new, initialized instance can be obtained by: view plaincopy to clipboardprint? 1. #studentdetailsinit.py 2. class Student: 3. """A simple example class""" 4. def __init__(self, sclass, sroll, sname): 5. self.c = sclass 6. self.r = sroll 7. self.n = sname 8. def messg(self): 9. return 'New Session will start soon.'

VIJAY Page 72 Python Programming Language

Methods We have already discussed that classes/objects can have methods just like functions except that we have an extra self variable. We will now see an example (save as oop_method.py). class Person: def say_hi(self): print('Hello, how are you?') p = Person() p.say_hi() # The previous 2 lines can also be written as # Person().say_hi()

$ python oop_method.py Hello, how are you? How It Works Here we see the self in action. Notice that the say_hi method takes no parameters but still has the self in the function definition. Constructor Python doesn't have explicit constructors like C++ or Java, but the __init__() method in Python is something similar, though it is strictly speaking not a constructor. It behaves in many ways like a constructor, e.g. it is the first code which is executed, when a new instance of a class is created. The name sounds also like a constructor "__init__". But strictly speaking it would be wrong to call it a constructor, because a new instance is already "constructed" by the time the method __init__ is called.

But anyway, the __init__ method is used - like constructors in other object oriented programming languages - to initialize the instance variables of an object. The definition of an init method looks like any other method definition:

VIJAY Page 73 Python Programming Language def __init__(self, holder, number, balance,credit_line=1500): self.Holder = holder self.Number = number self.Balance = balance self.CreditLine = credit_line Inheritance The concept of inheritance provides an important feature to the the object-oriented programming is reuse of code. Inheritance is the process of creating a new class (derived class) to be based on an existing (base class) one where the new class inherits all the attributes and methods of the existing class. Following diagram shows the inheritance of a derived class from the parent (base) class

VIJAY Page 74 Python Programming Language

Like other object-oriented language, Python allows inheritance from a parent (or base) class as well as multiple inheritances in which a class inherits attributes and methods from more than one parent. See the single and multiple inheritance syntaxes :class DerivedClassName(BaseClassName): Statement-1 Statement-1 ...... Statement-n class DerivedClassName(BaseClassName1, BaseClassName2, BaseClassName3): Statement-1 Statement-1 ...... Statement-n Example : In a company Factory, staff and Office staff have certain common properties – all have a name, designation, age etc. Thus they can be grouped under a class called CompanyMember. Apart from sharing those common features, each subclass has its own characteristic - FactoryStaff gets overtime allowance while OfficeStaff gets traveling allowance for an office job. The derived classes ( FactoryStaff & OfficeStaff) has its own characteristic and, in addition, they inherit the properties of the base class (CompanyMember).

See the example code.

1. # python-inheritance.py 2. class CompanyMember: 3. '''Represents Company Member.''' 4. def __init__(self, name, designation, age): 5. self.name = name 6. self.designation = designation 7. self.age = age 8. def tell(self): 9. '''Details of an employee.''' 10. print('Name: ', self.name,'\nDesignation : ',self.designation, '\nAge : ',self.age) 11. 12. class FactoryStaff(CompanyMember): 13. '''Represents a Factory Staff.'''

VIJAY Page 75 Python Programming Language

14. def __init__(self, name, designation, age, overtime_allow): 15. CompanyMember.__init__(self, name, designation, age) 16. self.overtime_allow = overtime_allow 17. CompanyMember.tell(self) 18. print('Overtime Allowance : ',self.overtime_allow) 19. 20. class OfficeStaff(CompanyMember): 21. '''Represents a Office Staff.''' 22. def __init__(self, name, designation, age, travelling_allow): 23. CompanyMember.__init__(self, name, designation, age) 24. self.marks = travelling_allow 25. CompanyMember.tell(self) 26. print('Traveling Allowance : ',self.travelling_allow) Now execute the class in Python Shell and see the output.

Overriding Methods: You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass. Example: #!/usr/bin/python class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class

VIJAY Page 76 Python Programming Language def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method When the above code is executed, it produces the following result: Calling child method Data Hiding: An object's attributes may or may not be visible outside the class definition. For these cases, you can name attributes with a double underscore prefix, and those attributes will not be directly visible to outsiders.

Example: #!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.__secretCount When the above code is executed, it produces the following result: 1 2 Traceback (most recent call last): File "test.py", line 12, in print counter.__secretCount AttributeError: JustCounter instance has no attribute '__secretCount’ Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it would work for you: ...... print counter._JustCounter__secretCount When the above code is executed, it produces the following result: 1 2 2 Difference between an error and Exception Exceptions occur when exceptional situations occur in your program. For example, what if you are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program was running? Such situations are handled using exceptions. Similarly, what if your program had some invalid statements? This is handled by Python which raises its hands and tells you there is an error.

VIJAY Page 77 Python Programming Language

Errors Consider a simple print function call. What if we misspelt print as Print? Note the capitalization. In this case, Python raises a syntax error. > Print("Hello World") Traceback (most recent call last): File "", line 1, in NameError: name 'Print' is not defined > print("Hello World") Hello World Observe that a NameError is raised and also the location where the error was detected is printed. This is what an error handler for this error does.

What is Exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it can't cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.

Handling an exception: If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Syntax: Here is simple syntax of try....except...else blocks: try: You do your operations here; ...... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block...... else: If there is no exception then execute this block. Here are few important points about the above-mentioned syntax: A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else- block executes if the code in the try: block does not raise an exception. The else- block is a good place for code that does not need the try: block's

VIJAY Page 78 Python Programming Language protection.

Example: Here is simple example, which opens a file and writes the content in the file and comes out gracefully because there is no problem at all: #!/usr/bin/python try: fh = open("testfile", "w") fh.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" fh.close() This will produce the following result: Written content in the file successfully

Example: Here is one more simple example, which tries to open a file where you do not have permission to write in the file, so it raises an exception: #!/usr/bin/python try: fh = open("testfile", "w") fh.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 will produce 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; ...... except: If there is any exception, then execute this block...... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice

VIJAY Page 79 Python Programming Language though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

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; ...... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block...... else: If there is no exception then execute this block.

The try-finally clause: You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this: try: You do your operations here; ...... Due to any exception, this may be skipped. finally: This would always be executed...... Note that you can provide except clause(s), or a finally clause, but not both. You can not use else clause as well along with a finally clause. Example: #!/usr/bin/python try: fh = open("testfile", "w") fh.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, 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", "w") try: fh.write("This is my test file for exception handling!!")

VIJAY Page 80 Python Programming Language finally: print "Going to close the file" fh.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. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

Argument of an Exception: An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows: try: You do your operations here; ...... except ExceptionType, Argument: You can print value of Argument here... If you are writing the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception. This variable will receive the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location. Example: Following is an example for a single exception: #!/usr/bin/python # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz"); This would produce the following result: The argument does not contain numbers invalid literal for int() with base 10: 'xyz' Raising an exceptions:

VIJAY Page 81 Python Programming Language

You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement. Syntax: raise [Exception [, args [, traceback]]] Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. Example: An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows: def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write our except clause as follows: try:

Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here... User-Defined Exceptions: Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught. In the try block, 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. class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg So once you defined above class, you can raise your exception as follows: try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args

VIJAY Page 82 Python Programming Language

UNIT -6

Brief Tour of the Standard Library Interface The os module provides dozens of functions for interacting with the operating system: > import os > os.getcwd() # Return the current working directory 'C:\\Python26' > os.chdir('/server/accesslogs') # Change current working directory > os.system('mkdir today') # Run the command mkdir in the system shell 0 Be sure to use the import os style instead of from os import *. This will keep os.open() from shadowing the built-in open() function which operates much differently. The built-in dir() and help() functions are useful as interactive aids for working with large modules like os: > import os > dir(os) > help(os) For daily file and directory management tasks, the shutil module provides a higher level interface that is easier to use: > import shutil > shutil.copyfile('data.db', 'archive.db') > shutil.move('/build/executables', 'installdir')

String Pattern Matching The re module provides regular expression tools for advanced string processing. For complex matching and manipulation, regular expressions offer succinct, optimized solutions: > import re > re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] > re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat' When only simple capabilities are needed, string methods are preferred because they are easier to read and debug: > 'tea for too'.replace('too', 'two') 'tea for two'

VIJAY Page 83 Python Programming Language

Mathematics

The math module gives access to the underlying C library functions for floating point math: > import math > math.cos(math.pi / 4.0) 0.70710678118654757 > math.log(1024, 2) 10.0 The random module provides tools for making random selections: > import random > random.choice(['apple', 'pear', 'banana']) 'apple' > random.sample(xrange(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] > random.random() # random float 0.17970987693706186 > random.randrange(6) # random integer chosen from range(6) 4 Internet Access There are a number of modules for accessing the internet and processing internet protocols. Two of the simplest are urllib2 for retrieving data from URLs and smtplib for sending mail: > import urllib2 > for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print line
Nov. 25, 09:43:32 PM EST > import smtplib > server = smtplib.SMTP('localhost') > server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ...

... """) > server.quit() (Note that the second example needs a mailserver running on localhost.)

Dates and Times The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation. The module also supports objects that are timezone aware.

VIJAY Page 84 Python Programming Language

> # dates are easily constructed and formatted > from datetime import date > now = date.today() > now datetime.date(2003, 12, 2) > now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12- 02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' > # dates support calendar arithmetic > birthday = date(1964, 7, 31) > age = now - birthday > age.days 14368 Data Compression Common data archiving and compression formats are directly supported by modules including: zlib, gzip, bz2, zipfile and tarfile. > import zlib > s = 'witch which has which witches wrist watch' > len(s) 41 > t = zlib.compress(s) > len(t) 37 > zlib.decompress(t) 'witch which has which witches wrist watch' > zlib.crc32(s) 226805979 Python GUI Programming (Tkinter) Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below. Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter. wxPython: This is an open-source Python interface for wxWindows http://wxpython.org. JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org. There are many other interfaces available, which you can find them on the net. Tkinter Programming Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.

VIJAY Page 85 Python Programming Language

Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps − Import the Tkinter module. Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each event triggered by the user. Example #!/usr/bin/python import Tkinter top = Tkinter.Tk() # Code to add widgets will go here... top.mainloop() This would create a following window –

Tkinter Widgets

Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets. There are currently 15 types of widgets in Tkinter. 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. Canvas The Canvas widget is used to draw shapes, such aslines, ovals, polygons and rectangles, in your application. Checkbutton The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time. Entry The Entry widget is used to display a single-line text field for accepting values from a user. Frame The Frame widget is used as a container widget to organize other widgets.

Page VIJAY 86 Python Programming Language

Operator Description Label The Label widget is used to provide a single-line caption for other widgets. It can also contain images. List box The List box widget is used to provide a list of options to a user . Menu The Menu button widget is used to display menus in your button application. Menu The Menu widget is used to provide various commands to a user. These commands are contained inside Menu button. Message The Message widget is used to display multiline text fields for accepting values from a user. Radio The Radio button widget is used to display a number of options button as radio buttons. The user can select only one option at a time. Scale The Scale widget is used to provide a slider widget.

Scrollbar The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes. Text The Text widget is used to display text in multiple lines.

Top level The Top level widget is used to provide a separate window . container Spin box The Spin box widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values. Paned A Paned Window is a container widget that may contain any Window number of panes, arranged horizontally or vertically. Label Frame A label frame is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts. Tk Message This module is used to display message boxes in your Box applications

Let us study these widgets in detail − Standard attributes Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified. Dimensions Colors Fonts Anchors

Relief styles Bitmaps

VIJAY Page 87 Python Programming Language

Cursors Let us study them briefly − Geometry Management All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes: pack, grid, and place. The pack() Method - This geometry manager organizes widgets in blocks before placing them in the parent widget. The grid() Method - This geometry manager organizes widgets in a table-like structure in the parent widget. The place() Method -This geometry manager organizes widgets by placing them in a specific position in the parent widget. turtle — Turtle graphics Introduction Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966. Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.left(25), and it rotates in-place 25 degrees clockwise. By combining together these and similar commands, intricate shapes and pictures can easily be drawn. The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5. It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch. The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. The object-oriented interface uses essentially two+two classes: 1. The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvasas argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible.

VIJAY Page 88 Python Programming Language

All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface. 2. RawTurtle (alias: RawPen) defines Turtle objects which draw on a TurtleScreen. Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure- oriented interface. The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle. They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called. To use multiple turtles on a screen one has to use the object-oriented interface. Note In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here. Overview of available Turtle and Screen methods Turtle methods Turtle motion Move and draw forward() | fd() backward() | bk() | back() right() | rt() left() | lt() goto() | setpos() | setposition() setx() sety() setheading() | seth() home() circle() dot() stamp() clearstamp() clearstamps() undo() speed() Tell Turtle’s state position() | pos() towards() xcor() ycor()

VIJAY Page 89 Python Programming Language heading() distance() Setting and measurement degrees() radians() Pen control Drawing state pendown() | pd() | down() penup() | pu() | up() pensize() | width() pen() isdown() Color control color() pencolor() fillcolor() Filling filling() begin_fill() end_fill() More drawing control reset() clear() write() Turtle state Visibility showturtle() | st() hideturtle() | ht() isvisible() Appearance shape() resizemode() shapesize() | turtlesize() shearfactor() settiltangle() tiltangle() tilt() shapetransform() get_shapepoly() Using events onclick() onrelease() ondrag()

Special Turtle methods begin_poly() VIJAY Page 90 Python Programming Language end_poly() get_poly() clone() getturtle() | getpen() getscreen() setundobuffer() undobufferentries() Methods of TurtleScreen/Screen Window control bgcolor() bgpic() clear() | clearscreen() reset() | resetscreen() screensize() setworldcoordinates() Animation control delay() tracer() update() Using screen events listen() onkey() | onkeyrelease() onkeypress() onclick() | onscreenclick() ontimer() mainloop() Settings and special methods mode() colormode() getcanvas() getshapes() register_shape() | addshape() turtles() window_height() window_width() Input methods textinput() numinput() Methods specific to Screen bye() exitonclick() setup() title() VIJAY Page 91 Python Programming Language

Example Program:

Why testing is required ?, Software testing is very important because of the following reasons: 1. Software testing is really required to point out the defects and errors that were made during the development phases. 2. It’s essential since it makes sure of the Customer’s reliability and their satisfaction in the application. 3. It is very important to ensure the Quality of the product. Quality product delivered to the customers helps in gaining their confidence. (Know more about Software Quality) 4. Testing is necessary in order to provide the facilities to the customers like the delivery of high quality product or software application which requires lower maintenance cost and hence results into more accurate, consistent and reliable results. 5. Testing is required for an effective performance of software application or product. 6. It’s important to ensure that the application should not result into any failures because it can be very expensive in the future or in the later stages of the development. 7. It’s required to stay in the business.

VIJAY Page 92 Python Programming Language

Basic Concepts of Testing What is Testing? The process of testing the application to make sure that the application is working according to the requirements. What is Software Testing? Software testing is the process of executing a program / application under positive and negative conditions by manual or automated means. It checks for the :- .Specification .Functionality .Performance Who should test? .Developer .Understands the system .But,will test gently .Independent Tester .Must learn system .But,will attempt to break it What is an “Error”,”Bug”,”Fault” and “Failure”? A person makes an Error That creates a fault in software That can cause a failure in operation Error : An error is a human action that produces the incorrect result that results in a fault. Bug : The presence of error at the time of execution of the software. Fault : State of software caused by an error. Failure : Deviation of the software from its expected result. It is an event. Who is a Software Tester? Software Tester is the one who performs testing and find bugs, if they exist in the tested application.

The Testing Team Program Manager .The planning and execution of the project to ensure the success of a projectminimizing risk throughout the lifetime of the project. .Responsible for writing the product specification, managing the scheduleand making the critical decisions and trade-offs. QA Lead .Coach and mentor other team members to help improve QA effectiveness.Work with other department representatives to collaborate on joint projectsand initiatives .Implement industry best practices related to testing automation and tostreamline the QA Department. Test Analyst / Lead .Responsible for planning, developing and executing automated test systems,

VIJAY Page 93 Python Programming Language manual test plans and regressions test plans. .Identifying the Target Test Items to be evaluated by the test effort. .Defining the appropriate tests required and any associated Test Data. .Gathering and managing the Test Data. .Evaluating the outcome of each test cycle.

Test Engineer .Writing and executing test cases and Reporting defects. .Test engineers are also responsible for determining the best way a test canbe performed in order to achieve 100% test coverage of all components.

Unit test — Unit testing framework (If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.) The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. To achieve this, unittest supports some important concepts in an object-oriented way:

Test fixture A test fixture represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.

Test case A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. unittest provides a base class,TestCase, which may be used to create new test cases.

Test suite A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.

Test runner A test runner is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests. Basic example The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.

VIJAY Page 94 Python Programming Language

Here is a short script to test three string methods: import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper())

VIJAY Page 95