USIT-301-Python-Programming-munotes

Page 1

UNITI1INTRODUCTIONUnit Structure1.0Objectives1.1Introduction: The Python Programming Language1.2History1.3Features1.4Installing Python1.5Running Python program1.6Debugging1.6.1 Syntax Errors1.6.2 Runtime Errors1.6.3 SemanticErrors1.6.4 Experimental Debugging1.7Formal and Natural Languages1.8The Difference Between Brackets, Braces, and Parentheses1.9Summary1.10References1.11Unit End Exercise1.0OBJECTIVESAfter reading through this chapter, you will be able to–•To understand and use the basic of python.•To understand the historyand features ofpythonprogramming.•To understand the installation of python.•To handle the basis errors in python.•To understand the difference between brackets, braces andparenthesis.1.1 INTRODUCTION: THE PYTHONPROGRAMMING LANGUAGE•Pythonis an object-oriented, high level language, interpreted,dynamic and multipurpose programming language.•Python is notintended to work on special area such as webprogramming. That is why it is known asmultipurposebecause itcan be used with web, enterprise, 3D CAD etc.munotes.in

Page 2

•We don’t need to use data types to declare variable because itisdynamically typedso we can write a=10 to declare an integervalue in a variable.•Python makes the development and debuggingfastbecause there isno compilation step included in python development.1.2 HISTORY•Python was first introduced byGuido Van Rossumin1991at theNational Research Institute for Mathematics and ComputerScience, Netherlands.•Though the language was introduced in 1991, the developmentbegan in the 1980s. Previouslyvan Rossum worked on theABClanguageatCentrumWiskunde & Informatica(CWI)intheNetherlands.•TheABC language was capable ofexception handlingandinterfacing with theAmoebaoperating system. Inspired by thelanguage, Van Rossum first tried out making his own version of it.•Python is influenced by programming languages like: ABClanguage, Modula-3,Python is used for software development atcompanies and organizations such as Google, Yahoo, CERN,Industrial Light and Magic, and NASA.•Why the Name Python?•Python developer, Rossum always wanted the name of his newlanguage to be short, unique, and mysterious.•Inspired byMonty Python’s Flying Circus, a BBC comedy series,he named itPython.1.3 FEATURESThere are a lotof featuresprovided by python programming languageas follows1. Easy to Code:•Python is a very developer-friendly language which means thatanyone and everyone can learn to code it in a couple of hours ordays.•As compared to other object-oriented programming languages likeJava, C, C++, and C#, Python is one of the easiest to learn.2. Open Source and Free:•Python is an open-source programming language which means thatanyone can create and contribute to its development.•Python has an online forum where thousands of coders gather dailyto improve this language further. Along withthisPythonis free todownload and use in any operating system, be it Windows, Mac orLinux.munotes.in

Page 3

3. Support for GUI:•GUI or Graphical User Interface is one of the key aspects of anyprogramming language because it has the ability to add flair tocode and make the results more visual.•Python has support for a wide array of GUIs which can easily beimported to the interpreter, thus making this one of the mostfavorite languages for developers.4.Object-Oriented Approach:•One of the key aspects of Python is itsobject-orientedapproach. This basically means that Python recognizes theconcept of class and object encapsulation thus allowingprograms to be efficient in the long run.5.Highly Portable:•Suppose you are running Python on Windows and you need to shiftthe same to either a Mac or a Linux system, then you can easilyachieve the same in Python without having to worry aboutchanging the code.•This is not possible in otherprogramming languages, thus makingPython one of the most portable languages available in theindustry.6. Highly Dynamic•Python is one of the most dynamic languages available in theindustry today. What this basically means is that the type of avariableis decided at the run time and not in advance.•Due to the presence of this feature, we do not need to specify thetype of the variable during coding, thus saving time and increasingefficiency.7. Large Standard Library:•Out of the box, Python comesinbuilt with a large numberoflibrariesthat can be imported at any instance and be used in aspecific program.•The presence of libraries also makes sure that you don’t need towriteall the code yourself and can import the same from those thatalready exist in the libraries.1.4 INSTALLING PYTHON•To install Python, firstly download the Python distribution fromofficial website of python (www.python.org/ download).•Havingdownloaded the Python distribution now execute it.•Setting Path in Python:munotes.in

Page 4

Before starting working with Python, a specific path is to set to set pathfollow the steps:Right click on My Computer-->Properties-->Advanced Systemsetting-->Environment Variable-->NewIn Variable name write path and in Variable value copy path up to C://Python (i.e., path where Python is installed). Click Ok->Ok.1.5 RUNNING PYTHON PROGRAM:There are different ways of working in Python:1)How to Execute PythonProgram Using Command Prompt:If you want to create aPython file in .py extensionand run. You canuse the Windows command prompt to execute the Python code.Example:•Here is the simple code of Python given in the Python filedemo.py. It containsonlysingle line codeof Python which printsthe text “Hello World!” on execution.•So, how you can execute the Python program using the commandprompt. To see this, you have to firstopen the commandpromptusing the ‘window+r’ keyboard shortcut. Now, typetheword ‘cmd’ to open the command prompt.•This opens the command prompt with the screen as givenbelow.Change the directory locationto the location where youhave just saved your Python .py extension file.•We canuse the cmd command ‘cd’to change thedirectorylocation. Use ‘cd..’ to come out of directory and “cd” to comeinside of the directory. Get the file location where you saved yourPython file.
•To execute the Python file, you have touse the keyword‘Python’followed by the file name with extension.pySee theexample given in the screen above with the output of the file.
munotes.in

Page 5

2)Interactive Mode to Execute Python Program:•To execute the code directly in the interactive mode. You have toopen the interactive mode. Press the window button and typethetext “Python”.Click the “Python 3.7(32 bit) Desktop app”as givenbelow to open the interactive mode of Python.
•You cantype the Python codedirectly in the Python interactivemode. Here, in the image below contains the print program ofPython.•Press the enter buttonto execute the print code of Python. Theoutput gives the text “Hello World!” after you press the enterbutton.
•Type any code of Python you want to execute andrun directlyoninteractive mode.
munotes.in

Page 6

3) Using IDLE (Python GUI) toExecute Python Program:•Another useful methodof executing the Python code. Use thePython IDLE GUI Shell to execute the Python program onWindows system.•Open the Python IDLE shell by pressing the window button of thekeyboard. Type “Python” andclick the“IDLE (Python 3.7 32bit)”to open the Python shell.
•Create a Python file with.py extension and open it with the Pythonshell. The file looks like the image given below.
munotes.in

Page 7


•It contains the simple Python code which prints the text “HelloWorld!”. Inorder to execute the Python code, you have toopen the‘run’ menuandpress the ‘Run Module’option.
•Anew shell window will openwhich contains the output of thePython code. Create your own file and execute the Python codeusing this simple methodusing Python IDLE.
1.6 DEBUGGING•Debugging means the complete control over the programexecution. Developers use debugging to overcome program fromany bad issues.•debugging is a healthier process for the program and keeps thediseases bugs far away.•Python also allows developers to debug the programs using pdbmodule that comes with standard Python by default.•We just need to import pdb module in the Python script. Using pdbmodule, we can set breakpoints in the program to check the currentstatus
munotes.in

Page 8

•Wecan Change the flow of execution by using jump, continuestatements.1.6.1 Syntax Error:•Errors are the mistakes or faults performed by the user whichresults in abnormal working of the program.•However, we cannot detect programming errors before thecompilation of programs. The process of removing errors from aprogram is called Debugging.•A syntax error occurs when we do not use properly defined syntaxin any programming language. For example: incorrect arguments,indentation, use of undefined variables etc.Example:age=16if age>18:print ("you can vote”) # syntax error because of not using indentationelseprint ("you cannot vote”) #syntax error because of not usingindentation1.6.2 Runtime Errors:•The second type of error is a runtime error,so called because theerror does not appear until after the program has started running.•These errors are also called exceptions because they usuallyindicate that something exceptional (and bad) has happened.•Some examples of Python runtime errors:•division by zero•performing an operation on incompatible types•using an identifier which has not been defined•accessing a list element, dictionary value or object attributewhich doesn’t exist•trying to access a file which doesn’t exist1.6.3 SemanticErrors:•The third type of error is the semantic error. If there is a semanticerror in your program, it will run successfully in the sense that thecomputer will not generate any error messages, but it will not dothe right thing. It will do something else.•The problem is that the program you wrote is not the program youwanted to write. The meaning of the program (its semantics) iswrong.•Identifying semantic errors can be tricky because it requires you towork backward by looking at the output of the program and tryingto figure out what it is doing.munotes.in

Page 9

1.6.4 Experimental Debugging:•One of the most important skills you will acquire is debugging.Although it can be frustrating, debugging is one of the mostintellectually rich, challenging, and interesting parts ofprogramming.•Debugging is also like an experimental science. Once you have anidea about what is going wrong, you modify your program and tryagain.•For some people, programming and debugging are the same thing.That is, programming is the process ofgradually debugging aprogram until it does what you want.•The idea is that you should start with a program that doessomething and make small modifications, debugging them as yougo, so that you always have a working program.1.7 FORMAL AND NATURALLANGUAGES•Natural languages are the languages people speak, such as English,Spanish, and French. They were not designed by people (althoughpeople try to impose some order on them); they evolved naturally.•Formal languages are languages that are designed by people forspecific applications.•For example, the notation that mathematicians use is a formallanguage that is particularly good at denoting relationships amongnumbers and symbols. Chemists use a formal language to representthe chemical structure of molecules.•Programming languages are formal languages that have beendesigned to express computations.•Formal languages tend to have strict rules about syntax. Forexample, 3 + 3 = 6 is a syntactically correct mathematicalstatement.•Syntax rules comein two flavors, pertaining to tokens andstructure. Tokens are the basic elements of the language, such aswords, numbers, and chemical elements.•The second type of syntax rule pertains to the structure of astatement; that is, the way the tokens are arranged. The statement3+ = 3 is illegal because even though + and = are legal tokens, youcan’t have one right after the other.1.8 THE DIFFERENCE BETWEEN BRACKETS,BRACES, AND PARENTHESES:•Brackets [ ]:Brackets are used to define mutable data types such as list or listcomprehensions.munotes.in

Page 10

Example:To define a list with name as L1 with three elements 10,20 and 30>>> L1 = [10,20,30]>>> L1[10,20,30]•Brackets can be used for indexing and lookup of elementsExample:>>>L1[1] = 40>>>L1[10,40,30]Example: To lookup the element of list L1>>> L1[0]10•Brackets can be used to access the individual characters of a stringor to make string slicingExample:Lookup the first characters of stringstr>>>’mumbai’>>> str [0]‘m’Example: To slice a string>>> str [1:4]‘umb’Braces {}•Curly braces are used in python to define set or dictionary.Example:Create a set with three elements 10,20,30.>>> s1 = {10,20,30}>>> type(s1)Example:Create adictionary with two elements with keys, ‘rollno’ and ‘name’>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}>>> type(d1)•Brackets can be used to access the value of dictionary element byspecifying the key.>>> d1[‘rollno’]101munotes.in

Page 11

Parentheses( )•Parentheses can be used to create immutable sequence data typetuple.Example: Create a tuple named ‘t1’ with elements 10,20,30>>> t1= (10,20,30)>>> type(t1)•Parentheses can be used to define the parameters of functiondefinition andfunction call.Example:Multiply two numbers using a functiondef mul(a,b):returns a*bx=2y=3z=mul (2,3)print(x,’*’,y,’=’z)•In the function definition def mul(a,b) formal parameters arespecified using parentheses•In the function call z=mul (2,3)actual values are specified usingparenthesis.1.9 SUMMARY•In this chapter we studied Introduction, history, features of PythonProgramming Language.•We don’t need to use data types to declare variable because itisdynamically typedso we can writea=10 to declare an integervalue in a variable.•In this chapter we are more focused on types of errors in pythonlike syntax error, runtime error, semantic error and experimentaldebugging.•Execution of Python Program Using Command Prompt andInteractive Mode to Execute Python Program.•Also, we studied DifferencebetweenBrackets, Braces, andParentheses in python.1.10 REFERENCES•www.journaldev.com•www.edureka.com•www.tutorialdeep.communotes.in

Page 12

•www.xspdf.com•Think Python by Allen Downey 1st edition.•PythonProgramming for Beginners By Prof. Rahul E. Borate, Dr.Sunil Khilari, Prof. Rahul S. Navale.1.11 UNIT END EXERCISE1.Use a web browser to go to the Python website http: // python.org.This page contains information about Python and links toPython-related pages, and it gives you the ability to search the Pythondocumentation.For example, if you enter print in the search window, the first linkthat appears is the documentation of the print statement. At thispoint, not all of it will make sense to you, but it is good to knowwhere it is.2.Start the Python interpreter and type help () to start the online helputility. Or you can type help('print') to get information about theprint statement.munotes.in

Page 13

2VARIABLES AND EXPRESSIONUnit Structure2.0Objectives2.1Introduction2.2Values and Types2.2.1 Variables2.2.2 Variable Names and Keywords2.3Type conversion2.3.1Implicit Type Conversion2.3.2Explicit Type Conversion2.4Operatorsand Operands2.5Expressions2.6Interactive Mode and Script Mode2.7Order of Operations2.8Summary2.9References2.10Unit End Exercise2.0 OBJECTIVESAfter reading through this chapter, you will be able to–•To understand and use the basicdatatypesof python.•To understand thetype conversionof variables inpythonprogramming.•To understand theoperators and operands inpython.•Tounderstand the interactive mode and script modein python.•To understandthe order of operations in python.2.1 INTRODUCTION•Variables in a computer program are not quite like mathematicalvariables. They are placeholders forlocations in memory.•Memory values consists of a sequence of binary digits (bits) that canbe0or1, so all numbers are represented internally inbase 2.•Names of variables are chosen by the programmer.munotes.in

Page 14

•Python is case sensitive, somyVariableis not the sameasMyvariablewhich in turn is not the same asMyVariable.•With some exceptions, however, the programmer should avoidassigning names that differ only by case since human readers canoverlook such differences.2.2 VALUES AND TYPES•A value is one of the basic things aprogram works with, like a letter ora number. The values we have seen so far are 1, 2, and 'Hello, World!'.•These values belong to different types: 2 is an integer, and 'Hello,World!' is a string, so-called because it contains a “string” of letters.Youcan identify strings because they are enclosed in quotation marks.•If you are not sure what type a value has, the interpreter can tell you.>>>type ('Hello, World!')>>> type (17)•Not surprisingly, strings belong to the type strand integers belong tothe type int. Less obviously, numbers with a decimal point belong to atype called float, because these numbers are represented in a formatcalled floating-point.>>> type (3.2)•What about values like '17' and '3.2'? They look like numbers, but theyare in quotation marks like strings.>>> type (‘17’)>>> type (‘3.2’)They are strings.2.2.1 Variables:•One of the most powerful features of a programming language is theability to manipulatevariables. A variable is a name that refers to avalue.•An assignment statement creates new variables and gives them values:>>> message =‘Welcome to University of Mumbai’>>> n = 17>>> pi = 3.1415926535897932•The above example makes three assignments.The first assigns a stringto a new variable named message, the second gives the integer 17 to n,the third assigns the (approximate) value of π to pi.munotes.in

Page 15

•A common way to represent variables on paper is to write the namewith an arrow pointing to the variable’s value.>>> type(message)>>> type(n)>>> type(pi)2.2.2 Variable Names and Keywords:•Programmers generally choose names for their variables that aremeaningfulthey document what the variable is used for.•Variable names can be arbitrarily long. They can contain both lettersand numbers, but they have to begin with a letter. It is legal to useuppercase letters, but it is a good idea to begin variable names with alowercase letter.•The underscore character,_, can appear in a name. It is often used innames with multiple words, such as my_name orairspeed_of_unladen_swallow.•!!! >>> 76mumbai= 'bigcity'SyntaxError: invalid syntax>>>more@ = 1000000SyntaxError: invalid syntax>>> class = 'Advancedpython'SyntaxError: invalid syntax•76mumbai is illegal because it does not begin with a letter. more@ isillegal because it contains an illegal character, @. But what’s wrongwith class?•It turns out that class is one of Python’s keywords. The interpreter useskeywords to recognize the structure of the program, and they cannot beused as variable names.•Python has a lot of keywords. The number keeps on growing with thenew features comingin python.•Python 3.7.3 is the current version as of writing this book. There are35 keywords in Python 3.7.3 release.•We can get the complete list of keywords using python interpreter helputility.•$ python3.7>>> help ()help> keywordsmunotes.in

Page 16

 Here is a listof the Python keywords.Enter any keyword to get morehelp.FalseclassfromorNonecontinueglobalpassTruedefifraiseanddelimportreturnaselifintryassertelseiswhileasyncexceptlambdawithawaitfinallynonlocalyieldbreakfornot•You might want to keep this list handy. If the interpreter complainsabout one of your variable names and you don’t know why, see if it ison this list.2.3 TYPE CONVERSIONThe process ofconverting the value of one data type (integer, string, float,etc.) to another data type is called type conversion. Python has two typesof type conversion.2.3.1 Implicit Type Conversion:•In Implicit type conversion, Python automatically converts one datatype to another data type. This process doesn't need any userinvolvement.•example where Python promotes the conversion of the lower data type(integer) to the higher data type (float) to avoid data loss.Example1: Converting integer to floatnum_int= 123num_flo = 1.23num_new = num_int + num_floprint ("datatype of num_int:”, type(num_int))print ("datatype of num_flo:”, type(num_flo))print ("Value of num_new:”, num_new)print ("datatype of num_new:”, type(num_new))When we run the above program,the output will be:datatype of num_int: datatype of num_flo: Value of num_new: 124.23datatype of num_new: munotes.in

Page 17

 •In the above program, we add two variablesnum_intandnum_flo,storing the value innum_new.•We willlook at the data type of all three objects respectively.•In the output, we can see the data type ofnum_intis anintegerwhilethe data type ofnum_flois afloat.•Also, we can see thenum_newhas afloatdata type because Pythonalways converts smallerdata types to larger data types to avoid theloss of data.Example 2: Addition of string(higher) data type and integer(lower)datatypenum_int = 123num_str =“456”print (“Data type of num_int:”, type(num_int))print (“Data type of num_str:”,type(num_str))print(num_int+num_str)When we run the above program, the output will be:Data type of num_int: Data type of num_str: Traceback (most recent call last):File "python", line 7, in TypeError:unsupported operand type(s) for +: 'int' and 'str'•In the above program, we add two variablesnum_intandnum_str.•As we can see from the output, we gotTypeError. Python is not able touse Implicit Conversion in such conditions.•However, Python has a solution for these types of situations which isknown as Explicit Conversion.2.3.2ExplicitType Conversion:•In Explicit Type Conversion, users convert the data type of an objectto required data type. We use the predefined functionslikeint(),float(),str(), etc to perform explicit type conversion.•This type of conversion is also called typecasting because the usercasts (changes) the data type of the objects.Syntax:(expression)Typecasting can be done by assigning the required datatype function tothe expressionmunotes.in

Page 18

 Example 3: Addition of string and integer using explicit conversionnum_int = 123num_str = "456"print (“Data type of num_int:”, type(num_int))print (“Data type of num_str before Type Casting:”, type(num_str))num_str =int(num_str)print (“Data type of num_str after Type Casting:”, type(num_str))num_sum = num_int + num_strprint (“Sum of num_int and num_str:”, num_sum)print (“Data type of the sum:”, type(num_sum))When we run the above program, the output will be:Data type of num_int: Data type of num_str before Type Casting: Data type of num_str after Type Casting: Sum of num_int and num_str: 579Data type of the sum: •In the above program, we addnum_strandnum_intvariable.•We convertednum_strfrom string(higher) to integer(lower) typeusingint()function to perform the addition.•After convertingnum_strto an integer value, Python is able to addthese two variables.•We got thenum_sumvalue and data type to be an integer.2.4 OPERATORS AND OPERANDS:•Operators are particular symbols which operate on some values andproduce an output.•The values are known as Operands.Example:4+5=9Here 4 and 5 are Operands and (+), (=) signs are the operators.They produce the output 9•Python supports the following operators:Arithmetic Operators.munotes.in

Page 19

Relational Operators.Logical Operators.Membership Operators.Identity Operators•Arithmetic Operators:OperatorsDescription//Perform Floor division (givesinteger value after division)+To perform addition-To perform subtraction*To perform multiplication/To perform division%To return remainder after division (Modulus)**Perform exponent (raise to power)•Arithmetic Operator Examples:>>>10+2030>>> 20-1010>>> 10*220>>> 10/25>>> 10%31>>> 2**38>>> 10//33•Relational Operators:OperatorsDescriptionGreater than<=Less than or equal to>=Greater than or equal to==Equal to!=Not equal tomunotes.in

Page 20

•
 
  
>>> 10<20True>>> 10>20False>>> 10<=10True>>> 20>=15True>>> 5==6False>>>5!=6TrueLogical Operators:OperatorsDescriptionandLogical AND (When both conditions are true outputwillbe true)orLogical OR (If any one condition is true output will betruenotLogical NOT (Compliment the condition i.e., reverse)Logical Operators Examples:a=5>4 and 3>2print(a)Trueb=5>4 or 3<2print(b)Truec=not(5>4)print(c)FalseMembership Operators:OperatorsDescriptioninReturns true if a variable is in sequence of anothervariable, else false.not inReturns true if a variable is not in sequence ofanother variable, else false.munotes.in

Page 21

Membership Operators Examples:a=10b=20list= [10,20,30,40,50]if (a in list):print(“a is in given list”)else:print(“a is not in given list”)if (b not in list):print(“b is not given in list”)else:print(“b is given in list”)Output:>>>a is in given listb is given in listIdentity operators:OperatorsDescriptionisReturns true if identity of two operands are same, elsefalseis notReturns true if identity of two operands are not same,else false.Identity operators Examplesa=20b=20if (a is b):print(“a, b has same identity”)else:print(“a, b is different”)b=10if (a is not b):print(“a, b has different identity”)else:print(“a, b has same identity”)>>>a, b has same identitya, b has different identitymunotes.in

Page 22

2.5 EXPRESSIONS•An expression is a combination of values, variables, and operators.•A value all by itself is considered an expression, and so is a variable,so the following are all legal expressions (assuming that thevariable xhas been assigned a value):17xx + 17A statement is a unit of code that the Python interpreter can execute. Wehave seen two kinds of statement: print and assignment.•Technically an expression is also a statement, but it is probablysimplerto think of them as different things. The important differenceis that an expression has a value; a statement does not.2.6 INTERACTIVE MODE AND SCRIPT MODE:•One of the benefits of working with an interpreted language is that youcan test bits of code ininteractive mode before you put them in ascript. But there are differences between interactive mode and scriptmode that can be confusing.•For example, if you are using Python as a calculator, you might type>>> miles = 26.2>>> miles * 1.6142.182Thefirst line assigns a value to miles, but it has no visible effect. Thesecond line is an expression, so the interpreter evaluates it and displays theresult. So we learn that a marathon is about 42 kilometers.•But if you type the same code into a script and run it, you get nooutput at all.•In script mode an expression, all by itself, has no visible effect. Pythonactually evaluates the expression, but it doesn’t display the valueunless you tell it to:miles = 26.2print(miles * 1.61)This behavior can be confusing at first.•A script usually contains a sequence of statements. If there is morethan one statement, the results appear one at a time as the statementsexecute.•For examplemunotes.in

Page 23

print 1x = 2print xproduces the output12The assignment statementproduces no output.2.7 ORDER OF OPERATIONS•When more than one operator appears in an expression, the order ofevaluation depends on the rules of precedence. For mathematicaloperators, Python follows mathematical convention. The acronymPEMDAS is a useful way to remember the rules:•Parentheses have the highest precedence and can be used to force anexpression to evaluate in the order you want. Since expressions inparentheses are evaluated first,•2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also useparentheses tomake an expression easier to read, as in (minute * 100) / 60, even if itdoesn’t change the result.•Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4,and 3*1**3 is 3, not 27.•Multiplication and Division have the same precedence, which is higherthan Addition and Subtraction, which also have the same precedence.So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.•Operators with the same precedence are evaluated from left to right(except exponentiation). So, in the expression degrees / 2 * pi, thedivision happens first and the result is multiplied by pi. To divide by2π, you can use parentheses or write degrees / 2 / pi.•Example for Operator Precedence>>> 200/200+(100+100)201.0>>>>>> a=10>>> b=20>>> c=15>>> (a+b)*(c+b)-150900>>> (a+b)*c+b-150320>>> a+b**2410munotes.in

Page 24

>>> a or b + 2010>>> c or a + 2015>>> c and a + 2030>>> a and b + 2040>>> a>b>cFalse>>>2.8 SUMMARY•In this chapter we studied how to declare variables, expression andtypes of variables in python.•Weare more focuses on type conversion of variables in this chapterbasically two types of conversion are implicit type conversion andexplicit type conversion.•Also studied types of operators available in python like arithmetic,logical, relational and membership operators.•Focuses on interactive mode and script mode in pythonand order ofoperations.2.9 UNIT END EXERCISE1.Assume that we execute the following assignment statements:width = 17height = 12.0delimiter = '.'For each of the followingexpressions, write the value of the expressionand the type (of the value ofthe expression).1. width/22. width/2.03. height/34. 1 + 2 * 55. delimiter * 5munotes.in

Page 25

Use the Python interpreter to check your answers2.Type the following statements in the Python interpreter to see whatthey do:5x = 5x + 1Now put the same statements into a script and run it. What is theoutput? Modify the script by transforming each expression into a printstatement and then run itagain.3.Write a program add two numbers provided by the user.4.Write a program to find the square of number.5.Write a program that takes three numbers and prints their sum. Everynumber is given on a separate line.2.9 REFERENCES•Think Pythonby Allen Downey 1st edition.•Python Programming for Beginners By Prof. Rahul E. Borate, Dr.Sunil Khilari, Prof. Rahul S. Navale.•https://learning.rc.virginia.edu/•www.programiz.com•www.itvoyagers.inmunotes.in

Page 26

 3CONDITIONAL STATEMENTS,LOOPING, CONTROL STATEMENTSUnit Structure3.0Objectives3.1Introduction3.2Conditional Statements:3.2.1ifstatement3.2.2if-else,3.2.3if...elif...else3.2.4nested if–else3.3LoopingStatements:3.3.1forloop3.3.2whileloop3.3.3 nested loops3.4Control statements:3.4.1 Terminating loops3.4.2skipping specific conditions3.5Summary3.6References3.7Unit End Exercise3.0 OBJECTIVESAfter reading through this chapter, you will be able to–•To understand and use theconditional statementsinpython.•To understand theloop control inpythonprogramming.•To understand thecontrol statementsinpython.•To understand the concepts of python and able to apply it forsolving the complex problems.3.1 INTRODUCTION•In order to write useful programs, we almost always need theability to check conditions and change the behavior of the programaccordingly. Conditional statements give us this ability.•The simplest form is the if statement:if x > 0:print 'x is positive'munotes.in

Page 27

 The boolean expression after if is called the condition. If it is true,then the indented statement gets executed. If not, nothing happens.•if statements have the same structure as function definitions: aheader followed by an indented body. Statements like this arecalled compound statements.•There is no limit on the number of statements that can appear in thebody, but there has to be at least one. Occasionally, it is useful tohave a body with no statements. In that case, youcan use the passstatement, which does nothing.if x < 0:pass# need to handle negative values!3.2 CONDITIONAL STATEMENTSConditional Statement in Python perform differentcomputations or actions depending on whether a specific Booleanconstraint evaluates to true or false. Conditional statements are handledby IF statements in Python.Story of Two if’s:Consider the following if statement, coded in a C-like language:if (p > q){ p = 1;q = 2;}Now, look at the equivalent statement in the Python language:if p > q:p = 1q = 2what Python addswhat Python removes1) Parentheses are optionalif (x < y)---> if x < y2) End-of-line is end of statementC-like languagesPython languagex = 1;x = 13) End of indentation is end of blockWhy Indentation Syntax?A Few Special Casesa = 1;b = 2;print (a + b)munotes.in

Page 28

 You can chain together only simple statements, like assignments,prints, and function calls.3.2.1 if statement:Syntaxif test expression:statement(s)•Here, the program evaluates thetest expressionand will executestatement(s) only if the test expression isTrue.•If the test expression isFalse, the statement(s) is not executed.•In Python, the body oftheifstatement is indicated by theindentation. The body starts with an indentation and the firstunindented line marks the end.•Python interprets non-zero values asTrue.Noneand0areinterpreted asFalse.Example: Python if Statement# If the numberis positive, we print an appropriate messagenum = 3if num > 0:print (num, "is a positive number.")print ("This is always printed.")num =-1if num > 0:print (num, "is a positive number.")print ("This is also always printed.")When you runthe program, the output will be:3 is a positive number.This is always printed.This is also always printed.•In the above example,num > 0is the test expression.•The body ofifis executed only if this evaluates toTrue.•When the variablenumis equalto 3, test expression is trueandstatementsinside the body ofifare executed.•If the variablenumis equal to-1, test expression is false andstatements inside the body ofifare skipped.•Theprint()statement falls outside of theifblock(unindented).Hence, it is executed regardless of the test expression.munotes.in

Page 29

3.2.2 if-else statement:Syntaxif test expression:Body of ifelse:Body of else•Theif...elsestatement evaluatestest expressionand will executethe body ofifonly whenthe test condition isTrue.•If the condition isFalse, the body ofelseis executed. Indentation isused to separate the blocks.Example of if...else# Program checks if the number is positive or negative# And displays an appropriate messagenum = 3# Try these two variations as well.# num =-5# num = 0if num >= 0:print ("Positive or Zero")else:print ("Negative number")Output:Positive or Zero•In the above example, whennumis equal to 3, the test expressionis true and the bodyofifis executed and thebodyof else isskipped.•Ifnumis equal to-5, the test expression is false and the bodyofelseis executed and the body ofifis skipped.•Ifnumis equal to 0, the test expression is true and body ofifisexecuted andbodyofelse is skipped.3.2.3 if...elif...else Statement:Syntaxif test expression:Body of ifelif test expression:Body of elifelse:Body of elsemunotes.in

Page 30

•Theelifis short for else if. It allows us to check for multipleexpressions.•If the conditionforifisFalse, it checks the condition of thenextelifblock and so on.•If all the conditions areFalse, the body of else is executed.•Only one block among the severalif...elif...elseblocks is executedaccording to the condition.•Theifblock can haveonly oneelseblock. But it can havemultipleelifblocks.Example of if...elif...else:'''In this program,we check if the number is positive ornegative or zero anddisplay an appropriate message'''num = 3.4# Try these two variations as well:# num= 0# num =-4.5if num > 0:print ("Positive number")elif num == 0:print("Zero")else:print ("Negative number")•When variablenumis positive,Positive numberis printed.•Ifnumis equal to 0,Zerois printed.•Ifnumis negative,Negativenumberis printed.3.2.4 nested if–else:•We can have aif...elif...elsestatement insideanotherif...elif...elsestatement. This is called nesting in computerprogramming.•Any number of these statements can be nested inside one another.Indentation is the only way to figure out the level of nesting. Theycan get confusing, so they must be avoided unless necessary.Python Nested if Example'''In this program, we input a numbercheck if the number is positive ornegative or zero and displaymunotes.in

Page 31

an appropriatemessageThis time we use nested if statement'''num =float (input ("Enter a number: "))if num >= 0:if num == 0:print("Zero")else:print ("Positive number")else:print ("Negative number")Output1:Enter a number: 5Positive numberOutput2:Enter a number:-1Negative numberOutput3:Enter a number: 0Zero3.3 LOOPING STATEMENTS•In general, statements are executed sequentially: The firststatement in a function is executed first, followed by the second,and so on. There may be asituation when you need to execute ablock of code several number of times.•Programming languages provide various control structures thatallow for more complicated execution paths.•A loop statement allows us to execute a statement or group ofstatements multiple times.3.3.1 for loop:•The for loop in Python is used to iterate over a sequence(list,tuple,string) or other iterable objects. Iterating over asequence is called traversal.•Syntax of for Loopfor val in sequence:Body of formunotes.in

Page 32

•Here,valis the variable that takes the value of theitem inside thesequence on each iteration.•Loop continues until we reach the last item in the sequence. Thebody of for loop is separated from the rest of the code usingindentation.•Example: Python for Loop# Program to find the sum of all numbersstored in a list# List of numbersnumbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]# variable to store the sumsum = 0# iterate over the listfor val in numbers:sum = sum+valprint ("The sum is", sum)When you run the program, the output will be:The sum is48The range () function:•We can generate a sequence of numbers usingrange()function.range (10)will generate numbers from 0 to 9 (10numbers).•We can also define the start, stop and step size asrange (start,stop,step_size). step_size defaults to1,startto 0 andstop is end ofobjectif not provided.•This function does not store all the values in memory; it would beinefficient. So, it remembers the start, stop, step size and generatesthe next number on the go.•To force this function to output allthe items, we can use thefunctionlist().Example:print(range(10))print(list(range(10)))print (list (range (2, 8)))print (list (range (2, 20, 3)))Output:range (0, 10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][2, 3, 4, 5, 6, 7][2, 5, 8, 11, 14, 17]munotes.in

Page 33

•We canuse therange ()function inforloops to iterate through asequence of numbers. It can be combined with thelen ()function toiterate through a sequence using indexing. Here is an example.# Program to iterate through a list using indexingcity =['pune', 'mumbai', 'delhi']# iterate over the list using indexfor i in range(len(city)):print ("I like", city[i])Output:I like puneI like mumbaiI like delhifor loop with else:•Aforloop can have an optionalelseblock as well. Theelsepartisexecuted if the items in the sequence used in for loop exhausts.•Thebreakkeyword can be used to stop a for loop. In such cases,the else part is ignored.•Hence, a for loop's else part runs if no break occurs.Example:digits = [0, 1, 5]for i in digits:print(i)else:print("No items left.")When you run the program, the output will be:015No items left.•Here, the for loop prints items of the list until the loop exhausts.When the for-loop exhausts, it executes the block of code intheelseand printsNo items left.•Thisfor...elsestatement can be used with thebreakkeyword to runtheelseblock only when thebreakkeyword was not executed.Example:# program to display student's marks from recordstudent_name = 'Soyuj'marks ={'Ram': 90, 'Shayam': 55, 'Sujit': 77}munotes.in

Page 34

for student in marks:if student == student_name:print(marks[student])breakelse:print ('No entry with that name found.')Output:No entry with that name found.3.3.2 while loop:•The whileloop in Python is used to iterate over a block of code aslong as the test expression (condition) is true.•We generally use while loop when we don't know the number oftimes to iterate beforehand.•Syntax of while Loop in Pythonwhile test_expression:Body of while•In the while loop, test expression is checked first. The body of theloop is entered only if thetest_expressionevaluates toTrue.•After one iteration, the test expression is checked again. Thisprocess continues until thetest_expressionevaluates toFalse.•In Python, the body of the while loop is determined throughindentation.•The body starts with indentation and the first unindented line marksthe end.•Python interprets any non-zero value asTrue.Noneand0areinterpreted asFalse.Example: Python while Loop# Program to add natural# numbers up to# sum = 1+2+3+...+n# To take input from the user,# n = int (input ("Enter n: "))n = 10# initialize sum and countersum = 0i = 1while i <= n:sum = sum + ii = i+1 # update countermunotes.in

Page 35

# print the sumprint ("The sum is", sum)When you run the program, the output will be:Enter n: 10The sum is 55•In the above program, the test expression will beTrueas long asour counter variableiis less than or equal ton(10 in ourprogram).•We need to increase the value of the counter variable in the body ofthe loop. This is very important. Failing to do so will result in aninfinite loop (never-ending loop).While loop with else:•Same as withfor loops, while loops can also have anoptionalelseblock.•Theelsepart is executed if the condition in the while loopevaluates toFalse.•The while loop can be terminated with abreak statement. In suchcases, theelsepart is ignored. Hence, a while loop'selsepart runsif no break occurs and the condition is false.•Example:'''Example to illustratethe useof else statementwith the while loop'''counter = 0while counter < 3:print ("Inside loop")counter = counter + 1else:print ("Inside else")Output:Inside loopInside loopInside loopInside else•Here, we use a counter variable to printthe stringInside loopthreetimes.•On the fourth iteration, the condition inwhilebecomesFalse.Hence, theelsepart is executed.3.3.3NestedLoops:•Loops can be nested in Python similar to nested loops inotherprogramming languages.munotes.in

Page 36

 •Nested loop allows us to create one loop inside another loop.•It is similar tonested conditional statementslike nested ifstatement.•Nesting of loop can be implemented on both for loop and whileloop.•We can use any loop inside loop for example, for loop can havewhile loop in it.Nested for loop:•Forloop canhold anotherforloop inside it.•In above situation insideforloop will finish its execution first andthe control will be returned back to outsideforloop.Syntaxfor iterator in iterable:for iterator2 in iterable2:statement(s) of inside for loopstatement(s) of outside for loop•In this firstforloop will initiate the iteration and latersecondforloop will start its first iteration and till secondforloopcomplete its all iterations the control willnot be given tofirstforloop and statements of insidefor loop will be executed.•Once all iterations of insideforloop are completed then statementsof outsideforloop will be executed and next iteration fromfirstforloop will begin.Example1:of nested for loop in python:for i in range (1,11):for j in range (1,11):m=i*jprint (m, end=' ')print (“Table of“, i)Output:1 2 3 4 5 6 7 8 9 10 Tableof 12 4 6 8 10 12 14 16 18 20 Tableof 23 6 9 12 15 18 21 24 27 30 Tableof34 8 12 16 20 24 28 32 36 40 Tableof 45 10 15 20 25 30 35 40 45 50 Tableof 56 12 18 24 30 36 42 48 54 60 Tableof 67 14 21 28 35 42 49 56 63 70 Tableof 78 16 24 32 40 48 56 64 72 80 Tableof 8munotes.in

Page 37

 9 18 27 36 45 54 63 72 81 90 Tableof 910 20 30 40 5060 70 80 90 100 Tableof 10Example2:of nested for loop in python:for i in range (10):for j in range(i):print ("*”, end=’ ’ )print (" ")Output:** ** * ** * * ** * * * ** * * * * ** * * * * * ** * * * * * * ** * * * * * * * *Nested while loop:•Whileloop can hold anotherwhileloop inside it.•In above situation insidewhileloop will finish its execution firstand the control will be returned back to outsidewhileloop.Syntaxwhile expression:while expression2:statement(s) of inside while loopstatement(s) of outside while loop•In this firstwhileloop will initiate the iteration and latersecondwhileloop will start its first iteration and tillsecondwhileloop complete itsall iterations the control will not begiven to firstwhileloop and statements of insidewhileloop will beexecuted.•Once all iterations of insidewhileloop are completed thanstatements of outsidewhileloop will be executed and next iterationfrom firstwhileloop will begin.•It is also possible that if first condition inwhileloop expression isFalse then secondwhileloop will never be executed.Example1: Program to show nested while loopp=1munotes.in

Page 38

 while p<10:q=1while q<=p:print (p, end=" ")q+=1p+=1print (" ")Output:12 23 3 34 4 4 45 5 5 5 56 6 6 6 6 67 7 7 7 7 7 78 8 8 8 8 8 8 89 9 9 9 9 9 9 9 9Exampleb2: Program to nested while loopx=10while x>1:y=10while y>=x:print (x, end=" ")y-=1x-=1print(" ")Output:109 98 8 87 7 7 76 6 6 6 65 5 5 5 5 54 4 4 4 4 4 43 3 3 3 3 3 3 32 2 2 2 2 2 2 2 2munotes.in

Page 39

3.4 CONTROL STATEMENTS:•Control statements in python areused to control the order ofexecution of the program based on the values and logic.•Python provides us with three types of Control Statements:ContinueBreak3.4.1 Terminating loops:•The break statement is used inside the loop to exit out of the loop.Itis useful when we want to terminate the loop as soon as thecondition is fulfilled instead of doing the remaining iterations.•It reduces execution time. Whenever the controller encountered abreak statement, it comes out of that loop immediately.•Syntaxofbreakstatementfor element in sequence:if condition:breakExample:for num in range (10):if num > 5:print ("stop processing.")breakprint(num)Output:012345stop processing.3.4.2 skipping specificconditions:•Thecontinuestatement is used to skip the current iterationandcontinuewith the next iteration.•Syntax ofcontinuestatement:for element in sequence:if condition:continuemunotes.in

Page 40

Example of acontinuestatement:for num in range (3,8):if num == 5:continueelse:print(num)Output:34673.5 SUMMARY•In this chapter we studied conditional statements like if, if-else, if-elif-else and nested if-else statements for solving complexproblems in python.•Morefocuses on loop control in python basically two types ofloops available in python like while loop, for loop and nested loop.•Studied how to control the loop using break and continuestatements in order to skipping specific condition and terminatingloops.3.6UNIT END EXERCISE1.Print the squares of numbers from 1 to 10 using loop control.2.Write a Python program to print the prime numbers of up to agiven number, accept the number from the user.3.Write a Python program to print thefollowing pattern1234567891011121314154.Write a Python program to construct the following pattern, using anested for loop.** ** * ** * * ** * * * ** * * ** * ** **munotes.in

Page 41

5.Write a Python program to count the number of even and oddnumbersfrom a series of numbers.Sample numbers: numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)Expected Output:Number of even numbers: 5Number of odd numbers: 46.Write a Python program that prints all the numbers from 0 to 6except 3 and6Note: Use 'continue'statement.Expected Output: 0 1 2 4 57.Print First 10 natural numbers using while loop8.Print the following pattern11 21 2 31 2 3 41 2 3 4 59.Display numbers from-10 to-1 using for loop10.Print the following pattern*****************3.7REFERENCES•Think Python by Allen Downey 1st edition.•Python Programming for Beginners By Prof. Rahul E. Borate, Dr.Sunil Khilari, Prof. Rahul S. Navale.• "•!•  •https://pynative.communotes.in

Page 42

UNIT II4FUNCTIONSUnit Structure4.0Objectives4.1Introduction4.2Function Calls4.3Type Conversion Functions4.4Math Functions4.5Adding New Functions4.6Definitions and Uses4.6.1Flow of Execution4.6.2Parameters and Arguments4.6.3Variables and Parameters Are Local4.6.4Stack Diagrams4.7Fruitful Functions and Void Functions4.8Why Functions?4.9Importing with from, Return Values, Incremental Development4.10Boolean Functions4.11More Recursion, Leap of Faith,Checking Types4.12Summary4.13References4.14Unit End Exercise4.0 OBJECTIVESAfter reading through this chapter, you will be able to–•To understand and use thefunction calls.•To understand thetype conversion functions.•To understand themathfunction.•Toadding new function.•To understand theParameters and Arguments.•To understand the fruitful functions and void functions.•To understand the boolean functions, Recursion,checking typesetc.4.1 INTRODUCTION•One of the core principles of any programming language is, "Don'tRepeat Yourself". If you have an action that should occur manymunotes.in

Page 43

times, you can define that action once and then call that codewhenever you need to carry out that action.•We are already repeating ourselves in our code, so this is a goodtime to introduce simple functions. Functions mean less work forus as programmers, and effective use of functions results in codethat is less error.4.2 FUNCTION CALLSWhat is a function in Python?•InPython, a function is a group of related statements that performsa specific task.•Functions help break our program into smaller and modularchunks. As our program grows larger and larger, functions make itmore organized and manageable.•Furthermore, itavoids repetition and makes the code reusable.Syntax of Functiondef function_name(parameters):"""docstring"""statement(s)Above shown is a function definition that consists of the followingcomponents.1.Keyworddefthat marks the start of the function header.2.A function name to uniquely identify the function. Functionnaming follows the samerules of writing identifiers in Python.3.Parameters (arguments) through which we pass values to afunction. They are optional.4.A colon (:) to mark the end of the function header.5.Optional documentation string (docstring) to describe what thefunction does.6.One or more valid python statements that make up the functionbody. Statements must have the same indentation level (usually 4spaces).7.An optionalreturnstatement to return a value from the function.Example:def greeting(name):"""This function greets tothe person passed in asmunotes.in

Page 44

a parameter"""print ("Hello, " + name + ". Good morning!")How to call a function in python?•Once we have defined a function, we can call it from anotherfunction, program or even the Python prompt.•To call a function we simply type the function name withappropriate parameters.>>> greeting('IDOL')Hello, IDOL. Good morning!4.3 TYPE CONVERSION FUNCTIONS•The process of converting the value of one data type (integer,string, float, etc.) to another data type is called type conversion.Python has two types of type conversion.1. Implicit Type Conversion2. Explicit Type Conversion1. Implicit Type Conversion:•In Implicit type conversion, Python automatically converts onedata type to another data type. This process doesn't need any userinvolvement.•Let's see an example where Python promotes the conversion of thelower data type (integer) to the higher data type (float) to avoiddata loss.Example1: Converting integer to floatnum_int = 123num_float = 1.23num_new = num_int +num_floatprint (“datatype of num_int:”, type(num_int))print (“datatype of num_float:” type(num_float))print (“Value of num_new:”, num_new)print (“datatype of num_new:”, type(num_new))Output:datatype of num_int: datatype of num_float: Value of num_new: 124.23datatype of num_new: munotes.in

Page 45

Example 2: Addition of string(higher) data type and integer(lower)datatypenum_int = 123num_str = "456"print ("Data type of num_int:”, type(num_int))print ("Data type of num_str:”, type(num_str))print(num_int+num_str)Output:Data type of num_int: Data type of num_str: Traceback (most recent call last):File "python", line 7, in TypeError: unsupported operand type(s) for +: 'int' and'str'•In the above program,•We add two variables num_int and num_str.•As we can see from the output, we got TypeError. Python is notable to use Implicit Conversion in such conditions.•However, Python has a solution for these types of situations whichis known as Explicit Conversion.2. Explicit Type Conversion:•In Explicit Type Conversion, users convert the data type of anobject to required data type. We use the predefined functions likeint(), float(), str(), etc to perform explicit type conversion.•This type of conversion is also called typecasting because the usercasts (changes) the data type of the objects.Syntax:(expression)Example 3: Addition of string and integer using explicit conversionnum_int = 123num_str = "456"print("Data type of num_int:”, type(num_int))print ("Data type of num_str before Type Casting:”, type(num_str))num_str = int(num_str)print ("Data type of num_str after Type Casting:”, type(num_str))num_sum = num_int + num_strmunotes.in

Page 46

print ("Sum of num_int and num_str:”, num_sum)print ("Data type of the sum:”, type(num_sum))Output:Data type of num_int: Data type of num_str before Type Casting: Data type of num_str after Type Casting: Sum of num_int and num_str: 579Datatype of the sum: •Type Conversion is the conversion of object from one data type toanother data type.•Implicit Type Conversion is automatically performed by thePython interpreter.•Python avoids the loss of data in Implicit Type Conversion.•Explicit Type Conversion is also called Type Casting, the datatypes of objects are converted using predefined functions by theuser.•In Type Casting, loss of data may occur as we enforce the object toa specific data type.4.4 MATH FUNCTIONS•The math module is a standard module in Python and is alwaysavailable. To use mathematical functions under this module, youhave to import the module using import math.•For example# Square root calculationimport mathmath.sqrt(4)•Functions in Python Math ModulePi is a well-known mathematical constant, which is defined as theratio of the circumference to the diameter of a circle and its value is3.141592653589793.>>> import math>>>math.pi3.141592653589793•Another well-known mathematical constant defined inthe mathmodule ise. It is calledEuler's numberand it is a base of thenatural logarithm. Its value is 2.718281828459045.>>> import math>>>math.e2.718281828459045munotes.in

Page 47

 •The math module contains functions for calculating varioustrigonometric ratios for a given angle. The functions (sin, cos, tan,etc.) need the angle in radians as an argument. We, on the otherhand, are used to express the angle in degrees. The math modulepresents two angle conversion functions:degrees ()andradians (),to convert the angle from degrees to radians and vice versa.>>> import math>>>math.radians(30)0.5235987755982988>>>math.degrees(math.pi/6)29.999999999999996•math.log()The math.log() method returns the natural logarithm of a givennumber. The natural logarithm is calculated to the base e.>>> import math>>>math.log(10)2.302585092994046•math.exp()The math.exp() method returns a float number after raising e to thepower of the given number. In other words, exp(x) gives e**x.>>> import math>>>math.exp(10)22026.465794806718•math.pow()The math.pow() method receives two float arguments, raises the first tothe second and returns the result. In other words, pow(4,4) isequivalent to 4**4.>>> import math>>>math.pow(2,4)16.0>>> 2**416•math.sqrt()The math.sqrt() method returns the square root of a given number.>>> import math>>>math.sqrt(100)10.0munotes.in

Page 48


>>>math.sqrt(3)1.73205080756887724.5 ADDING NEW FUNCTIONS•So far, we have only been using the functions that come withPython, but it is also possible to add new functions.•Afunction definitionspecifies the name of a new function and thesequence of statements that execute when the function is called.•Example:def print_lyrics():print ("I'm a lumberjack, and I'm okay.")print ("I sleep all night and I work all day.")•defis a keyword that indicates that this is a function definition. Thename of the function isprint_lyrics. The rules for function namesare the same as for variable names: letters, numbers and somepunctuation marks are legal, but the first character can’t be anumber. You can’t use a keyword as the name of a function, andyou should avoid having a variable and a function with the samename.•The empty parentheses after the name indicate that this functiondoesn’t take any arguments.•The first line of the function definition is called theheader; the restis called thebody. The header has to end with a colon and the bodyhas to be indented.•By convention, the indentation is always four spaces .The body cancontain any number of statements.•The strings in the print statements are enclosed in double quotes.Single quotes and double quotes do the same thing; most peopleuse single quotes except in cases like this where a single quoteappears in the string.•Once you have defined a function, you can use it inside anotherfunction. For example, to repeat the previous refrain, we couldwrite a function calledrepeat_lyrics:def repeat_lyrics():print_lyrics()print_lyrics()And then call repeat_lyrics:>>> repeat_lyrics()I'm a lumberjack, and I'm okay.I sleep all night and I work all day.I'm a lumberjack, and I'm okay.I sleep all night and I work all day.munotes.in

Page 49

 4.6 DEFINITIONS AND USES•Pulling together the code fragments from the previous section, thewhole program looks like this:def print_lyrics ():print ("I'm a lumberjack, and I'm okay.")print ("I sleep all night and I work all day.")def repeat_lyrics ():print_lyrics ()print_lyrics ()repeat_lyrics ()•Thisprogramcontains two functiondefinitions:print_lyricsandrepeat_lyrics. Function definitions getexecuted just like other statements, but the effect is to createfunction objects.•The statements inside the function do not get executed until thefunction is called, and the function definition generatesno output.4.6.1 Flow of Execution:•In order to ensure that a function is defined before its first use, youhave to know the order in which statements are executed, which iscalled theflow of execution.•Execution always begins at the first statement ofthe program.Statements are executed one at a time, in order from top to bottom.•Function definitions do not alter the flow of execution of theprogram, but remember that statements inside the function are notexecuted until the function is called.•A function call is like a detour in the flow of execution. Instead ofgoing to the next statement, the flow jumps to the body of thefunction, executes all the statements there, and then comes back topick up where it left off.•When you read a program, you don’talways want to read from topto bottom. Sometimes it makes more sense if you follow the flowof execution.4.6.2 Parameters and Arguments:•Some of the built-in functions we have seen require arguments. Forexample, when you callmath.sinyou pass a number as anargument. Some functions take more than oneargument:math.powtakes two, the base and the exponent.munotes.in

Page 50

•Inside the function, the arguments are assigned to variablescalledparameters. Here is an example of a user-defined functionthat takes anargument.•def print_twice(bruce):print(bruce)print(bruce)•This function assigns the argument to a parameter namedbruce.When the function is called, it prints the value of the parametertwice.>>> print_twice('Spam')SpamSpam>>> print_twice (17)1717>>> print_twice(math.pi)3.141592653593.14159265359•The same rules of composition that apply to built-in functions alsoapply to user-defined functions, so we can use any kind ofexpression as an argument forprint_twice.>>> print_twice ('Spam '*4)Spam SpamSpamSpamSpam SpamSpamSpam>>> print_twice(math.cos(math.pi))-1.0-1.0The argument is evaluated before the function is called, so in theexamples the expressions'Spam '*4andmath.cos(math.pi)are onlyevaluated once.4.6.3 Variables andParameters Are Local:•When you create a variable inside a function, it islocal, whichmeans that it only exists inside the function.•For exampledef cat_twice(part1, part2):cat = part1 + part2print_twice(cat)munotes.in

Page 51

This function takes two arguments,concatenates them, and prints theresult twice. Here is an example that uses it:>>> line1 = 'Bing tiddle '>>> line2 = 'tiddle bang.'>>> cat_twice(line1, line2)Bing tiddle tiddle bang.Bing tiddle tiddle bang.•Whencat_twiceterminates, the variablecatis destroyed. If we tryto print it, we get an exception:>>> print catNameError: name 'cat' is not defined•Parameters are also local. For example, outsideprint_twice, there isno such thing asbruce.4.6.4 Stack Diagrams:•To keep track of whichvariables can be used where, it issometimes useful to draw astack diagram. Like state diagrams,stack diagrams show the value of each variable, but they also showthe function each variable belongs to.•Each function is represented by aframe. A frame isa box with thename of a function beside it and the parameters and variables of thefunction inside it. The stack diagram for the previous example isshown in Figure.
Fig. Stack Diagram•The frames are arranged in a stack that indicates which functioncalled which, and so on. In this example,print_twicewas calledbycat_twice, andcat_twicewas called by__main__, which is aspecial name for the topmost frame. When you create a variableoutside of any function, it belongs to__main__.
munotes.in

Page 52

•Each parameter refers to the same value as its correspondingargument. So,part1has the same value asline1,part2has the samevalue asline2, andbrucehas the same value ascat.•If an error occurs during a function call, Python prints the name ofthe function, and the name of the function that called it, and thename of the function that calledthat, all the way back to__main__.4.7 FRUITFUL FUNCTIONS AND VOID FUNCTIONS•Some of the functions we are using, such as the math functions,yield results; for lack of a bettername, I call themfruitfulfunctions. Other functions, likeprint_twice, perform an action butdon’t return a value. They are calledvoid functions.•When you call a fruitful function, you almost always want to dosomething with the result; for example, you might assign it to avariable or use it as part of an expression:x = math.cos(radians)golden = (math.sqrt(5) + 1) / 2When you call a function in interactive mode, Python displaysthe result:>>>math.sqrt(5)2.2360679774997898•But in a script, if you call a fruitful function all by itself, the returnvalue is lost forevermath.sqrt(5)This script computes the square root of 5, but since it doesn’t store ordisplay the result, it is not very useful.•Void functions might display something on the screen orhavesome other effect, but they don’t have a return value. If you try toassign the result to a variable, you get a special value calledNone.>>> result = print_twice('Bing')BingBing>>> print(result)NoneThe value None is not the same as the string'None'. It is a specialvalue that has its own type:>>> print type(None)•The functions we have written so far are all void.munotes.in

Page 53

4.8 WHY FUNCTIONS?•It may not be clear why it is worth the trouble to divide a programinto functions. Thereare several reasons:•Creating a new function gives you an opportunity to name a groupof statements, which makes your program easier to read and debug.•Functions can make a program smaller by eliminating repetitivecode. Later, if you make a change, you only have to make it in oneplace.•Dividing a long program into functions allows you to debug theparts one at a time and then assemble them into a working whole.•Well-designed functions are often useful for many programs. Onceyou write and debug one, you can reuse it.4.9 IMPORTING WITH FROM, RETURN VALUES,INCREMENTAL DEVELOPMENT•Importing withfrom:Python provides two ways to import modules, we have already seenone:>>> import math>>> print math>>> print math.pi3.14159265359•If you importmath, you get a module object namedmath. Themodule object contains constants likepiand functionslikesinandexp.But if you try to accesspidirectly, you get an error.>>> print piTraceback (most recent call last):File "", line 1, in NameError: name 'pi' is not defined•As an alternative, you can import an object from a module like this:>>> from math import piNow you can accesspidirectly, without dot notation.>>> print pi3.14159265359Or you can use the star operator to importeverythingfrom the module:>>> from math import *munotes.in

Page 54

>>> cos(pi)-1.0•The advantage of importing everything from the math module isthat your code can be more concise.•The disadvantage is that there might be conflicts betweennamesdefined in different modules, or between a name from a moduleand one of your variables.4.10 BOOLEAN FUNCTIONS•Syntax for boolean function is as followsBool([value])•As we seen in the syntax that the bool() function can take a singleparameter(value that needs to be converted). It converts the givenvalue to True or False.•If we don’t pass any value to bool() function, it returns False.•bool() function returns a boolean value and this functionreturnsFalsefor all the following values1. None2. False3. Zero number of any type such as int, float and complex. Forexample: 0, 0.0, 0j4. Empty list [], Empty tuple (), Empty String ”.5. Empty dictionary {}.6. objects of Classes that implements __bool__() or __len()__method, which returns 0 or False•bool() function returnsTruefor all other values except the valuesthat are mentioned above.•Example: bool() functionIn the following example, we will check the output of bool() functionfor the given values. We have different values of differentdatatypesand we are printing the return value of bool() function in theoutput.# empty listlis = []print(lis,'is',bool(lis))# empty tuplet = ()print(t,'is',bool(t))# zero complexnumbermunotes.in

Page 55

c = 0 + 0jprint(c,'is',bool(c))num = 99print(num, 'is', bool(num))val = Noneprint(val,'is',bool(val))val = Trueprint(val,'is',bool(val))# empty stringstr = ''print(str,'is',bool(str))str = 'Hello'print(str,'is',bool(str))Output:[] isFalse() is False0j is False99 is TrueNone is FalseTrue is Trueis FalseHello is True4.11 MORE RECURSION, CHECKING TYPES:•What is recursion?Recursion is the process of defining something in terms of itself.A physical world example would be toplace two parallel mirrorsfacing each other. Any object in between them would be reflectedrecursively.•In Python, we know that afunctioncan call other functions. It iseven possiblefor the function to call itself. These types of constructare termed as recursive functions.munotes.in

Page 56

•Following is an example of a recursive function to find the factorialof an integer.Factorial of a number is the product of all the integers from 1 to thatnumber. For example, the factorial of 6 (denoted as 6!)is1*2*3*4*5*6 = 720.•Example of a recursive functiondef factorial(x):"""This is a recursive functionto find the factorial of an integer"""if x == 1:return 1else:return (x * factorial(x-1))num = 3print("The factorial of", num, "is", factorial(num))Output:The factorial of 3 is 6•In the above example,factorial ()is a recursive function as it callsitself.When we call this function with a positive integer, it willrecursively call itself by decreasing the number.•Each function multiplies the number with the factorial of thenumber below it until it is equal to one. This recursive call can beexplained in the following steps.factorial (3) # 1st call with 33 * factorial (2) # 2nd call with 2
munotes.in

Page 57

 3 * 2 * factorial (1) # 3rd call with 13 * 2 * 1 # return from 3rd call as number=13 * 2 # return from2nd call6 # return from 1st call4.12 SUMMARY•In this chapter we studied function call, type conversion functionsin Python Programming Language.•In this chapter we are more focused on math function and addingnew function inpython.•Elaborating on definitions and uses of function, parameters andarguments in python.•Also studied fruitful functions and void functions, importing withfrom, boolean functions and recursion in python.4.14 UNIT END EXERCISE1.Python providesa built-in function calledlenthat returns the lengthof a string, so the value oflen('allen')is 5.Write a function namedright_justifythat takes a string namedsasa parameter and prints the string with enough leading spaces so thatthe last letterof the string is in column 70 of the display.>>> right_justify('allen')allen2.Write a Python function to sum all the numbers in a list.Goto theeditorSample List: (8, 2, 3, 0, 7)Expected Output: 203.Write a Python program to reverse a stringSample String: "1234abcd"Expected Output: "dcba4321"4.Write a Python function to calculate the factorial of a number (anon-negativeinteger). The function accepts the number as anargument.5.Write a Python program to print the even numbers from a givenlist.SampleList:[1, 2, 3, 4, 5, 6, 7, 8, 9]ExpectedResult:[2, 4, 6, 8]munotes.in

Page 58


4.13 REFERENCES•https://www.tutorialsteacher.com/python/math-module•https://greenteapress.com/thinkpython/html/thinkpython004.html•https://beginnersbook.com/•https://www.programiz.com/python-programming/recursion•www.journaldev.com•www.edureka.com•www.tutorialdeep.com•www.xspdf.com•Think Python by Allen Downey 1st edition.munotes.in

Page 59

 5STRINGSUnitStructure5.1A String is a Sequence5.2Traversal with a for Loop5.3String Slices5.4Strings Are Immutable5.5Searching5.6Looping and Counting5.7String Methods5.8The in Operator5.9String Comparison5.10String Operations5.11Summary5.12Questions5.13References5.0OBJECTIVES•To learn how to crate string in Python•To study looping and counting in Python•To write programs for creating string methods in Python•To understand various operators and string operation of Python•Tolearn the string traversal with a for loop in Python5.1 A STRING IS A SEQUENCEThere are numerous types of sequences in Python. Strings areaspecial type of sequence that can only store characters, and they have aspecial notation.Strings aresequencesof characters and are immutable.A string is asequenceof characters. We can access the charactersone at a time with the bracket operator:>>>food = 'roti'>>>letter = food[1]The second statement retrieves the character at index position onefromthefoodvariable and assigns it to thelettervariable.The expressionmunotes.in

Page 60

in brackets is called anindex. The index indicates which character in thesequence you required.Example.‘I want to read book’. This is astring, It has been surrounded in singlequotes.Declaring Python StringString literals in PythonString literals are surrounded bysinglequotesordouble-quotes.‘I want to read book’“I want to read book’”You can also surround them withtriplequotes(groupsof3singlequotesordoublequotes).“””I want to read book’””””’ I want to read book’”’Or usingbackslashes.>> ‘Thank\Good Morning Sir !’‘ThanksGood Morning Sir!’You cannotstartastringwith asinglequoteandendit with adoublequote..But if you surround a string withsingle quotes and also want to use singlequotes as part of the string, you have to escape it with abackslash(\).‘Send message to Madam\’s son ’This statement causes aSyntaxError:‘Send message to Madam’s son’You can also do this with double-quotes. If you want to ignoreescapesequences, you can create arawstringby using an‘r’or‘R’prefixwiththe string.Common escape sequences:•\\Backslash•\n Linefeed•\t Horizontal tab•\’ Single quotes•\” Double quotesWe can assign a string to avariable.munotes.in

Page 61

name=’Sunil’You can also create a string with thestr()function.>>> str(567)Output:‘567’>>> str('Shri')Output:‘Shri’5.2. TRAVERSAL AND THE FOR LOOP: BY ITEMA lot of computations involve processing a collection one item at atime. For strings this means that we would like to process one character ata time. Often we start at the beginning, select each character in turn, dosomething to it, and continue until the end. This pattern of processing iscalled a traversal.We have previously seen that the for statement can iterate over theitems of a sequence (a list of names in the case below).for aname in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi","Paris"]:invitation = "Hi " + aname + ". Please come to my party on Saturday!"print(invitation)Recall that the loop variable takes on each value in the sequence ofnames. The body is performed once for each name. The same was true forthe sequence of integers created by the range function.for avalue in range(10):print(avalue)Since a string is simply a sequence of characters, the for loop iterates overeach character automatically.for achar in "Go Spot Go":print(achar)munotes.in

Page 62

The loop variable achar is automatically reassigned each characterin the string “Go Spot Go”. Wewill refer to this type of sequence iterationas iteration by item. Note that it is only possible to process the charactersone at a time from left to right.Check your understandingstrings-10-4:How many times is the word HELLO printed by thefollowing statements?s = "python rocks"for ch in s:print("HELLO")Ans-Yes, there are 12 characters, including the blank.strings-10-5:How many times is the word HELLO printed by thefollowing statements?s = "python rocks"for ch in s[3:8]:print("HELLO")Ans-Yes, The blank is part of the sequence returned by slice5.3. STRING SLICESPython slice string syntax is:str_object[start_pos:end_pos:step]The slicing starts with the start_pos index (included) and ends atend_pos index (excluded). The step parameter is used to specify the stepsto take from start to end index.Python String slicing always follows this rule: s[:i] + s[i:] == s for anyindex ‘i’.All these parameters are optional–start_pos default value is 0, theend_pos default valueis the length of string and step default value is 1.Let’s look at some simple examples of string slice function to createsubstring.s = 'HelloWorld'print(s[:])print(s[::])munotes.in

Page 63

Output:HelloWorldHelloWorldNote that since none of the slicing parameterswere provided, the substringis equal to the original string.Let’s look at some more examples of slicing a string.s = 'HelloWorld'first_five_chars = s[:5]print(first_five_chars)third_to_fifth_chars = s[2:5]print(third_to_fifth_chars)Output:HelloLloNote that index value starts from 0, so start_pos 2 refers to the thirdcharacter in the string.Reverse a String using SlicingWe can reverse a string using slicing by providing the step value as-1.s = 'HelloWorld'reverse_str = s[::-1]print(reverse_str)Output:dlroWolleHLet’s look at some other examples of using steps and negative indexvalues.s1 = s[2:8:2]print(s1)Output:looHere the substring contains characters from indexes 2,4 and 6.s1 = s[8:1:-1]print(s1)munotes.in

Page 64

Output:lroWoll5.4STRINGS ARE IMMUTABLEThe standard wisdom is that Python strings are immutable. Youcan't change a string's value, only the reference to the string. Like so:x = "hello"x = "goodbye" # New string!Which implies that each time you make a change to a stringvariable, you are actually producing a brand new string. Because of this,tutorials out there warn you to avoid string concatenation inside a loop andadvise using join instead for performance reasons. Even the officialdocumentation says so!This iswrong. Sort of.There is a common case for when strings in Python are actuallymutable. I will show you an example by inspecting the string object'sunique ID using the builtin id() function, which is just the memoryaddress. The number is different foreach object. (Objects can be sharedthough, such as with interning.)An unchanging article alludes to the item which is once made can’tchange its worth all its lifetime. Attempt to execute the accompanyingcode:name_1 = "Aarun"name_1[0] = 'T'You will get a mistake message when you need to change the substance ofthe string.Traceback (latest call last):Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, inname_1[0] = 'T'TypeError: 'str' object doesn't uphold thing taskArrangementOne potential arrangement is to make another string object with vitalalterations:name_1 = "Aarun"name_2 = "T" + name_1[1:]print("name_1 = ", name_1, "and name_2 = ", name_2)munotes.in

Page 65

name_1 = Aarun and name_2 = TarunTo watch that they are variousstrings, check with the id() work:name_1 = "Aarun"name_2 = "T" + name_1[1:]print("id of name_1 = ", id(name_1))print("id of name_2 = ", id(name_2))Output:id of name_1 = 2342565667256id of name_2 = 2342565669888To see more about the idea of string permanence, think about theaccompanying code:name_1 = "Aarun"name_2 = "Aarun"print("id of name_1 = ", id(name_1))print("id of name_2 = ", id(name_2))Output:id of name_1 = 2342565667256id of name_1 with new value = 23425656686565.5 SEARCHINGSearching is a very basic necessity when you store data in differentdata structures. The simplest approach is to go across every element in thedata structure and match it with the value you are searching for.This isknown as Linear search. It is inefficient and rarely used, but creating aprogram for it gives an idea about how we can implement some advancedsearch algorithms.Linear Search:In this type of search, a sequential search is made over all itemsone by one. Every item is checked and ifa match is found then thatparticular item is returned, otherwise the search continues till the end ofthe data structure.Exampledef linear_search(values, search_for):search_at = 0search_res = Falsemunotes.in

Page 66

# Match the value with each data elementwhile search_at < len(values) and search_res is False:if values[search_at] == search_for:search_res = Trueelse:search_at = search_at + 1return search_resl = [64, 34, 25, 12, 22, 11, 90]print(linear_search(l, 12))print(linear_search(l, 91))Output:When the above code is executed, it produces the following result−TrueFalseInterpolation Search:This search algorithm works on the probing position of therequired value. For this algorithm to work properly, the data collectionshould be in a sorted form and equally distributed.Initially, the probeposition is the position of the middle most item of the collection.If amatch occurs, then the index of the item is returned.If the middle item isgreater than the item, then the probe position is again calculated in thesub-array to the right of the middle item. Otherwise, the item is searchedin the subarray to the left of the middle item. This process continues on thesub-array as well until the size of subarray reduces to zero.ExampleThere is a specific formula to calculate the middle position which isindicated in the program below−def intpolsearch(values,x ):idx0 = 0idxn = (len(values)-1)while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:# Find the mid pointmid = idx0 +\int(((float(idxn-idx0)/( values[idxn]-values[idx0]))* ( x-values[idx0])))# Compare the value at mid point with search valueif values[mid] == x:munotes.in

Page 67

 return "Found "+str(x)+" at index "+str(mid)if values[mid] < x:idx0 = mid + 1return "Searched element not in the list"l = [2, 6, 11, 19, 27, 31, 45, 121]print(intpolsearch(l, 2))Output:Found 2 at index 05.6LOOPING AND COUNTINGThe following program counts the number of times the letter “r” appearsin a string:word = 'raspberry'count = 0for letter in word:if letter == 'r':count = count + 1print(count)This program demonstrates another pattern of computation called acounter. The variable count is initialized to 0 and then incremented eachtime an “r” is found. When the loop exits, count contains the result: thetotal number of r’s.s = "peanut butter"count = 0for char in s:if char == "t":count = count + 1print(count)Output:The letter t appears 3 times in "peanut butter".5.7STRING METHODSPython has a set of built-in methods that you can use on strings.Note:All string methods returns new values. They do not change theoriginal string.munotes.in

Page 68


MethodDescriptioncapitalize()Convertsthe first character to upper casecasefold()Converts string into lower casecenter()Returns a centered stringcount()Returns the number of times a specified value occurs ina stringencode()Returns an encoded version of the stringendswith()Returns true if the string ends with the specified valueexpandtabs()Sets the tab size of the stringfind()Searches the string for a specified value and returns theposition of where it was foundformat()Formats specified values in a stringformat_map()Formats specified values in a stringindex()Searches the string for a specified value and returns theposition of where it was foundisalpha()Returns True if all characters in the string are in thealphabetisdecimal()Returns True if all characters in the string are decimalsisdigit()Returns True if all characters in the string are digitsisidentifier()Returns True if the string is an identifierislower()Returns True if all characters in the string are lowercaseisnumeric()Returns True if allcharacters in the string are numericisprintable()Returns True if all characters in the string are printableisupper()Returns True if all characters in the string are uppercasejoin()Joins the elements of an iterable to the end of the stringljust()Returns a left justified version of the stringlower()Converts a string into lower caselstrip()Returns a left trim version of the stringmaketrans()Returns a translation table to be used in translationspartition()Returns a tuple where the string is parted into threepartsreplace()Returns a string where a specified value is replaced witha specified valuerfind()Searches the string for a specified value and returns thelast position of where it was foundrindex()Searches the string for aspecified value and returns thelast position of where it was foundrjust()Returns a right justified version of the stringrsplit()Splits the string at the specified separator, and returns alistrstrip()Returns a right trim version of the stringsplit()Splits the string at the specified separator, and returns alistsplitlines()Splits the string at line breaks and returns a liststartswith()Returns true if the string starts with the specified valuestrip()Returns a trimmed version of the stringmunotes.in

Page 69

 swapcase()Swaps cases, lower case becomes upper case and viceversaNote:All string methods returns new values. They do not change theoriginal string.5.8. THE IN OPERATORNot let us take an example to get a better understanding of the in operatorworking.x in yHere “x” is the element and “y” is the sequence where membership isbeing checked.Let’s implement a simple Python code to demonstrate the use of the inoperator and how the outputs would look like.vowels = ['A', 'E', 'I', 'O', 'U']ch = input('Please Enter a Capital Letter:\n')if ch in vowels:print('You entered a vowel character')else:print('You entered a consonants character')We can use the “in” operator with Strings and Tuples too because they aresequences.>>> name='JournalDev'>>> 'D' in nameTrue>>> 'x' in nameFalse>>> primes=(2,3,5,7,11)>>> 3 in primesTrue>>> 6 in primesFalseCan we use Python “in” Operator with a Dictionary?Let’s see what happens when we use “in” operator with a dictionary.dict1 = {"name": "Pankaj", "id": 1}print("name" in dict1) # Truemunotes.in

Page 70

print("Pankaj" in dict1) # FalseIt looks like the Python “in” operator looks for the element in thedictionary keys.5.9 STRING COMPARISONThe following are the ways to compare two string in Python:1. By using == (equal to) operator2. By using != (not equal to) operator3. By using sorted() method4. By using is operator5. By using Comparison operators1. Comparing two strings using == (equal to) operatorstr1 = input("Enter the first String: ")str2 = input("Enter the second String: ")if str1 == str2:print ("First and second strings are equal and same")else:print ("First and second strings are not same")Output:Enter the first String: AAEnter the second String: AAFirst and secondstrings are equal and same2. Comparing two strings using != (not equal to) operatorstr1 = input("Enter the first String: ")str2 = input("Enter the second String: ")if str1 != str2:print ("First and second strings are not equal.")else:print ("First and second strings are the same.")Output:Enter the first String: abEnter the second String: baFirst and second strings are not equal.munotes.in

Page 71

3. Comparing two strings using the sorted() method:If we wish to compare two strings and check for their equality even if theorder of characters/words is different, then we first need to use sorted()method and then compare two strings.str1 = input("Enter the first String: ")str2 = input("Enter the second String: ")if sorted(str1) == sorted(str2):print ("First and second strings are equal.")else:print ("First and second strings are not the same.")Output:Enter the first String: Engineering DisciplineEnter the second String: Discipline EngineeringFirst and second strings are equal.4. Comparing two strings using ‘is’ operatorPython is Operator returns True if two variables refer to the same objectinstance.str1 = "DEED"str2 = "DEED"str3 = ''.join(['D', 'E', 'E', 'D'])print(str1 is str2)print("Comparision result = ", str1 is str3)Output:TrueComparision result = FalseIn the above example, str1 is str3 returns False because object str3 wascreated differently.5. Comparing two strings using comparison operatorsinput = 'Engineering'print(input < 'Engineering')print(input > 'Engineering')print(input <= 'Engineering')print(input >= 'Engineering')Output:Falsemunotes.in

Page 72

FalseTrueTrue5.10STRING OPERATIONSString is an array of bytes that represent the Unicode characters inPython. Python does not support character datatype. A single characteralso works as a string.Python supports writing the string within a singlequote('') and a double quote("").Example"Python" or 'Python'CodeSingleQuotes ='Python in Single Quotes'DoubleQuotes ="Python in Double Quotes"print(SingleQuotes)print(DoubleQuotes)Output:Python in Single QuotesPython in Double QuotesA single character is simply a string with a length of 1. The squarebrackets can be used to access the elements from the string.print()This function is used for displaying the output or result on the user screen.Syntaxprint('Text or Result') or print("Text or Result')Indexing in StringIt returns a particular character from the given string.SyntaxgetChar = a[index]message = "Hello, Python!"If I want to fetch the characters of the 7th index from the given string.Syntaxprint(string[index])Codeprint(message[7])munotes.in

Page 73

Output:P5.11 SUMMARYAPython Stringis an array of bytes demonstrating Unicodecharacters. Since there is no such data type called character data type inpython, A single character is a string of length one.String handling is oneof those activities in coding that programmers, use all the time.In Python, we have numerous built-in functions in the standard library toassist you manipulate.If the string has length one, then the indices startfrom 0 for the preliminary character and go to L-1 for the rightmostcharacter. Negative indices may be used to count from the right end,-1(minus one) for the rightmost character through-L for the leftmostcharacter. Strings are immutable, so specific characters could be read, butnot set. A substring of 0 or more successive characters of a string may bereferred to by specifying a starting index and the index oneearlierthe lastcharacter of the substring. If the starting and/or ending index is left outPython uses 0 and the length of the string correspondingly. Pythonassumes indices that would be beyond an end of the string essentiallysaytheend of the string.String formatting is the way we form instructions sothat Python can recognize how to integrate data in the creation of strings.How strings are formatted determines the presentation of this data. Thebasis of string formatting is its use of the formatting directives.Logicaloperators return true or false values. Comparison operators (==, !=, <>, >,>=, <, <=) compare two values.Any value in Python equates to a Booleantrue or false. A false can be equal to none, a zero of numeric type (0, 0l,0.0), an empty sequence ('', (), []), or an empty dictionary ({}). All othervalues are reflected true. Sequences, tuples, lists, and strings can be addedand/or multiplied by a numeric type with the addition and multiplicationoperators (+, *), correspondingly. Strings should be formatted with tuplesanddictionaries using the format directives %i, %d, %f, and %e.Formatting flags should be used with these directives.5.12 QUESTIONS1.Find the index of the first occurrence of a substring in a string.2.How would you check if each word in a string begins with a capitalletter?3.Write a Python program to calculate the length of a string4.Write a Python program to get a string from a given string where alloccurrences of its first char have been changed to '$', except the firstchar itself.munotes.in

Page 74

Sample String given: 'reboot'1.Write a Python program to change a given string to a new string wherethe first and last chars have been exchanged.2.Write a Python program to count the occurrences of each word in agiven sentence3.WritePython program to Check all strings are mutually disjoint4.Write a program to find the first and the lastoccurence of the letter 'o'and character ',' in "Good, Morning".5.Write a program to check if the word 'open' is present in the "This isopen source software".6.Write a program to check if the letter 'e' is present in the word'Welcome'.5.13 REFERENCES1.https://developers.google.com/edu/python/strings2.https://docs.python.org/3/library/string.html3.https://www.programiz.com/python-programming/string4.http://ww2.cs.fsu.edu/~nienaber/teaching/python/lectures/sequence-string.html5.https://www.tutorialsteacher.com/python/python-string6.https://techvidvan.com/tutorials/python-strings/7.http://anh.cs.luc.edu/handsonPythonTutorial/objectsummary.html8.https://docs.python.org/3/library/stdtypes.html9.https://www.programiz.com/python-programming/methods/string10.https://www.w3schools.com/python/python_ref_string.asp11.https://www.tutorialspoint.com/python_text_processing/python_string_immutability.htm12.https://web.eecs.utk.edu/~azh/blog/pythonstringsaremutable.htmlmunotes.in

Page 75

UNIT III6LISTUnit structure6.1Objectives6.2Values and Accessing Elements6.3Lists are mutable6.4Traversing a List6.5Deleting elements from List6.6Built-in List Operators6.7Concatenation6.8Repetition6.9In Operator6.10Built-in List functions and methods611Summary6.12Exercise6.13References6.1 OBJECTIVES1.To learn howpythonuses lists to store various data values.2.To study usage of the list index to remove, update and add items frompythonlist.3.To understandthe abstract data types queue, stack and list.4.To understand the implementations of basic linear data structures.5.To study the implementation of the abstract data type list as a linkedlist using the node.The list is most likely versatiledata typeavailable in the Pythonwhich is can be written as alist of comma-separated valuesbetweensquare brackets.TheImportant thing about a list is that items in the listneed not be of the same type.Creating a list is as verysimple as putting up different comma-separated by values between square brackets. For example–list1 = ['jack','nick',1997,5564];list2 = [1,2,3,4];list3 = ["a","b","c","d"];munotes.in

Page 76

Similar to a string indices, A list indices start from 0, and lists canbesliced, concatenated.6.2 VALUES AND ACCESSING ELEMENTSTo access values in lists, use the square brackets for slicing alongwith the index or indices to obtain value available at that index. Forexample–list1=['jack','nick',1997,5564];list2=[1,2,3,4,5,6,7];print"list1[0]: ",list1[0]print"list2[1:5]: ",list2[1:5]output−list1[0]:jacklist2[1:5]: [2, 3, 4, 5]6.3 LISTS ARE MUTABLE:lists is mutable. This means we can change a item in a list byaccessing it directly as part of theassignment pf statement. Using theindexing operator (square brackets) on the left of side an assignment, wecan update one of the list item.Example:color = ["red","white","black"]print(color)color[0] ="orange"color[-1] ="green"print(color)Output:.':.- ?12<. +4*,3('7:*60. ?12<. 0:..6(6.4 TRAVERSING A LISTThe mostly common way to traverse the elements of list with for loop. Thesyntax is the same as for strings:,747:':.- ?12<. +4=. 0:..6(munotes.in

Page 77

/7:,747:26,1..;.;8:26<,747:This works well if you only need to read the element of list. But if youwant to do write or update the element, you need the indices. A commonway to do that is to combine the functions range and len:/7:226:*60.4.66=5+.:6=5+.:'2(6=5+.:'2( output−redwhitebluegreen6.5 DELETING ELEMENTS FROM LIST%7-.4.<.*42;<.4.5.6< A7=,*6=;..2<1.:<1. ;<*<.5.6< del:.57>.;<1.2<.5*<*;8.,2/2,26-.@ 2/A7=367?.@*,<4A?12,1.4.5.6<;A7=*:.-.4.<2607:<1.:.57>.5.<17-2/A7=-767<367?
7:.@*584.Dlist1 = [‘red’, ‘green’, 5681, 2000,];print(list1)del list[2]print(“After deleting element at index 2 :”);print(list1)output−.'E:.-F E0:..6F   (/<.:-.4.<260.4.5.6<*<26-.@ 'E:.-F E0:..6F  (Example2:numbers=[50, 60, 70, 80]delnumbers[1:2]print(numbers)Output:[50, 70, 80]munotes.in

Page 78

•One other method from removing elements from a list is to take a sliceof thelist, which excludes the index or indexes of the item or itemsyou are trying to remove. For instance, to remove the first two items ofa list, you can dolist= list[2:]6.6 BUILT-IN LIST OPERATORSIn this lesson we will learn about built-in listoperators:
1.Concatenation:Concatenation or joining is a process in which multiple sequence / listscan be combined together. ‘+’ is a symbol concatenation operator.Example:42;< '   (42;< '   (8:26<42;< 42;< Output:[10, 20, 30, 40, 50, 60]76,*<.6*<276#.8.<2<276
!.5+.:;128%.;<260$42,2606-.@260List Operationmunotes.in

Page 79

2.Repetition / Replication / Multiply:This operator replication the list for a specified number of timesand creates a new list. ‘*’ is a symbol of repletion operator.Example:42;< '  (42;< '   (8:26<42;< 42;<  '       (3.Membership Operator:This operator used to check or test whether a particular element oritem is a member of any list or not.‘in’And‘not in’are theoperators formembership operator.Example:42;< '   (42;< '   (8:26<  42;< /*4;.8:26<  42;< <:=.8:26<  42;< <:=.8:26<  42;< /*4;.Output:*4;.%:=.%:=.*4;.4.Indexing:Indexingis nothing but there is an index value for eachtem presentin the sequence or list.munotes.in

Page 80

 
42;< '       (8:26<42;< '(Output: 5.Slicing operator:This operator used to slice a particular range of a list or a sequence.Slice is used to retrieve a subset of values.Syntax:list1[start:stop:step]Example:42;< '       (8:26<42;< '( '    (6.7 CONCATENATIONIn this we will learn different methods to concatenatelists inpython. Python list server the purpose of storing homogenous elementsand perform manipulations on the same.In general, Concatenation is the process of joining the elements ofa particular data-structure in an end-to-end manner.The following are the 4 ways to concatenate lists in python.•Concatenation (+) operator:The '+' operator can be used to concatenate two lists. It appends one list atthe end of the other list and results in a new list as output.
 
42;< '       (8:26<42;< '(Output: 5.Slicing operator:This operator used to slice a particular range of a list or a sequence.Slice is used to retrieve a subset of values.Syntax:list1[start:stop:step]Example:42;< '       (8:26<42;< '( '    (6.7 CONCATENATIONIn this we will learn different methods to concatenatelists inpython. Python list server the purpose of storing homogenous elementsand perform manipulations on the same.In general, Concatenation is the process of joining the elements ofa particular data-structure in an end-to-end manner.The following are the 4 ways to concatenate lists in python.•Concatenation (+) operator:The '+' operator can be used to concatenate two lists. It appends one list atthe end of the other list and results in a new list as output.
 
42;< '       (8:26<42;< '(Output: 5.Slicing operator:This operator used to slice a particular range of a list or a sequence.Slice is used to retrieve a subset of values.Syntax:list1[start:stop:step]Example:42;< '       (8:26<42;< '( '    (6.7 CONCATENATIONIn this we will learn different methods to concatenatelists inpython. Python list server the purpose of storing homogenous elementsand perform manipulations on the same.In general, Concatenation is the process of joining the elements ofa particular data-structure in an end-to-end manner.The following are the 4 ways to concatenate lists in python.•Concatenation (+) operator:The '+' operator can be used to concatenate two lists. It appends one list atthe end of the other list and results in a new list as output.
munotes.in

Page 81

 Example:list1 =[10, 11, 12, 13, 14]list2 =[20, 30, 42]result =list1 +list2print(str(result)) '          (•Naive method:In the Naive method, a for loop is used to be traverse the second list.After this, the elements from the second list will getappended to the firstlist. The first list of results out to be the concatenation of the first and thesecond list.Example:list1 = [10, 11, 12, 13, 14]list2 = [20, 30, 42]print(“Before Concatenation:” +str(list1))for x in list2 :list1.append(x)print (“After Concatenation:” +str(list1))Output:Before Concatenation:[10,11,12,13,14]After Concatenation:[10,11,12,13,14,20,30,42]List comprehension:Python list comprehension is an the alternative method to concatenatetwo lists in python. List comprehension is basically the process of building/ generating a list of elements based on an existing list.It uses the for loop to process and traverses alist in the element-wisefashion. The below inline is for-loop is equivalent to a nested for loop.munotes.in

Page 82

 Example:list1 = [10, 11, 12, 13, 14]list2 = [20, 30, 42]result= [j for iin [list1, list2] for j in i]print ("Concatenated List:\n"+ str(result))Output:Concatenated list:[10, 11, 12, 13, 14, 20, 30, 42]Extend() method:Pythonextend()method can be used to concatenate two lists inpython. Theextend()function does iterate over the password parameterand add the item to the list, extending the list in a linear fashion.Syntax:list.extend(iterable)Example:list1 = [10, 11, 12, 13, 14]list2 = [20, 30, 42]print("list1 before concatenation:\n" + str(list1))list1.extend(list2)print ("Concatenated list i.e ,ist1 afterconcatenation:\n"+ str(list1))All the elements of the list2 get appended to list1 and thus the list1 getsupdated and results as output.Output:list1 before concatenation:[10, 11, 12, 13, 14]Concatenated list i.e ,ist1 after concatenation:[10, 11,12, 13, 14, 20, 30, 42]•‘*’ operator:Python’s ’ *’ operator can be used for easily concatenate the two lists inPython.munotes.in

Page 83

The ‘*’ operator in Python basically unpacks the collection of items atthe index arguments.For example: Consider a list list = [1, 2,3, 4].The statement *list would replace by the list with its elements on the indexpositions. So, it unpacks the items of the lists.Example:list1 = [10, 11, 12, 13, 14]list2 = [20, 30, 42]res = [*list1, *list2]print ("Concatenated list:\n" + str(res))Output:In the above snippet of code, the statement res = [*list1, *list2]replaces the list1 and list2 with the items in the given order i.e. elements oflist1 after elements of list2. This performs concatenation and results in thebelowoutput.Output:Concatenated list:[10, 11, 12, 13, 14, 20, 30, 42]•Itertools.chain() method:Python itertools modules’ itertools.chain() function can also be used toconcatenate lists in Python.The itertools.chain() function accepts different iterables such as lists,string, tuples, etc as parameters and gives a sequence of them as output.It results out to be a linear sequence. The data type of the elementsdoesn’t affect the functioning of the chain() method.For example: The statementitertools.chain([1, 2], [‘John’,‘Bunny’]) would produce the following output: 1 2 John BunnyExample:import itertoolslist1 = [10, 11, 12, 13, 14]munotes.in

Page 84

list2 = [20, 30, 42]res = list(itertools.chain(list1, list2))print ("Concatenated list:\n " +str(res))Output:Concatenated list:[10, 11, 12, 13, 14, 20, 30, 42]6.8 REPETITIONNow,weare accustomed to using the '*' symbol to represent themultiplication, but when the operand on the left of side of the '*' is a tuple,it becomes the repetition operator.And The repetition of the operator itwill makes the multiple copies of a tuple andjoins them all together.Tuples can be created using the repetition operator, *.Example:number= (0,) * 5 # we use the comma to denote that this is a single valued tupleand not an‘#’expressionOutputprint numbers(0, 0, 0, 0, 0)[0] is a tuplewith one element, 0. Now repetition of the operator it willmakes 5 copies of this tuple and joins them all together into a single tuple.Another example using multiple elements in the tuple.Example:numbers = (0, 1, 2) * 3Outputprint numbers(0,1, 2, 0, 1, 2, 0, 1, 2)6.9 IN OPERATORPython's in operator lets you loop through all the members of acollection (such as a list or a tuple) and check if there's a member in thelist that's equal to the given item.munotes.in

Page 85

Example:my_list = [5, 1, 8, 3,7]print(8 in my_list)print(0 in my_list)Output:TrueFalseNote:Note that in operator against dictionary checks for the presence ofkey.Example:my_dict = {’name’: ’TutorialsPoint’, ’time’: ’15 years’, ’location’: ’India’}print(’name’ in my_dict)Output:This will give the output−True6.10 BUILT-IN LIST FUNCTIONS AND METHODS1.Built-infunction:Sr. No.Function with Description1cmp(list1, list2)Compares elements of both lists.2len(list)Gives the total length of the list.3max(list)Returns item from the list with max value.4min(list)Returns item from the list with min value.5list(seq)Converts a tuple into list.munotes.in

Page 86

2.Built-in methods:Sr.No.Methods with Description1list.append(obj)Appends object obj tolist2list.count(obj)Returns count of how many times obj occurs in list3list.extend(seq)Appends the contents of seq to list4list.index(obj)Returns the lowest index in list that obj appears5list.insert(index, obj)Inserts object obj into listat offset index6list.pop(obj=list[-1])Removes and returns last object or obj from list7list.remove(obj)Removes object obj from list8list.reverse()Reverses objects of list in place9list.sort([func])Sorts objects of list, use compare func ifgiven6.11SUMMARYPython listsare commanding data structures, and listunderstandings are one of the furthermost convenient and brief ways tocreate lists. In this chapter, we have given some examples of how you canuse list comprehensions to be more easy-to-read and simplify your code.The list is the common multipurpose data type available in Python.Alistisan ordered collection of items. When it comes to creating lists, Python listare more compressed and faster than loops and other functions used suchas, map(), filter(), and reduce().Every Python list can be rewritten in forloops, but not every complex for loop can be rewritten in Python listunderstanding. Writing very long list in one line should be avoided so asto keep the code user-friendly. So list looksjust like dynamic sizedarrays, declared in other languages. Lists need not be homogeneousalways which makes it a most powerful tool inPython. A single list maycontain Datatype’s like Integers, Strings, and Objects etc.List loads allthe elements into memory at one time, when the list is too long, it willreside in too much memory resources, and we usually only need to use afew elements. A list is a data-structure that can be used to store multipledata at once. The list will be ordered and there will be a definite count ofit. The elements are indexed allowing to a sequence and the indexing isdone with 0 as the first index. Each element will have a discrete place inthe sequence and if the same value arises multiple times in the sequence.munotes.in

Page 87

6.12QUESTIONS1.Explain List parameters with an example.2.Write a program in Python to delete first andlast elements from a list3.Write a Python program to print the numbers of a specified list afterremoving even numbers from it.4.Write a python program using list looping5.Write a Python program to check a list is empty or not6.Write a Python program to multiplies all the items in a list7.Write a Python program to remove duplicates from a list8.Write a Python program to append a list to the second list9.Write a Python program to find the second smallest number in a list.10.Write a Python program to find common itemsfrom two lists6.13REFERENCES1.https://python.plainenglish.io/python-list-operation-summary-262f40a863c8?gi=a4f7ce4740e92.https://howchoo.com/python/how-to-use-list-comprehension-in-python3.https://intellipaat.com/blog/tutorial/python-tutorial/python-list-comprehension/4.https://programmer.ink/think/summary-of-python-list-method.html5.https://www.geeksforgeeks.org/python-list/6.https://enricbaltasar.com/python-summary-methods-lists/7.https://developpaper.com/super-summary-learn-python-lists-just-this-article-is-enough/8.https://www.programiz.com/python-programming/methods/list9.https://www.hackerearth.com/practice/python/working-with-data/lists/tutorial/10.https://data-flair.training/blogs/r-list-tutorial/munotes.in

Page 88

7TUPLES AND DICTIONARIESUnit Structure7.1Objectives7.2Tuples7.2Accessing values in Tuples7.3Tuple Assignment7.4Tuples as return values7.5Variable-length argument tuples7.6Basic tuples operations7.7Concatenation7.8Repetition7.9InOperator7.10Iteration7.11Built-in Tuple Functions7.12Creating a Dictionary7.13Accessing Values in a dictionary7.14Updating Dictionary7.15Deleting Elements from Dictionary7.16Properties of Dictionary keys7.17Operations in Dictionary7.18Built-In Dictionary Functions7.19Built-in Dictionary Methods7.20Summary7.21Exercise7.22References7.1 OBJECTIVES1.To understand when to use a dictionary.2.To study how a dictionary allows us to characterize attributes withkeys and values3.To learn how to read a value from a dictionary4.To study how in python to assign a key-value pair to a dictionary5.To understand howtuples returns valuesmunotes.in

Page 89

7.2 TUPLESA tuple in the Python is similar to the list. The difference betweenthe two is that we cannot change the element of the tuple once it isassigned to whereas we can change the elements of a listThe reasons for having immutable types apply to tuples: copyefficiency: rather than copying an immutable object, you can alias it (binda variable to a reference) ... interning: you need to store at most of onecopy of any immutable value.There’sno anyneed to synchronize accessto immutable objects in concurrent code.Creating a Tuple:A tuple is created by the placing all theelements insideparentheses '()', separated by commas. The parentheses are the optionalandhowever, it is a good practice to use them.A tuple can have any number of the items and they may be adifferent types (integer, float, list, string, etc.).
2//.:.6<26026<.0.:;<=84.  8:26<<=84.<=84.?2<152@.--*<*8:26<<=84.6.;<.-<=84.<=84.,747: '   (   8:26<<=84.munotes.in

Page 90

 Output:()   ,7-. 
,747: '   (   A tuple canalso be created without using parentheses. This is known astuple packing.<=84. 
 ,747:8:26<<=84.<=84.=68*,32602;*4;787;;2+4.* + ,<=84.8:26<*8:26<+
8:26<,-70Output: 
 ,747:
,747:7.3 ACCESSING VALUES IN TUPLESThere are various ways in which we can access the elements of a tuple.1. Indexing:We can use the index operator [] to access an item in a tuple,where the index starts from 0.So, a tuple having 6elements will have indices from 0 to 5. Tryingto access an index outside of the tuple index range(6,7,... in this example)will raise an IndexError.munotes.in

Page 91

 The index must be an integer, so we cannot use float or othertypes. This will result in TypeError. 23.?2;. 6.;<.-<=84.;*:.*,,.;;.-=;2606.;<.-26-.@260 *;;17?626<1..@*584.+.47?
# Accessing tuple elements using indexingtuple = (’a’,’b’,’c’,’d’,’e’,’f’)print(tuple[0]) # ’a’print(tuple[5]) # ’f’# IndexError: list index out of range# print(tuple[6])# Index must be an integer# TypeError: list indices must be integers, not float# tuple[2.0]# nested tupletuple = ("color", [6, 4, 2], (1, 2, 3))# nested indexprint(tuple[0][3]) # ’o’print(tuple[1][1]) # 4Output:afo42. Negative Indexing:"A<176*447?;6.0*<2>.26-.@260/7:2<;;.9=.6,.;
The index of-1 refers to the last item,-2 to the second last item and so on.Example:# Negative indexing for accessing tuple elementstuple = (’a’,’b’,’c’,’d’,’e’,’f’)munotes.in

Page 92

 # Output: ’f’print(tuple[-1])# Output: ’a’print(tuple[-6])Output:fa3. Slicing:We can access the range of items from the tuple by using theslicing operator colon:Example:# Accessing tuple elements using slicingtuple =(’a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’)# elements 2nd to 4th# Output: (’b’, ’c’, ’d’)print(tuple[1:4])# elements beginning to 2nd# Output: (’a’, ’b’)print(tuple[:-7])# elements 8th to end# Output: (’h’, ’i’)print(tuple[7:])# elements beginning toend# Output: (’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)print(tuple[:])Output:(’b’, ’c’, ’d’)(’a’, ’b’)munotes.in

Page 93

(’h’, ’i’)(’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)7.4 TUPLE ASSIGNMENTOne of the unique syntactic features of the Python language istheability to have a tuple on the left side of an assignment statement. Thisallows you to assign more than one variable at a time when the left side isa sequence.In this example we have a two-element list (which is a sequence)and assign the first andsecond elements of the sequence to the variables xand y in a single statement.Example:<=84.':.- +4=.(@ A<=84.Output:@:.-A+4=.It is not magic, Pythonroughlytranslates the tuple assignmentsyntax to be the following:5':.- +4=.(@5' (A5' (Output:@:.-A+4=.7.5 TUPLES AS RETURN VALUESFunctions can return tuples as return values. Now we often want toknow some batsman’s highest and lowest score or we want to know tomunotes.in

Page 94

find the mean and the standarddeviation,or we want to know the year, themonth, and the day, or if we’re doing some ecological modeling we maywant to know the number of rabbits and the number of wolves on an islandat a given time. In each case, a function (which can only return a singlevalue), can create a single tuple holding multiple elements.For example, we could write a function that returns both the area and thecircumference of a circle of radius.Example:-./,2:4,.)26/7:#.<=:6,2:,=5/.:.6,. *:.*7/*,2:,4.7/:*-2=;:, 
 :*
 :::.<=:6, *8:26<,2:4,.)26/7  
   
7.6 VARIABLE-LENGTH ARGUMENT TUPLESFunctions can take a variable number of arguments. The parametername that beginswiththe* gather the argument into the tuple. Forexample,theprint all take any number of the arguments and print them:def printall(*args):print argsThe gather parameter can have any name you like, butargsisconventional. Here’s how the functionworks:The complement of gather is scatter. If you have the sequence ofvalues and you want to pass it to the function as multiple as arguments,you can use the * operator. For example, divmod take exactly twoarguments it doesn’t work with the tuple:t= (7, 3)divmod(t)TypeError: divmod expected 2 arguments, got 1But if you scatter the tuple, it works:divmod(*t)munotes.in

Page 95

(2, 1)Example-Many of the built-in functions are use variable-length argumenttuples. For example, max and min it can take any of numberarguments:max(1,2sum(1,2,3)TypeError: sum expected at most 2 arguments, got 3,3)But sumdoes not.7.7 BASIC TUPLES OPERATIONSNow, we will learn the operations that we can perform on tuples inPython.1.Membership:&.,*6*884A<1.E26F*6-E67<26F78.:*<7:76<1.2<.5;
%12;<.44;=;?1.<1.:<1.A+.4760<7<1.<=84.
’a’ in tuple("string")Output:False’x’ not in tuple("string")Output:True2.Concatenation:Like we’ve previously discussed on several occasions,concatenation is the act of joining. We can join two tuples using theconcatenation operator ‘+’.(1,2,3)+(4,5,6)Output:(1, 2, 3, 4, 5, 6)Note:Other arithmetic operations do not apply on a tuple.3.Logical:44<1.4702,*478.:*<7:;423. 

,*6+.*8842.-76*<=84.
(1,2,3)>(4,5,6)munotes.in

Page 96

Output:False(1,2)==(’1’,’2’)Output:False4.Identity:Remember the ‘is’ and ‘is not’ operators we discussed about in ourtutorial on Python Operators? Let’s try that on tuples.a=(1,2)(1,2) is aOutput:That did not make sense, did it? So what really happened? Now, inPython, two tuples or lists don't have the same identity. In other words,they are two different tuples or lists. As a result, it returns False.7.8 CONCATENATIONNow, we will learn 2 different ways to concatenate or join tuples inthe python language with code example. We will use ‘+” operator and abuilt-in sum() function to concatenate or join tuples in python.•How to concatenate tuples into single/nested Tuples using sum():2.1Sum() to concatenate tuples into a single tuple:In our first example, we will use the sum() function to concatenate twotuples and result in a single tuple.Let us jump to example:tupleint= (1,2,3,4,5,6)langtuple = (’C#’,’C++’,’Python’,’Go’)#concatenate the tupletuples_concatenate = sum((tupleint, langtuple), ())print(’concatenate of tuples\n =’,tuples_concatenate)Output:concatenate of tuplesmunotes.in

Page 97

= (1, 2, 3, 4, 5, 6, ’C#’, ’C++’, ’Python’, ’Go’)Sum() to concatenate tuple into a nested tuple:Now let us understand how we can sum tuples to make a nestedtuple.In this program we will use two tuples which are nested tuples,please note the ‘,’ at the end of each tuples tupleint and langtuple.let us understand example:tupleint= (1,2,3,4,5,6),langtuple = (’C#’,’C++’,’Python’,’Go’),#concatenate the tupletuples_concatenate = sum((tupleint, langtuple), ())print(’concatenate of tuples\n =’,tuples_concatenate)Output:concatenate of tuples= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))Concatenate tuple Using ‘+’ operator:2.1 ‘+’ operator to concatenate two tuples into a single tuple:In our first example, we will use the “+” operator to concatenatetwo tuples and result in a single tuple.In this example we have two tupletupleint and langtuple,We are the concatenating these tuples into the singletuple as we can see in output.tupleint= (1,2,3,4,5,6)langtuple = ('C#','C++','Python','Go')#concatenate the tupletuples_concatenate = tupleint+langtupleprint('concatenate oftuples\n =',tuples_concatenate)Output:2.2 ‘+’ operator with a comma(,) to concatenate tuples into nestedTuples:This example, we have the two tuple tuple int and lang tuple. NowWe are using the comma(,) end of the each tuple to the concatenate themmunotes.in

Page 98

into a nested tuple. We are concatenating these tuples into a nested tupleas we can see in the resulting output.# comma(,) after tuple to concatenate nested tupletupleint= (1,2,3,4,5,6),langtuple = ('C#','C++','Python','Go'),#concatenate the tuple into nested tupletuples_concatenate = tupleint+langtupleprint('concatenate of tuples\n =',tuples_concatenate)Output:concatenate of tuples= ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go'))7.9 REPETITIONNow, we are going to explain how to use Python tuple repetitionoperator with basic syntax and many examples for better understanding.Python tuple repetition operator (*) is used to the repeat a tuple,number of times which is given by the integer value and create a new tuplevalues.Syntax: * NN * Input Parameters:•tuple_variable_name1 : The tuples thatwe want to be repeated.•N : where is the number of times that we want that tuple to be repeatedex: 1,2,3,……..nExample:data=(1,2,3,’a’,’b’)# tuple after repetitionprint(’New tuple:’, data* 2)munotes.in

Page 99

Output:New tuple: [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’,‘b’]In the above Example, using repetition operator (*), we haverepeated ‘data’ tuple variable 2 times by ‘data* 2’ in print statement andcreated new tuple as [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’].7.10 IN OPERATORThe Python in operator lets you loop through all to the members ofthe collection and check if there's a member in the tuple that's equal to thegiven item.Example:my_tuple = (5, 1, 8, 3, 7)print(8 in my_tuple)print(0 in my_tuple)Output:TrueFalseNote that in operator againstdictionary checks for the presence ofkey.Example:Output:TrueIt can also be used to check the presence of a sequence or substringagainst string.Example:my_str = "This is a sample string"print("sample" in string)Output:TrueIt can be uses in the many of other places and how it works in thethose scenarios of varies a lot. This is the how in works in tuples. It startmunotes.in

Page 100

the comparing references of the objects from the first one till it either findsthat the object in the tuple orreaches in the end of the tuple.7.11 ITERATIONThere are many ways to iterate through the tuple object. Forstatement in Python has a variant which traverses a tuple till it isexhausted. It is equivalent to for each statement in Java. Its syntax is–for var in tuple:stmt1stmt2Example:T = (10,20,30,40,50)for var in T:print (T.index(var),var)Output:0 101 202 303 404 507.12 BUILT-IN TUPLE FUNCTIONSTuples support the following build-in functions:Comparison:If the elements are ofthe same type, python performs thecomparison and returns the result. If elements are different types, it checkswhether they are numbers.If numbers,perform comparison.If either the element is an number, then the other element is areturned.Otherwise, types are sorted alphabetically.munotes.in

Page 101

If we reached to the end of one ofthe lists, the longer list isa"larger." If both are list are same it returns 0.tuple1 = (’a’, ’b’, ’c’,’d’, ’e’)tuple2 = (’1’,’2’,’3’)tuple3 = (’a’, ’b’, ’c’, ’d’, ’e’)cmp(tuple1, tuple2)Out: 1cmp(tuple2, tuple1)Out:-1cmp(tuple1, tuple3)Out: 0Tuple Length:len(tuple1)Out:5Max of a tuple:The function min returns the item from the tuple with the min value:min(tuple1)Out:’a’min(tuple2)Out:’1’Convert a list intotuple:The built-in function tuple converts a list into a tuple:list=[1,2,3,4,5]tuple(list)Out:(1,2,3,4,5)Tuple concatenation:Use + to concatenate two tuples:tuple1+tuple2Out:(’a’,’b’,’c’,’d’,’e’,’1’,’2’,’3’)munotes.in

Page 102

7.13 CREATING ADICTIONARYCreating a Dictionary:To create the Python dictionary, we need to pass the sequence ofthe items inside curly braces {}, and to separate them using a comma (,).Each item has a key and a value expressed as an "key:value" pair.The valuescan belong to the any of data type and they can repeat,but the keys are must remain the unique.The following examples are demonstrate how to create the Pythondictionaries:Creating an empty dictionary:-2,<);*584.BCCreating a dictionary with integer keys:dict_sample = {1: ’mango’, 2: ’pawpaw’}Creating a dictionary with mixed keys:dict_sample = {’fruit’: ’mango’, 1: [4, 6, 8]}We can also create a dictionary by explicitly calling the Python's dict()method:dict_sample = dict({1:’mango’,2:’pawpaw’})A dictionary can also be created from a sequence as shown below:Dictionaries can also be nested, which means that we can create adictionary inside another dictionary. For example:dict_sample = {1: {’student1’ : ’Nicholas’, ’student2’ : ’John’, ’student3’ : ’Mercy’},2: {’course1’ : ’Computer Science’, ’course2’ : ’Mathematics’,’course3’ : ’Accounting’}}To print the dictionary contents, we can use the Python's print() functionand pass the dictionary name as the argument to the function.Forexample:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}print(dict_sample)Output:B758*6A%7A7<* 57-.4":.527 A.*: Cmunotes.in

Page 103

7.14 ACCESSING VALUES IN A DICTIONARYTo access the dictionary items, we needto pass the key insidesquare brackets []. For example:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}x = dict_sample["model"]print(x)Output:PremioWe created a dictionary named dict_sample. A variable named x isthencreated and its value is set to be the value for the key "model" in thedictionary.7.15 UPDATING DICTIONARYAfter adding a value to a dictionary we can then modify theexisting dictionary element. You use the key of the element to change thecorresponding value. For example:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}dict_sample["year"] = 2014print(dict_sample)Output:{’year’: 2014, ’model’: ’Premio’, ’Company’: ’Toyota’}In this example you can see that we haveupdated the value for the key"year" from the old value of 2012 to a new value of 2014.munotes.in

Page 104

7.16 DELETING ELEMENTS FROM DICTIONARYThe removal of an element from a dictionary can be done inseveral ways, which we'll discuss one-by-one in this section:The del keyword can be used to remove the element with thespecified key. For example:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}del dict_sample["year"]print(dict_sample)Output:{’Company’: ’Toyota’, ’model’: ’Premio’}We called the del keyword followed by the dictionary name. Insidethe square brackets that follow the dictionary name, we passed the key ofthe element we need to delete from the dictionary, which in this examplewas "year". The entry for "year" in the dictionary was then deleted.Another type to delete a key-value pair is to use the pop() methodand pass the key of the entry to be deleted as the argument to the function.For example:Output:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}dict_sample.pop("year")print(dict_sample)We invoked that pop() method by appending it with the dictionaryname. And, in this example the entry for "year" in the dictionary will bedeleted.munotes.in

Page 105

The popitem() method removes the last item of inserted into thedictionary, without needing to specify the key. Take a look at thefollowing example:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}dict_sample.popitem()print(dict_sample)Output:{’Company’: ’Toyota’, ’model’:’Premio’}The last entry into the dictionary was "year". It has been removedafter calling the popitem() function.But what if you want to delete the entire dictionary? It would bedifficult and cumbersome to use one of these methods on every single key.Instead, you can use the del keyword to delete the entire dictionary. Forexample:dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}del dict_sampleprint(dict_sample)Output:NameError: name ’dict_sample’ is not definedThe code returns an error. The reason is we are trying to access thean dictionary which is doesn't exist since it is has been deleted.However, your use-case may require you to just remove alldictionary elements and be left with an empty dictionary. This canbeachieved by calling the clear() function on the dictionary:munotes.in

Page 106

dict_sample = {"Company": "Toyota","model": "Premio","year": 2012}dict_sample.clear()print(dict_sample)Output:{}The code is returns an empty dictionary since all thedictionary elementshave been removed.7.17 PROPERTIES OF DICTIONARY KEYSDictionary values have no restrictions. These can be any oferratically Python object, either they standard objects or user-definedobjects. However, similar is not true for the keys.There are two important points to be remember about thedictionary keys:(a)More than one ofthe entry per key not allowed.Which means that noduplicate key isallowed. When the duplicate keys are encountered duringthe assignment, And, the lastassignment wins.For example:dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Name’: ‘Manni’};print “dict[‘Name’]: “, dict[‘Name’];Output:dict[‘Name’]: Mannidict= {[‘Name’]: ‘Zara’, ‘Age’: 7};print “dict[‘Name’]: “, dict[‘Name’];(b)Keys must be immutable.Which mean by you can use strings, And thenumbers or tuples as dictionary keys but something like [‘key’] is notallowed. Following is a simple:munotes.in

Page 107

Output:Traceback (most recent call last):File “test.py”, line 3, indict= {[‘Name’]: ‘Zara’, ‘Age’: 7};TypeError: list objects are unhashable7.18 OPERATIONS IN DICTIONARYBelow is a list of common dictionary operations:create an empty dictionaryx = {}create a three items dictionaryx = {"one":1, "two":2, "three":3}access an elementx[’two’]get a list of all the keysx.keys()get a list of all the valuex.values()add an entryx["four"]=4change an entryx["one"] = "uno"delete an entrydel x["four"make a copyy = x.copy()remove all itemsmunotes.in

Page 108

x.clear()number ofitemsz = len(x)test if has keyz = x.has_key("one")looping over keysfor item in x.keys(): print itemlooping over valuesfor item in x.values(): print itemusing the if statement to get the valuesif "one" in x:print x[’one’]if"two" not in x:print "Two not found"if "three" in x:del x[’three’]7.18 BUILT-IN DICTIONARY FUNCTIONSA function is a procedure that can be applied on a construct to get avalue. Furthermore, it doesn’t modify the construct. Python gives us a fewfunctions that we can apply on a Python dictionary. Take a look.1. len():The len() function returns the length of the dictionary in Python.Every key-value pair adds 1 to the length.len(dict4)Output3len({})any({False:False,’’:’’})An emptyPython dictionary has a length of 0.munotes.in

Page 109

2. any():Like it is with lists an tuples, the any() function returns True ifeven one key in a dictionary has a Boolean value of True.Output:FalseOutput:any({True:False,"":""})True3. all():Unlike theany() function, all() returns True only if all the keys in thedictionary have a Boolean value of True.Output:all({1:2,2:’’,"":3})False4. sorted():Like it is with lists and tuples, the sorted() function returns a sortedsequence of the keys in thedictionary. The sorting is in ascending order,and doesn’t modify the original Python dictionary.dict4={3:3,1:1,4:4}But to see its effect, let’s first modify dict4.Now, let’s apply the sorted() function on it.Output:[1, 3, 4]As you can see, theoriginal Python dictionary wasn’t modified.dict4This function returns the keys in a sorted list. To prove this, let’s see whatthe type() function returns.Output:munotes.in

Page 110

This proves that sorted() returns a list.{3: 3, 1: 1, 4: 4}dict4type(sorted(dict4))7.19 BUILT-IN DICTIONARY METHODSA method is a set of the instructions to execute on the construct,and it may be modify the construct. To do this, the method must be calledon the construct, let’s look at the available the methods for dictionaries.dict4.keys()Let’s use dict4 for this example.1. keys():dict_keys([3, 1, 4])The keys() method returns a list of keys in a Python dictionary.dict4.values()Output:2. values():Likewise, the values() method returns a listof values in the dictionary.Output:dict_values([3, 1, 4])3. items()This method returns a list of key-value pairs.Output:dict_items([(3, 3), (1, 1), (4, 4)])7.20 SUMMARYTuples:InPython,tuplesare structured and accessed based onposition.A Tuple is a collection of Python objects separated by commas.In some ways a tuple is similar to a list in terms of indexing, nestedobjects and repetition but a tuple is absolute unlike lists that are variable.In Python it is an unordered collection of data values, used to store datavalues like a map, which unlike other data types that hold only singlevalue as an element.Tuples areabsolutelists. Elements of a list can bemodified, but elements in a tuple can only be accessed, not modified. Themunotes.in

Page 111

nametupledoes not mean that only two values can be stored in this datastructure.Dictionaries:DictionariesinPythonare structured and accessed usingkeys and values.Dictionariesare defined inPythonwith curly braces { } .Commas separate the key-value pairs that make up thedictionary.Dictionaries are made up of key and/or value pairs. In Python, tuples areorganized and accessed based on position. The location of a pair of keysand values stored in a Python dictionary is unrelated.Key value isprovided in the dictionary to make it more optimized.A Pythondictionary is basically ahashtable. In some languages, they might bementioned toanassociativearrays. They are indexed with keys, whichcan be any absolute type.7.21 QUESTIONS1.Let list = [’a’, ’b’, ’c’,’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:]2.State the difference between lists and dictionary3.What is the benefit ofusing tuple assignment in Python?4.Define dictionary with an example5.Write a Python program to swap two variables6.Define Tuple and show it is immutable with an example7.Create tuple with single element8.How can you access elements from the dictionary9.Write aPython program to create a tuple with different data types.10.Write a Python program to unpack a tuple in several variables7.22 REFERENCES1.https://www.geeksforgeeks.org/differences-and-applications-of-list-tuple-set-and-dictionary-in-python/2.https://problemsolvingwithpython.com/04-Data-Types-and-Variables/04.05-Dictionaries-and-Tuples/3.https://problemsolvingwithpython.com/04-Data-Types-and-Variables/04.05-Dictionaries-and-Tuples/4.https://ncert.nic.in/textbook/pdf/kecs110.pdf5.https://python101.pythonlibrary.org/chapter3_lists_dicts.html6.https://www.programmersought.com/article/26815189338/7.https://www.javatpoint.com/python-tuples8.https://cloudxlab.com/assessment/displayslide/873/python-dictionaries-and-tuples9.https://medium.com/@aitarurachel/data-structures-with-lists-tuples-dictionaries-and-sets-in-python-612245a712af10.https://www.w3schools.com/python/python_tuples.aspmunotes.in

Page 112

8FILES AND EXCEPTIONSUnit Structure8.1Objective8.2Text Files8.3The File Object Attributes8.4Directories8.5Built-in Exceptions8.6Handling Exceptions8.7Exception with Arguments8.8User-defined Exceptions8.9Summary8.10Exercise8.11References8.1 OBJECTIVE1.To understand howpython will raise an exception.2.To create program to catch an exception using atry/exceptblock.3.To study the Python errors and exceptions.4.To study creation and use of read and writecommands for files.inpython5.To understand how to open, write and closefiles in python8.2 TEXT FILESNow we willlearnaboutvarious ways to read text files in Python.The following shows how to read all texts from the readme.txt file into astring:with open(’readme.txt’) as f:lines = f.readlines()Steps forreading a text file in Python:To read the text file in the Python, you have to follow these steps:munotes.in

Page 113

Firstly, you have to open the text file for reading by using theopen() method.Second, you have to read the text from the text file using the fileread(), readline(), or readlines() method of the file object.Third, you have to close the file using the file close() method.1) open() functionThe open() function has many parameters but you’ll be focusing on thefirst two.open(path_to_file, mode)The path to the file parameter is specifies the path to the text file.If the file is in the same folder as is program, you have just need tospecify the file name. Otherwise, you have need to specify the path to thefile.Specify the path to the file, youhave to use the forward-slash ('/')even if you are working in Windows.Example, if the file is in the readme.txt stored in the sample folderas the program, you have need to specify the path to the file asc:/sample/readme.txtA mode is in the optionalparameter. This is the string that isspecifies the mode in which you want to open the file.The following table shows available modes for opening a text file:ModeDescription'r'Open for text file for reading text'w'Open a text file for writing text'a'Open a text file for appending textFor example, to open a file whose name is the-zen-of-python.txt stored inthe same folder as the program, you use the following code:f = open(’the-zen-of-python.txt’,’r’)The open() function returns a file objectwhich you will use to readtext from a text file.2) Reading text methods:The file object provides you with three methods for reading text from atext file:munotes.in

Page 114

read()–read all text from a file into a string. This method is useful if youhave a smallfile and you want to manipulate the whole text of that file.readline()–read the text file line by line and return all the lines as strings.readlines()–read all the lines of the text file and return them as a list ofstrings.3) close() method:Thefile that you open will remain open until you close it using theclose() method.It’s important to close the file that is no longer in use. If you don’tclose the file, the program may crash or the file would be corrupted.The following shows how to callthe close() method to close the file:f.close()To close the file automatically without calling the close() method,you use the with statement like this:with open(path_to_file) as f:contents = f.readlines()In practice, you’ll use the withstatement to close the fileautomatically.Reading a text file examples:We’ll use the-zen-of-python.txt file for the demonstration.The following example illustrates how to use the read() method to read allthe contents of the the-zen-of-python.txt file into a string:with open(’the-zen-of-python.txt’) as f:contents = f.read()print(contents)Output:Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex....munotes.in

Page 115

The following example uses the readlines()method to read the text fileand returns the file contents as a list of strings:lines = []with open(’the-zen-of-python.txt’) as f:lines = f.readlines()count = 0for line in lines:count += 1print(f’line {count}: {line}’)Output:line 1:Beautiful is better than ugly.line 2: Explicit is better than implicit.line 3: Simple is better than complex....8.3 THE FILE OBJECT ATTRIBUTESOnce a file is opened and you have one file object, you can getvarious information related to that file.Here is a list of all attributesrelated to file object:AttributeDescriptionfile.closedReturns true if file is closed, false otherwise.file.modeReturns access mode with which file was opened.file.nameReturns name of the file.file.softspaceReturns false if space explicitly required with print, trueotherwise.Example# Open a filefo = open(“foo.txt”, “wb”)print “Name of the file: “, fo.nameprint “Closed or not : “, fo.closedprint “Opening mode : “, fo.modeprint “Softspace flag : “,fo.softspacemunotes.in

Page 116

This produces the following result:Name of the file: foo.txtClosed or not : FalseOpening mode : wbSoftspace flag : 08.4 DIRECTORIESIn this Python Directory tutorial, we will import the OS module tobe able to access the methods we will apply.importosHow to Get Current Python Directory?To find out which directory in python you are currently in, use thegetcwd() method.os.getcwd()Output:‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’Cwd is for currentworking directory in python. This returns the path ofthe current python directory as a string in Python.To get it as a bytes object, we use the method getcwdb().os.getcwdb()Output:b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′Here, we get two backslashes instead of one. This is because thefirst one is to escape the second one since this is a string object.type(os.getcwd())To render it properly, use the Python method with the print statement.print(os.getcwd())munotes.in

Page 117

Output:Changing Current Python DirectoryTo change our current working directories in python, we use the chdir()method.This takes one argument-the path to the directory to which to change.Output:‘unicodeescape’ code can’tdecode bytes in position 2-3: truncated\UXXXXXXXX escapeBut remember that when using backward slashes, it isrecommended to escape the backward slashes to avoid a problem.Output:How to Create Python Directory?We can also create new pythondirectories with the mkdir() method. Ittakes one argument, that is, the path of the new python directory to create.os.mkdir('Christmas Photos')os.listdir()Output:[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘ChristmasPhotos’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘EclipseJava Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘For the book.txt’, ‘Items fortrip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’,‘Today.txt’, ‘topics.txt’,‘unnamed.jpg’]How toRenamePython Directory?:To rename directories in python, we use the rename() method. Ittakes two arguments-the python directory to rename, and the new namefor it.os.rename('Christmas Photos','Christmas 2017')os.listdir()Output:[‘Adobe Photoshop CS2.lnk’, ‘Atom.lnk’, ‘Burn Book.txt’, ‘Christmas2017’, ‘desktop.ini’, ‘Documents’, ‘Eclipse Cpp Oxygen.lnk’, ‘Eclipsemunotes.in

Page 118

Java Oxygen.lnk’, ‘Eclipse Jee Oxygen.lnk’, ‘Forthe book.txt’, ‘Items fortrip.txt’, ‘Papers’, ‘Remember to remember.txt’, ‘Sweet anticipation.png’,‘Today.txt’, ‘topics.txt’, ‘unnamed.jpg’]How to Remove Python Directory?We made a file named ‘Readme.txt’ inside our folder Christmas2017. To delete this file, we use the method remove().os.chdir('C:\\Users\\lifei\\Desktop\\Christmas 2017')os.listdir()Output:[‘Readme.txt’]8.5 BUILT-IN EXCEPTIONSIllegal operations can raise exceptions. There are plenty of built-inexceptions in Python thatare raised when corresponding errors occur. Wecan view all the built-in exceptions using the built-in local() function asprint(dir(locals()['__builtins__']))follows:locals()['__builtins__'] will return a module of built-in exceptions,functions, andattributes. dir allows us to list these attributes as strings.Some of the common built-in exceptions in Python programming alongwith the error that cause them are listed below:ExceptionCause of ErrorAssertionErrorfails.Raised when an assert statementAttributeErrorRaised when attribute assignment or referencefails.EOFErrorRaised when the input() function hitsend-of-filecondition.FloatingPointErrorRaised when a floating point operation fails.GeneratorExitRaise when a generator'sclose() method iscalled.ImportErrorRaised when the imported module is not found.IndexErrorRaised when the index of a sequence is out ofrange.KeyErrorRaised when a key is not found in a dictionary.KeyboardInterruptRaised when the user hits theinterrupt key(Ctrl+C or Delete).munotes.in

Page 119

MemoryErrorRaised when an operation runs out of memory.NameErrorRaised when a variable is not found in local orglobal scope.NotImplementedErrorRaised by abstract methods.OSErrorRaised when system operation causes systemrelated error.OverflowErrorRaised when the result of an arithmeticoperation is too large to be represented.ReferenceErrorRaised when a weak reference proxy is used toaccess a garbage collected referent.RuntimeErrorRaised when an errordoes not fall under anyother category.StopIterationRaised by next() function to indicate that thereis no further item to be returned by iterator.SyntaxErrorRaised by parser when syntax error isencountered.IndentationErrorRaised when there is incorrect indentation.TabErrorRaised when indentation consists of inconsistenttabs and spaces.SystemErrorRaised when interpreter detects internal error.SystemExitRaised by sys.exit() function.TypeErrorRaised when a function or operation isappliedto an object of incorrect type.UnboundLocalErrorRaised when a reference is made to a localvariable in a function or method, but no valuehas been bound to that variable.UnicodeErrorRaised when a Unicode-related encoding ordecoding error occurs.UnicodeEncodeErrorRaised when a Unicode-related error occursduring encoding.UnicodeDecodeErrorRaised when a Unicode-related error occursduring decoding.UnicodeTranslateErrorRaised when a Unicode-related error occursduring translating.ValueErrorRaised when a function gets an argument ofcorrect type but improper valueZeroDivisionErrorRaised when the second operand of division ormodulo operation is zero.8.6 HANDLING EXCEPTIONSIf you have some suspicious code that may raisean exception, youcan defend your program by placing the suspicious code in a try: block.After the try: block, include an except: statement, followed by a block ofcode which handles the problem as elegantly as possible.Syntax:Here is simple syntax oftry....except...else blocks:munotes.in

Page 120

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 isuseful when the try block contains statements that maythrow differenttypes of exceptions.You can also provide a generic except clause, which handles anyexception.After the except clause(s), you can include an else-clause. Thecode in the else-block executes if the code in the try: block does not raisean exception.The else-block is a good place for code that does not need the try:block's protection.Example:This example opens a file, writes content in the, file and comes outgracefully because there is no problem at all: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:munotes.in

Page 121

print "Writtencontentinthefilesuccessfully"fh.close()This produces thefollowing result:Writtencontentinthefilesuccessfully8.7 EXCEPTION WITH ARGUMENTSWhy use Argument in Exceptions?Using arguments for Exceptions in Python is useful for thefollowing reasons:It can be used to gain additionalinformation about the error encountered.As contents of an Argument can vary depending upon differenttypes of Exceptions in Python, Variables can be supplied to the Exceptionsto capture the essence of the encountered errors. Same error can occur ofdifferent causes, Arguments helps us identify the specific cause for anerror using the except clause.It can also be used to trap multiple exceptions, by using a variableto follow the tuple of Exceptions.Arguments in Buil-in Exceptions:The belowcodes demonstrates use of Argument with Built-in Exceptions:Example 1:try:b = float(100 + 50 / 0)except Exception as Argument:print( 'This is the Argument\n', Argument)Output:This is the Argumentdivision by zeroArguments in User-defined Exceptions:The below codes demonstrates use of Argument with User-definedExceptions:munotes.in

Page 122

Example 1:# create user-defined exception# derived from super classExceptionclass MyError(Exception):# Constructor or Initializerdef __init__(self, value):self.value = value# __str__ is to print() the valuedef __str__(self):return(repr(self.value))try:raise(MyError("Some Error Data"))# Value ofException is stored in errorexcept MyError as Argument:print(’This is the Argument\n’, Argument)Output:’This is the Argument’SomeErrordata’8.8 USER-DEFINED EXCEPTIONSCreating User-defined ExceptionProgrammers may name their own exceptionsby creating a newexception class. Exceptions need to be derived from the Exception class,either directly or indirectly. Although not mandatory, most of theexceptions are named as names that end in “Error” similar to naming ofthe standard exceptions inpython. For example:# A python program to create user-defined exception# class MyError is derived from super class Exceptionclass MyError(Exception):# Constructor or Initializerdef __init__(self, value):munotes.in

Page 123

self.value = value# __str__ is toprint() the valuedef __str__(self):return(repr(self.value))try:raise(MyError(3*2))# Value of Exception is stored in errorexcept MyError as error:print(’A New Exception occured: ’,error.value)Ouput:(’A New Exception occured: ’, 6)8.9SUMMARYFiles:Python supports file handling and allows users to handle files forexample, to read and write files, along with many other file handlingoptions, to operate on files. The concept of file handling has justified byvarious other languages, but theimplementation is either difficult.Python delights file differently as text or binary and this is significant.Each line of code includes a sequence of characters and they form textfile. Each line of a file is ended with a special character like comma {,}.It ends the current line and expresses the interpreter a new one hasstarted. In Pythona file is a contiguous set of bytesused to store data.This data is organized in a precise format and can be anything as simple asa text file. In the end, these byte files are then translated intobinary1and0for simple for processing. In Python, a file operation takesplace in the order like Open a file then Read or write and finally close thefile.Exceptions: Pythonprovides two important features to handle anyunexpected error in Python programs and to add debugging capabilities inthem.In Python, all exceptions must be occurrences of a class that arisesfromBaseException. In atrystatement with anexceptclausethatreferences a particular class, that clause further handles any exceptionclasses derived from that class .Two exception classes that are notconnected via sub classing are never equal, even if they have the samename. User code can advance built-in exceptions. This can be used to testan exception handler and also to report an error condition.munotes.in

Page 124

8.10QUESTIONS1.Write a Python program to read an entire text file2.Write a Python program to append text to a file and display the text3.Write a Pythonprogram to read a file line by line store it into avariable4.Write a Python program to count the number of lines in a text file5.Write a Python program to write a list to a file6.Write a Python program to extract characters from various text filesand puts them into a list.7.What are exceptions in Python?8.When would you not use try-except?9.When will the else part of try-except-else be executed?10.How can one block of except statementshandlemultipleexception? ...8.11REFERENCES1.https://www.learnpython.org/2.https://www.packtpub.com/tech/python3.https://www.softcover.io/read/e4cd0fd9/conversational-python/ch6_files_excepts4.https://docs.python.org/3/library/exceptions.html5.https://www.tutorialspoint.com/python/python_exceptions.htm6.https://www.w3schools.com/python/python_try_except.asp7.https://www.geeksforgeeks.org/python-exception-handling/8.https://www.analyticsvidhya.com/blog/2020/04/exception-handling-python/9.https://www.programiz.com/python-programming/file-operation10.https://www.geeksforgeeks.org/file-handling-python/11.https://realpython.com/read-write-files-python/12.https://www.guru99.com/reading-and-writing-files-in-python.htmlmunotes.in

Page 125

UNITIV9REGULAR EXPRESSIONUnit Structure9.0Objectives9.1Introduction9.2Concept of regular expression9.3Various types of regular expressions9.4Using match function.9.7Summary9.8Bibliography9.9Unit End Exercise9.0OBJECTIVES•Regular expressionsare particularly useful for defining filters.•Regular expressionscontain a series of characters that define apattern of text to be matched—to make a filter more specialized, orgeneral.•Theregular expression^AL[.]* searches for allitems beginning withAL.9.1 INTRODUCTIONRegular expressions (called REs, or regexes, or regex patterns) areessentially a tiny, highly specialized programming language embeddedinside Python and made available through theremodule. Using this littlelanguage, you specify the rules for the set of possible strings that you wantto match; this set might contain Englishsentences, or e-mail addresses, orTeX commands, or anything you like. You can then ask questions such as“Does this string match the pattern?”, or “Is there a match for the patternanywhere in this string?”. You can also use REs to modify a string or tosplit it apart in various ways.Regular expression patterns are compiled into a series of bytecodeswhich are then executed by a matching engine written in C. For advanceduse, it may be necessary to pay careful attention to how the engine willexecute agiven RE, and write the RE in a certain way in order to producebytecode that runs faster. Optimization isn’t covered in this document,because it requires that you have a good understanding of the matchingengine’s internals.munotes.in

Page 126

The regular expression language is relatively small and restricted,so not all possible string processing tasks can be done using regularexpressions. There are also tasks thatcanbe done with regularexpressions, but the expressions turn out to be very complicated. In thesecases,you may be better off writing Python code to do the processing;while Python code will be slower than an elaborate regular expression, itwill also probably be more understandable.9.2CONCEPT OF REGULAR EXPRESSIONYou may be familiar with searching for text by pressingctrl-F andtyping in the wordsyou’re looking for.Regular expressionsgo one step further: They allow you to specify apattern of textto search for.Regular expressions are helpful, but not many non-programmersknow about them even though mostmodern text editors and wordprocessors, such asMicrosoft WordorOpenOffice, have find andfind-and-replacefeatures that can search based on regular expressions.Regular expressions are hugetime-savers,not just for software users butalso for programmers.Finding Patterns of Text Without Regular ExpressionsSay you want to find a phone number in a string.You know the pattern:three numbers, a hyphen, three numbers, a hyphen, and four numbers.example:415-555-4242.Regular expressions, called regexes for short, are descriptions for a patternof text.For example, a\d in a regex stands for a digit character—that is, anysingle numeral 0 to 9.The regex\d\d\d-\d\d\d-\d\d\d\d is used by Python to match the same textthea string of three numbers, a hyphen, three more numbers, another hyphen,and four numbers.Any other string would not match the\d\d\d-\d\d\d-\d\d\d\d regex.But regular expressions can be much more sophisticated.munotes.in

Page 127

Example:adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match thispattern three times.”So the slightly shorter regex\d{3}-\d{3}-\d{4} also matches the correctphone number format.Symbol and it’s Meaning:
Quantifiers:
9.3VARIOUSTYPES OF REGULAR EXPRESSIONSThe "re" package provides several methods to actually performqueries on an input string. We will see the methods of re in Python:Note: Based on the regular expressions, Python offers two differentprimitive operations. Thematch method checks for a match only at thebeginning of the string while search checks for a match anywhere in thestring.
Example:adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match thispattern three times.”So the slightly shorter regex\d{3}-\d{3}-\d{4} also matches the correctphone number format.Symbol and it’s Meaning:
Quantifiers:
9.3VARIOUSTYPES OF REGULAR EXPRESSIONSThe "re" package provides several methods to actually performqueries on an input string. We will see the methods of re in Python:Note: Based on the regular expressions, Python offers two differentprimitive operations. Thematch method checks for a match only at thebeginning of the string while search checks for a match anywhere in thestring.
Example:adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match thispattern three times.”So the slightly shorter regex\d{3}-\d{3}-\d{4} also matches the correctphone number format.Symbol and it’s Meaning:
Quantifiers:
9.3VARIOUSTYPES OF REGULAR EXPRESSIONSThe "re" package provides several methods to actually performqueries on an input string. We will see the methods of re in Python:Note: Based on the regular expressions, Python offers two differentprimitive operations. Thematch method checks for a match only at thebeginning of the string while search checks for a match anywhere in thestring.
munotes.in

Page 128

 9.3.1re.search(): Finding Pattern in Text:re.search()function will search the regular expression pattern and returnthe firstoccurrence. Unlike Python re.match(), it will check all lines of theinput string. The Python re.search() function returns a match object whenthe pattern is found and “null” if the pattern is not foundIn order to use search() function, you need toimport Python remodule first and then execute the code. The Python re.search() functiontakes the "pattern" and "text" to scan from our main string.Thesearch()function searches the string for a match, and returnsaMatch objectif there is a match.If there is more than one match, only the first occurrence of thematch will be returned:Example:Search for the first white-space character in the string:importretxt ="The rain in Spain"x = re.search("\s",txt)print("The first white-space character is located in position:", x.start())output:The first white-space character is located in position: 39.3.2The split() Function:Thesplit()function returns alist where the string has been split at eachmatch:Example:Split at each white-space character:importretxt ="The rain in Spain"x = re.split("\s",txt)print(x)output:[‘The’,‘rain’,‘in’,‘Spain’]munotes.in

Page 129

 9.3.3re.findall():findall()module is used to search for “all” occurrences that matcha given pattern. In contrast,search () module will only return the firstoccurrence that matches the specified pattern.findall () will iterate over allthe lines of the file and will return allnon-overlapping matches of patternin a single step.Thefindall ()function returns a list containing all matchesExample:Print a list of all matches:importretxt ="The rain in Spain"x = re.findall("ai",txt)print(x)output:[‘ai’ , ‘ai’]Forexample, here we have a list of e-mail addresses, and we wantall the e-mail addresses to be fetched out from the list, we use the methodre.findall() in Python. It will find all the e-mail addresses from the list.9.3.4TheSub () Function:Thesub()functionreplaces the matches with the text of your choice:Replace every white-space character with the number 9:importretxt ="The rain in Spain"x = re.sub("\s","9", txt)print(x)output:The9rain9in9SpainYou can control the number of replacements by specifyingthecountparameter:Example:Replace the first 2 occurrences:munotes.in

Page 130

importretxt ="The rain in Spain"x = re.sub("\s","9", txt,2)print(x)output:The9rain9inSpain9.4 USING MATCH FUNCTIONre.match()function of re in Python will search the regularexpression pattern and return the first occurrence. The Python RegExMatch method checks for a match only at the beginning of the string. So,if a match is found in the first line, it returns thematch object. But if amatch is found in some other line, the Python RegEx Match functionreturns null.ExampleDo a search that will return a Match Object:importretxt ="The rain in Spain"x = re.search("ai",txt)print(x)#this will print anobjectoutput:<_sre.SRE_Match object; span=(5, 7), match='ai'>The Match object has properties and methods used to retrieve informationabout the search, and the result:.span()returns a tuple containing the start-, and end positions of the match..stringreturns the string passed into the function.group()returnsthe part of the string where there was a matchExample:Print the string passed into the function:importretxt ="The rain in Spain"x = re.search(r"\bS\w+", txt)munotes.in

Page 131

print(x.string)output:The rain in SpainExample:Print the part of the string where there was a match.The regular expression looks for any words that starts with an upper case"S":importretxt ="The rain in Spain"x = re.search(r"\bS\w+", txt)print(x.group())output:SpainEmail validation examplevalidate the Email from file as well from string by using RegularExpression:# importing the module re
munotes.in

Page 132

9.7 SUMMARYA regular expression in aprogramming languageis a special text stringusedfor describing a search pattern. It includes digits and punctuation andall special characters like $#@!%, etc. Expression can include literal•Text matching•Repetition•Branching•Pattern-composition etc.In Python, a regular expression is denoted as RE(REs, regexes orregex pattern) are embedded through Python re module.
munotes.in

Page 133

9.8BIBLIOGRAPHY1.Python for Beginners by Shroff Publishers2.https://www.w3schools.com/python/python_regex.asp3.https://www.tutorialspoint.com/python/python_reg_expressions.htm4.https://www.guru99.com/python-regular-expressions-complete-tutorial.html5.https://docs.python.org/3/howto/regex.html9.9 UNIT END EXERCISES1)Explain the Regular Expression and PatternMatching in details2)Write a code to Validate mobile number by using regular expressions.3)Write a code to Validate URL by using regular expressions.4)Write a code to Validate Email by using regular expressions.munotes.in

Page 134

10CLASSES AND OBJECTSUnit Structure10.0Objectives10.1Overview of OOP10.2Class Definition, Creating Objects10.3Instances as Arguments, Instances as return values10.4Built-in Class Attributes10.5Inheritance10.6Method Overriding10.7Data Encapsulation10.8Data Hiding10.9Summary10.10Unit End Exercise10.11Bibliography10.0OBJECTIVES•Classesprovide an easy way of keeping the data members andmethods together in one•Placewhich helps in keeping the program more organized.•Usingclassesalso providesanotherfunctionality of thisobject-oriented programming•Paradigm, that is, inheritance.•Classesalsohelp in overriding any standard operator10.1 OVERVIEW OF OOPPythonis an object-oriented programming language. It allows us todevelop applicationsusing Object Oriented approach. In Python, we caneasily create and use classes and objects.Major principles of object-oriented programming system are given belowObjectClassMethodInheritancemunotes.in

Page 135

PolymorphismData AbstractionEncapsulationObject:Object is an entity that has state and behavior. It may be anything. It maybe physical andlogical. For example: mouse, keyboard, chair, table, penetc.Class:Class canbe defined as a collection of objects. It is a logical entity that hassome specificattributes and methods.Inheritance:Inheritance is a feature of object-oriented programming. It specifies thatone object acquires all the properties and behaviors ofparent object. Byusing inheritance you can define a new class with a little or no changes tothe existing class. The new class is known as derived class or child classand from which it inherits the properties is alled base class or parent class.It provides re-usability of the code.Polymorphism:Polymorphism is made by two words "poly" and "morphs". Poly meansmany and Morphsmeans form, shape. It defines that one task can beperformed in different ways.For example:You have a class animal andall animals talk. But they talk differently.Here, the "talk"behavior is polymorphic in the sense and totally dependson the animal. So, the abstract"animal" concept does not actually "talk",but specific animals (like dogs and cats) have aconcrete implementationof the action "talk".Encapsulation:Encapsulation is also the feature of object-oriented programming. It isused to restrict accessto methods and variables. In encapsulation, codeand data are wrapped together within asingle unit from being modified byaccident.Data Abstraction:Data abstraction and encapsulation both are often used as synonyms. Bothare nearlysynonym because data abstraction is achieved throughencapsulation.Abstraction is used to hide internaldetails and show only functionalities.Abstractingsomething means to give names to things, so that the namecaptures the core of what afunction or a whole program does.munotes.in

Page 136

10.2 CLASS DEFINITION, CREATING OBJECTSClass:Class can be defined as acollection of objects. It is a logical entitythat has some specificattributes and methods. For example: if you have anemployee class then it should contain anattribute and method i.e. an emailid, name, age, salary etc.For example: if you have an employee class then it should contain anattribute and method i.e. an email id, name, age, salary etc.Syntax:class ClassName:...Method:Method is a function that is associated with an object. In Python, methodis not unique to class instances. Any object type can have methods.Object:Object is an entity that has state and behavior. It may be anything. It maybe physical andlogical. For example: mouse, keyboard, chair, table, penetc.Everything in Python is anobject, and almost everything has attributes andmethods. Allfunctions have a built-in attribute __doc__, which returns thedoc string defined in thefunction source code.Syntaxclass ClassName:self.instance_variable = value #value specific to instanceclass_variable = value #value shared across all class instances#accessing instance variableclass_instance = ClassName()class_instance.instance_variable#accessing class variableClassName.class_variableExampleclass Car:wheels = 4 # class variabledef __init__(self, make):munotes.in

Page 137

 self.make = make #instance variablenewCar = Car("Honda")print ("My new car is a {}".format(newCar.make))print ("My car, like all cars, has {%d}wheels".format(Car.wheels))10.3 INSTANCES AS ARGUMENTS AND INSTANCESAS RETURN VALUESFunctions and methods can return objects. This is actually nothingnew since everything inPython is an object and we have been returningvalues for quite some time.The differencehere is that we want to have themethod create an object using the constructor and then returnit as thevalue of the method.Suppose you have a point object and wish to find the midpointhalfway between it and someother target point. We would like to write amethod, call ithalfwaythat takes anotherPointasa parameter and returnsthePointthat is halfway between the point and the target.Example:class Point:def __init__(self, initX, initY):""" Create a new point at the given coordinates. """self.x = initXself.y = initYdef getX(self):return self.xdef getY(self):return self.ydef distanceFromOrigin(self):return ((self.x ** 2) + (self.y ** 2)) ** 0.5def __str__(self):return "x=" + str(self.x) + ", y=" + str(self.y)def halfway(self, target):mx = (self.x + target.x) / 2my = (self.y + target.y) / 2return Point(mx, my)p =Point(3, 4)q = Point(5, 12)mid = p.halfway(q)print(mid)print(mid.getX())print(mid.getY())munotes.in

Page 138


The resulting Point,mid, has an x value of 4 and a y value of 8.We can also use any othermethods sincemidis aPointobject.Inthe definition of themethodhalfwaysee how the requirement toalways use dot notationwith attributes disambiguates the meaning of theattributesxandy: We can always seewhether the coordinatesofPointselfortargetare being referred to.Instances as return values:When you call aninstancemethod (e.g. func ) from aninstanceobject(e.g. inst),Pythonautomatically passes thatinstanceobject as thefirstargument, in addition to anyotherargumentsthat were passed in bythe user.In the example there are twoclasses Vehicle and Truck, object of classTruck is passed asparameter to the method of class Vehicle. In methodmain() object of Vehicle is created.Then the add_truck() method of class Vehicle is called and object of Truckclass is passed asparameter.Example:class Vehicle:def __init__(self):self.trucks = []def add_truck(self, truck):self.trucks.append(truck)class Truck:def __init__(self, color):self.color = colordef __repr__(self):return "{}".format(self.color)def main():v = Vehicle()for t in 'Red Blue Black'.split():t = Truck(t)v.add_truck(t)print(v.trucks)if __name__ == "__main__":main()munotes.in

Page 139

 Sample output of above program:[Red, Blue, Black]10.4BUILT-IN CLASS ATTRIBUTESEvery Python class keeps following built-in attributes and they can beaccessed using dot operator like any other attribute−__dict__−Dictionary containing the class's namespace.__doc__−Class documentation string or none,if undefined.__name__−Class name.__module__− Module name in which the class is defined. This attributeis "__main__" in interactive mode.__bases__−A possibly empty tuple containing the base classes, in theorder of their occurrence inthe base class list.Example:For the above class let us try to access all these attributes−classEmployee:'Common base class for all employees'empCount=0def__init__(self,name,salary):self.name=nameself.salary=salaryEmployee.empCount+=1defdisplayCount(self):print"Total Employee %d"%Employee.empCountdefdisplayEmployee(self):print"Name : ",self.name,", Salary: ",self.salaryprint"Employee.__doc__:",Employee.__doc__print"Employee.__name__:",Employee.__name__print"Employee.__module__:",Employee.__module__print"Employee.__bases__:",Employee.__bases__print"Employee.__dict__:",Employee.__dict__Output:When the above code is executed, it produces the following result−Employee.__doc__:Common base class for all employeesEmployee.__name__: EmployeeEmployee.__module__: __main__Employee.__bases__: ()Employee.__dict__: {'__module__': '__main__', 'displayCount':munotes.in

Page 140

, 'empCount': 2,'displayEmployee': ,'__doc__': 'Common base class for all employees','__init__': }10.5 INHERITANCEWhat isInheritance?Inheritance is a feature of Object Oriented Programming. It is usedto specifythat one classwill get most or all of its features from its parentclass. It is a very powerful feature whichfacilitates users to create a newclass with a few or more modification to an existing class.The new class is called child class or derived class and the mainclass from which it inheritsthe properties is called base class or parentclass.The child class or derived class inherits the features from theparent class, adding newfeatures to it. It facilitates re-usability of code.Python Multilevel Inheritance:Multilevel inheritance is also possible in Python like other Object Orientedprogramminglanguages. We can inherit a derived class from anotherderived class, this process is known asmultilevel inheritance. In Python,multilevel inheritance can be done at any depth.
munotes.in

Page 141

Python MultipleInheritances:Python supports multiple inheritance too. It allows us to inheritmultiple parent classes. We can derive a child class from more thanonebase (parent) classes.
munotes.in

Page 142

10.6 METHOD OVERRIDINGMethod overriding is an ability of any object-orientedprogramming language that allows a subclass or child class to provide aspecific implementation of a method that is already provided by oneof itssuper-classes or parent classes. When a method in a subclass has the samename, same parameters or signature and same return type(or sub-type) as amethod in its super-class, then the method in the subclass is saidtooverridethe method in the super-class.
The version of a method that is executed will be determined by theobject that is used to invoke it. If an object of a parent class is used to
munotes.in

Page 143

invoke the method, then the version in the parent class will be executed,but if an object of the subclass is used to invoke the method, then theversion in the child class will be executed. In other words, it is the type ofthe object being referred to (not the type of the reference variable) thatdetermines which version of an overridden method will be executed.Example:class Parent():# Constructordef __init__(self):self.value = "Inside Parent"# Parent's show methoddef show(self):print(self.value)# Defining child classclassChild(Parent):# Constructordef __init__(self):self.value = "Inside Child"# Child's show methoddef show(self):print(self.value)# Driver's codeobj1 = Parent()obj2 = Child()obj1.show()obj2.show()Output:Inside ParentInside Child10.7DATA ENCAPSULATIONEncapsulation is one of the fundamental concepts in object-oriented programming (OOP). Itdescribes the idea of wrapping data andthe methods that work on data within oneunit. Thisputs restrictions onaccessing variables and methods directly and can prevent the accidentalmodification of data. To prevent accidental change, an object’s variablemunotes.in

Page 144

can only be changedby an object’s method. Those types of variables areknown asprivate variable.A class is an example of encapsulation as it encapsulates all thedata that is memberfunctions, variables, etc.Consider a real-life example of encapsulation, in a company, thereare different sections likethe accounts section, finance section, salessection etc. The finance section handles all thefinancial transactions andkeeps records of all the data related to finance. Similarly, the salessectionhandles all the sales-related activities and keeps records of all the sales.Nowtheremay arise a situation when for some reason an official from thefinance section needs all thedata about sales in a particular month. In thiscase, he is not allowed to directly access thedata of the sales section. Hewill first have to contact someother officer in the sales sectionand thenrequest him to give the particular data. This is what encapsulation is.# Creating a base classclass Base:def __init__(self):# Protected memberself._a = 2# Creating aderived classclass Derived(Base):def __init__(self):# Calling constructor of# Base classBase.__init__(self)print("Calling protected member of base class: ")print(self._a)obj1 = Derived()obj2 = Base()# Calling protected member# Outside class willresult in# AttributeErrorprint(obj2.a)munotes.in

Page 145

Output:Calling protected member of base class:2Traceback (most recent call last):File "/home/6fb1b95dfba0e198298f9dd02469eb4a.py", line 25, inprint(obj1.a)AttributeError: 'Base' object has no attribute 'a'10.8 DATA HIDINGWhat is Data Hiding?Data hiding is a part of object-oriented programming, which isgenerally used tohide the datainformation from the user. It includesinternal object details such as data members, internalworking. Itmaintained the data integrity and restricted access to the class member.The mainworking of data hiding is that it combines the data and functionsinto a single unit to concealdata within a class. We cannot directly accessthe data from outside the class.This process is also known as thedata encapsulation.It is doneby hiding the workinginformation to user. In the process, wedeclare classmembers as private so that no other classcan access these data members.It is accessible only within the class.Data Hiding in Python:Pythonis the most popularprogramming languageas it applies inevery technical domain andhas a straightforward syntax and vast libraries.In the official Python documentation, Datahiding isolates the client from apartof program implementation. Some of the essentialmembers must behidden from the user. Programs or modules only reflected how we coulduse them, but users cannot be familiar with how the application works.Thus it providessecurity and avoiding dependency as well.We can perform data hiding in Python using the __ doubleunderscore before prefix. Thismakes the class members private andinaccessible to the other classes.Example-classCounterClass:__privateCount=0munotes.in

Page 146

defcount(self):self.__privateCount+=1print(self.__privateCount)counter=CounterClass()counter.count()counter.count()print(counter.__privateCount)Output:12Traceback (most recent call last):File "", line 17, in AttributeError: 'CounterClass' object has no attribute '__privateCount10.9 SUMMARYIt allows us to develop applications using an Object-Orientedapproach. InPython, we caneasily create and use classes and objects. Anobject-oriented paradigm is to design theprogram using classes andobjects.Theoops conceptfocuses on writing the reusable code.10.10 UNIT END EXERCISE1)Explain the object oriented concept in details.2)Explain the instancereturn values in details3)Explain theData hidingand Data encapsulationwith examples.4)Write a python code to create animal class and in it create one instancevariable , and access it through object .5)Explain multiple and multilevel inheritance with examples10.11BIBLIOGRAPHY1.https://runestone.academy/runestone/books/published/thinkcspy/ClassesBasics/InstancesasrreturnValues.html2.https://www.tutorialspoint.com/built-in-class-attributes-in-python3.https://www.pythonlikeyoumeanit.com/Module4_OOP/Methods.html#:~:text=When%20yu%20call%20an%20instance,passed%20in%20by%20the%20user.4.https://www.geeksforgeeks.org/method-overriding-in-python/5.https://www.javatpoint.com/data-hiding-in-python.munotes.in

Page 147

 11MULTITHREADED PROGRAMMINGUnit Structure11.0Objectives11.1Introduction11.1Thread Module11.2Creating a thread11.3Synchronizing threads11.4Multithreaded priority queue11.5Summary11.6Bibliography11.7Unit End Exercise11.0OBJECTIVES•To use Multithreading•To achieve Multithreading•To use the threading module to create threads•Address issues or challenges for threads11.1 INTRODUCTIONWhat is a Thread in Computer Science?In software programming, a thread is thesmallest unit of executionwith the independent set of instructions.It is a part of the process andoperates in the same context sharing program’s runnable resources likememory. A thread has a starting point, an execution sequence, and a result.It has an instruction pointer that holds the current state of the thread andcontrols what executes next in what order.What is multithreading in Computer Science?The ability of aprocess to execute multiple threads parallelly iscalled multithreading. Ideally,multithreading can significantly improvethe performance of any program. And Python multithreading mechanismis pretty user-friendly, which you can learn quickly.munotes.in

Page 148


11.2 THREAD MODULEIt is started with Python 3, designated as obsolete, and can only beaccessedwith_threadthat supports backward compatibility.How to find Nth Highest Salary in SQLSyntax:thread.start_new_thread(function_name,args[,kwargs])To implement the thread module in Python, we need to importathreadmodule and thendefine a function that performs some action bysetting the target with a variable.Example:Thread.pyimportthread#importthethreadmoduleimporttime#importtimemoduledefcal_sqre(num):#definethecal_sqrefunctionprint("Calculatethesquarerootofthegivennumber")forninnum:time.sleep(0.3)#ateachiterationitwaitsfor0.3timeprint('Squareis:',n*n)defcal_cube(num):#definethecal_cube()functionprint("Calculatethecubeofthegivennumber")forninnum:time.sleep(0.3)#ateachiterationitwaitsfor0.3timeprint("Cubeis:",n*n*n)arr=[4,5,6,7,2]#givenarrayt1=time.time()#gettotaltimetoexecutethefunctionscal_sqre(arr)#callcal_sqre()functioncal_cube(arr)#callcal_cube()functionprint("Totaltimetakenbythreadsis:",time.time()-t1)#printthetotaltimeOutput:Calculate the square root of the given numberSquare is: 16Square is: 25Square is: 36Square is: 49munotes.in

Page 149

 Square is: 4Calculate the cube of the given numberCube is: 64Cube is: 125Cube is: 216Cube is: 343Cube is: 8Total time taken by threads is: 3.00579380989074711.3 CREATING A THREADThreadsin python are an entity within a process that can be scheduled forexecution. Insimpler words, athread is a computation process that is to beperformed by a computer. It is asequence of such instructions within aprogram that can be executed independently of othercodes.In python, there are two ways to create a new Thread. In thisarticle, we willalso be makinguse of thethreading modulein Python.Below is a detailed list of those processes:1. Creating python threads using class:Below has a coding examplefollowed by the code explanation for creatingnew threads usingClassinpython.# imprt the threading moduleimport threadingclass thread(threading.Thread):def __init__(self, thread_name, thread_ID):threading.Thread.__init__(self)self.thread_name = thread_nameself.thread_ID = thread_ID# helper function to execute the threadsdef run(self):print(str(self.thread_name) +" "+ str(self.thread_ID));thread1 = thread("GFG", 1000)thread2 = thread("IDOL", 2000);thread1.start()thread2.start()munotes.in

Page 150

print("Exit")Output:GFG 1000IDOL2000Exit2. Creating python threads using function:The below code shows the creation of new thread using a function:Example:from threading import Threadfromtime import sleep# function to create threadsdef threaded_function(arg):for i in range(arg):print("running")# wait 1 sec in between each threadsleep(1)if __name__ == "__main__":thread = Thread(target= threaded_function, args = (10, ))thread.start()thread.join()print("thread finished...exiting")Output:runningrunningrunningrunningrunningrunningrunningrunningrunningrunningthread finished...exitingSo what we did in the abovecode,We defined a function to create a thread.munotes.in

Page 151

Then we used the threading module to create a thread that invoked thefunction as its target.Then we used start() method to start the Python thread.11.4 SYNCHRONIZING THREADSThe threading moduleprovided with Python includes a simple-to-implement lockingmechanism that allows you to synchronize threads. Anew lock is created by callingtheLock()method, which returns the newlock.Theacquire(blocking)method of the new lock object is used toforce threads to runsynchronously. The optionalblockingparameterenables you to control whether the threadwaits to acquire the lock.Ifblockingis set to 0, the thread returns immediately with a 0value if the lock cannot beacquired and with a 1 ifthe lock was acquired.If blocking is set to 1, the thread blocks andwait for the lock to bereleased.Therelease()method of the new lock object is used to release the lockwhen it is no longerrequired.import threadingimport timeclass myThread (threading.Thread):def __init__(self, threadID, name, counter):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterdef run(self):print "Starting " + self.name# Get lock tosynchronize threadsthreadLock.acquire()print_time(self.name, self.counter, 3)# Free lock to release next threadthreadLock.release()def print_time(threadName, delay, counter):while counter:time.sleep(delay)print "%s: %s" % (threadName, time.ctime(time.time()))counter-= 1munotes.in

Page 152

threadLock = threading.Lock()threads = []# Create new threadsthread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# Start new Threadsthread1.start()thread2.start()# Add threads to thread listthreads.append(thread1)threads.append(thread2)# Wait for all threads to completefor t in threads:t.join()print "Exiting Main Thread"When the above code is executed, it produces the following result−StartingThread-1Starting Thread-2Thread-1: Thu Mar 21 09:11:28 2013Thread-1: Thu Mar 21 09:11:29 2013Thread-1: Thu Mar 21 09:11:30 2013Thread-2: Thu Mar 21 09:11:32 2013Thread-2: Thu Mar 21 09:11:34 2013Thread-2: Thu Mar 21 09:11:36 2013Exiting Main Thread11.5MULTITHREADED PRIORITY QUEUEThe Queue module is primarily used to manage to process largeamounts of data on multiplethreads. It supports the creation of a newqueue object that can take a distinct number ofitems.Theget()andput()methodsare used to add or remove items froma queue respectively.Below is the list of operations that are used to manage Queue:get():It is used to add an item to a queue.put():It is used to remove an item from a queue.qsize():It is used to find thenumber of items in a queue.empty():It returns a boolean value depending upon whether the queue isempty or not.munotes.in

Page 153

full():It returns a boolean value depending upon whether the queueisfull or not.APriority Queueis an extension of the queue with the followingproperties:An element with high priority is dequeued before an element with lowpriority.If two elements have the same priority, they are servedaccording to theirorder in the queue.Below is a code example explaining the process of creating multi-threadedpriority queue:Example:import queueimport threadingimport timethread_exit_Flag = 0class sample_Thread (threading.Thread):def__init__(self, threadID, name, q):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.q = qdef run(self):print ("initializing " + self.name)process_data(self.name, self.q)print ("Exiting " + self.name)# helper function to process datadef process_data(threadName, q):while not thread_exit_Flag:queueLock.acquire()if not workQueue.empty():data = q.get()queueLock.release()print ("% s processing % s" % (threadName, data))else:queueLock.release()time.sleep(1)thread_list = ["Thread-1", "Thread-2", "Thread-3"]name_list = ["A", "B", "C", "D", "E"]munotes.in

Page 154

queueLock = threading.Lock()workQueue =queue.Queue(10)threads = []threadID = 1# Create new threadsfor thread_name in thread_list:thread = sample_Thread(threadID, thread_name, workQueue)thread.start()threads.append(thread)threadID += 1# Fill the queuequeueLock.acquire()for items in name_list:workQueue.put(items)queueLock.release()# Wait for the queue to emptywhile not workQueue.empty():pass# Notify threads it's time to exitthread_exit_Flag = 1# Wait for all threads to completefor t inthreads:t.join()print ("Exit Main Thread")Output:initializing Thread-1initializing Thread-2initializing Thread-3Thread-2 processing AThread-3 processing BThread-3 processing CThread-3 processing DThread-2 processing EExiting Thread-2Exiting Thread-1Exiting Thread-3Exit Main Threadmunotes.in

Page 155

Advantages of Multithreading:Multithreading can significantly improvethe speed of computationon multiprocessor ormulti-core systems because each processor or corehandles a separate threadconcurrently.Multithreading allows a program to remain responsive while onethread waitsfor input, andanother runs a GUI at the same time. Thisstatement holds true for both multiprocessor orsingle processor systems.All the threads of a process haveaccess to its global variables. If aglobal variable changes inone thread, it is visible to other threads as well.A thread can also have its own localvariables.Disadvantages of Multithreading:On a single processor system, multithreading won’t hit the speedof computation. Theperformance may downgrade due to the overhead ofmanaging threads.Synchronization is needed to prevent mutual exclusion whileaccessing shared resources. Itdirectly leads to more memory and CPUutilization.Multithreadingincreases the complexity of the program, thus alsomaking it difficult todebug.It raises the possibility of potential deadlocks.It may cause starvation when a thread doesn’t get regular access toshared resources. Theapplication would then fail toresume its work.11.6SUMMARYIn this Python multithreading tutorial, you’ll get to see differentmethods to create threadsand learn to implement synchronization forthread-safe operations. Each section of this post includes an example andthe samplecode to explain the concept step by step.By the way, multithreading is a core concept of softwareprogramming that almost all the high-level programming languagessupport.11.7BIBLIOGRAPHY1.https://www.javatpoint.com/multithreading-in-python-32.https://www.geeksforgeeks.org/how-to-create-a-new-thread-in-python/munotes.in

Page 156

3.https://www.tutorialspoint.com/multithreaded-priority-queue-in-python4.https://www.techbeamers.com/python-multithreading-concepts/11.8 UNIT END EXERCISE1.Explain the differencesbetween multithreading and multiprocessing?2.Explain different types of multithreading?3.Explain different types of thread states?4.Explain the wait () and sleep () methods?5.Explain different methods for threads?munotes.in

Page 157

12MODULEUnit Structure12.0Objectives12.1Introduction12.2Importing module12.3Creatingand exploring modules12.4Math module12.5Random module12.6Time module12.7Summary12.8Bibliography12.9Unit End Exercise12.0OBJECTIVES•Modulesare simply a 'program logic' or a 'pythonscript' that can beused for variety ofapplications or functions.•We can declare functions, classes etc in amodule.•The focus is to break down the code into differentmodulesso thatthere will be no orminimum dependencies on one another12.1INTRODUCTIONIf you quit from the Python interpreter and enter it again, thedefinitions you havemade(functions and variables) are lost. Therefore,if you want to write a somewhatlongerprogram, you are betteroffusing a text editor to prepare the input for theinterpreter and running itwith that file as input instead. This is known as creating ascript.As your program gets longer, you may want to split it intoseveral files foreasier maintenance. You may also want to use a handyfunction that you’ve written inseveral programs without copying itsdefinition into each program.To support this, Python has a way to putdefinitions in a file and use them in a script or inan interactive instanceof the interpreter. Such a file is called amodule; definitions fromamodule can beimportedinto other modules or into themainmodule(the collectionof variables that you have access to in a script executedat the top level and incalculator mode).munotes.in

Page 158

 12.2IMPORTINGMODULEImport in python is similar to #include header_file in C/C++.Python modules can get accessto code from another module byimporting the file/function using import.The import statement is the most common way of invoking theimport machinery, butit is not the only way.12.2.1import module_name:When the import is used, it searches for the module initially in thelocal scope by calling __import__() function.The value returned by the function is then reflected in theoutput of the initial code.Example:import mathprint(math.pi)Output:3.14159265358979312.2.2import module_name.member_name:In the above code module, math is imported, and its variablescan be accessedby considering it to be a class and pi as its object.The valueof pi is returned by __import__().pi as a whole can be imported into our initial code, rather thanimporting the whole module.Example:from math import pi# Note that in the above example,# we used math.pi. Here we have used# pi directly.print(pi)Output:3.14159265358979312.2.3from module_name import *:In the above code module, math is not imported, rather just pihas been imported as avariable.All the functions and constants can be imported using *.munotes.in

Page 159


Example:from math import *print(pi)print(factorial(6))Output:3.141592653589793720As said above import uses __import__() to search for themodule, and if not found, it wouldraise ImportErrorExample:import mathematicsprint(mathematics.pi)Output:Traceback (most recentcall last):File "C:/Users/GFG/Tuples/xxx.py", line 1, inimport mathematicsImportError: No module named 'mathematics'12.3 CREATING AND EXPLORING MODULES12.3.1What are modules in Python?Modules refer to a file containing Python statementsanddefinitions.A file containing Python code, for example:example.py, iscalled a module, and its module name would beexample.We use modules to break down large programs into smallmanageable and organized files. Furthermore, modules providereusability of code.We can define our most used functions in a module and importit, instead of copying their definitions into different programs.Let us create a module. Type the following and save it asexample.py.# Python Module exampledef add(a,b):"""This program adds twonumbers and return the result"""result = a + breturn resultmunotes.in

Page 160

 Here, we have defined afunctionadd()inside a modulenamedexample. The functiontakes in two numbers and returns theirsum.12.3.2 Importing modules:We can import the definitions inside a module to anothermodule or the interactive interpreter in Python.We use theimportkeyword to do this. To import our previouslydefinedmoduleexample, we type the following in the Python prompt.>>> import exampleThis does not import the names of the functions definedinexampledirectly in the current symbol table. It only imports themodule nameexamplethere.Using the module name we can access the function using thedot.operator. For example:>>> example.add(4,5.5)9.5Python has tons of standard modules. You can check out thefull list ofPython standard modulesand their use cases. These files arein the Lib directory inside the location where you installed Python.Standard modules can be imported the same way as we importour user-defined modules.12.3.3 Executing a Module as a Script:Any.pyfile that containsamoduleis essentially also aPythonscript, and there isn’t any reason it can’t be executed like one.Here again ismod.pyas it was defined above:mod.pys = "If Comrade Napoleon says it, it must be right."a = [100, 200, 300]def foo(arg):print(f'arg = {arg}')class Foo:passThis can be run as a script:C:\Users\john\Documents>python mod.pyC:\Users\john\Documents>There are no errors, so it apparently worked. Granted, it’s notvery interesting. As it is written, it onlydefinesobjects. Itdoesn’tdoanything with them, and it doesn’t generate any output.munotes.in

Page 161

Let’s modify the above Python module so it does generatesome output when run as a script:mod.pys = "If Comrade Napoleon says it, it must be right."a = [100, 200, 300]deffoo(arg):print(f'arg = {arg}')class Foo:passprint(s)print(a)foo('quux')x = Foo()print(x)Now it should be a little more interesting:C:\Users\john\Documents>python mod.pyIf Comrade Napoleon says it, it must be right.[100, 200, 300]arg =quux<__main__.Foo object at 0x02F101D0>Unfortunately, now it also generates output when imported as amodule:>>>>>> import modIf Comrade Napoleon says it, it must be right.[100, 200, 300]arg = quuxThis is probablynot what you want. It isn’t usual for a moduleto generate output when it is imported.Wouldn’t it be nice if you could distinguish between when thefile is loaded as a module and when it is run as a standalone script?Ask and ye shall receive.When a.pyfile is imported as a module, Python sets thespecialdundervariable__name__to the name of the module.However, if a file is run as a standalone script,__name__is(creatively) set to the string'__main__'. Using this fact, you candiscern which is the case at run-time and alter behavior accordingly:mod.pys = "If Comrade Napoleon says it, it must be right."a = [100, 200, 300]def foo(arg):print(f'arg = {arg}')munotes.in

Page 162

class Foo:passif (__name__ == '__main__'):print('Executing as standalonescript')print(s)print(a)foo('quux')x = Foo()print(x)Now, if you run as a script, you get output:C:\Users\john\Documents>python mod.pyExecuting as standalone scriptIf Comrade Napoleon says it, it must be right.[100, 200, 300]arg = quux<__main__.Foo object at 0x03450690>12.4MATH MODULEPython math module is defined as the most famousmathematical functions, which includes trigonometric functions,representation functions, logarithmic functions, etc. Furthermore, italso defines two mathematical constants, i.e., Pie and Euler number,etc.Pie (n):It is a well-known mathematical constant and defined as theratio of circumstance to the diameter of a circle. Its value is3.141592653589793.Euler's number(e):It is defined asthe base of the natural logarithmic,and its value is 2.718281828459045.There are different math modules which are given below:math.log ()This method returns the natural logarithm of a given number. It iscalculated to the base e.ExampleHTMLTutorialimportmathnumber=2e-7#smallvalueofofxprint('log(fabs(x),base)is:',math.log(math.fabs(number),10))Output:log(fabs(x), base) is :-6.698970004336019

Page 163

This method returns base 10 logarithm of the given number andcalled the standard logarithm.Exampleimportmathx=13#smallvalueofofxprint('log10(x)is:',math.log10(x))Output:log10(x) is : 1.1139433523068367math.exp()This method returns a floating-point number after raising e tothe givennumber.Exampleimportmathnumber=5e-2#smallvalueofofxprint('Thegivennumber(x)is:',number)print('e^x(usingexp()function)is:',math.exp(number)-1)Output:The given number (x) is : 0.05e^x (using exp() function) is : 0.05127109637602412math.pow(x,y)This method returns the power of the x corresponding to thevalue of y. If value of x is negative or y is not integer value than itraises a ValueError.Exampleimportmathnumber=math.pow(10,2)print("Thepowerofnumber:",number)Output:The power of number: 100.0math.floor(x)This method returns the floor value of the x. It returns the lessthan or equal value to x.Example:importmathnumber=math.floor(10.25201)print("Thefloorvalueis:",number)munotes.in

Page 164

Output:The floor value is: 10math.ceil(x)This method returns the ceil value of the x. It returns the greater thanor equal value to x.importmathnumber=math.ceil(10.25201)print("Thefloorvalueis:",number)Output:Thefloor value is: 11math.fabs(x)This method returns the absolute value of x.importmathnumber=math.fabs(10.001)print("Thefloorabsoluteis:",number)Output:The absolute value is: 10.001math.factorial()This method returns the factorial of the given number x. If x isnot integral, it raises aValueError.Exampleimportmathnumber=math.factorial(7)print("Thefactorialofnumber:",number)Output:The factorial of number: 5040math.modf(x)This method returns the fractional andinteger parts of x. It carries thesign of x is float.Exampleimportmathnumber=math.modf(44.5)print("Themodfofnumber:",number)Output:The modf of number: (0.5, 44.0)Python provides the several math modules which can performthe complextask in single-line of code.Here, we have discussed a fewimportant math modules.munotes.in

Page 165

12.5 RANDOM MODULEThe Python random module functions depend on a pseudo-random number generator function random(), which generates the floatnumber between 0.0 and 1.0.There are different types of functions used in a random module whichis given below:random.random()This function generates a random float number between 0.0 and 1.0.random.randint()This function returns a random integer between the specifiedintegers.random.choice()This function returns a randomly selected element from a non-emptysequence.ExampleHello Java Program for Beginners#importing"random”module.importrandom#Weareusingthechoice()functiontogeneratearandomnumberfrom#thegivenlistofnumbers.print("Therandomnumberfromlistis:",end="")print(random.choice([50,41,84,40,31]))Output:The random number from list is : 84random.shuffle()This function randomly reorders the elements in the list.random.randrange(beg,end,step)This function is used to generate a number within the rangespecified in its argument. It accepts three arguments, beginningnumber, last number, and step, which is used to skip a number in therange.Consider the following example.#Weareusingrandrange()functiontogenerateinrangefrom100#to500.Thelastparameter10isstepsizetoskip#tennumberswhenselecting.importrandomprint("Arandomnumberfromrangeis:",end="")print(random.randrange(100,500,10))munotes.in

Page 166

Output:Arandom number from range is : 290random.seed()This function is used to apply on the particular random number withthe seed argument. It returns the mapper value. Consider the followingexample.#importing"random"module.importrandom#usingrandom()togeneratearandomnumber#between0and1print("Therandomnumberbetween0and1is:",end="")print(random.random())#usingseed()toseedarandomnumberrandom.seed(4)Output:The random number between 0 and 1 is :0.440557666898103312.6 TIME MODULEPython has defined amodule, “time” which allows us to handlevarious operations regarding time, its conversions and representations,which find its use invarious applications in life. The beginning of timeis started measuring from1 January, 12:00 am, 1970and this verytime is termed as “epoch” in Python.Operations onTime:1.time ():-This function is used to count the number ofsecondselapsedsince the epoch.2.gmtime(sec):-This function returns astructure with 9valueseach representing a time attribute in sequence. Itconvertsseconds into time attributes(days, years, monthsetc.)till specified seconds from epoch. If no seconds arementioned, time is calculated till present. The structure attributetable is given below.IndexAttributesValues0tm_year20081tm_mon1 to 122tm_mday1 to 313tm_hour0 to 234tm_min0 to 595tm_sec0 to 61 (60 or 61 are leap-seconds)6tm_wday0 to 67tm_yday1 to 3668tm_isdst-1, 0, 1 where-1 means Librarydetermines DSTmunotes.in

Page 167

# Pythoncode to demonstrate the working of# time() and gmtime()#importing "time" module for time operationsimport time# using time() to display time since epochprint ("Seconds elapsed since the epoch are : ",end="")print (time.time())# using gmtime()to return the time attribute structureprint ("Time calculated acc. to given seconds is : ")print (time.gmtime())Output:Seconds elapsed since the epoch are : 1470121951.9536893Time calculated acc. to given seconds is :time.struct_time(tm_year=2016,tm_mon=8, tm_mday=2,tm_hour=7, tm_min=12, tm_sec=31, tm_wday=1,tm_yday=215, tm_isdst=0)3. asctime(“time”):-This function takes a time attributed stringproduced by gmtime() and returns a24 character string denotingtime.4. ctime(sec):-Thisfunction returns a24 character time stringbuttakes seconds as argument andcomputes time till mentionedseconds. If no argument is passed, time is calculated till present.# Python code to demonstrate the working of# asctime() and ctime()#importing "time" module for time operationsimport time# initializing time using gmtime()ti = time.gmtime()# using asctime() to display time acc. to time mentionedprint ("Time calculated using asctime() is : ",end="")print (time.asctime(ti))# using ctime() to display time string using secondsprint ("Time calculated using ctime() is : ", end="")print (time.ctime())Output:Time calculated using asctime() is : Tue Aug 2 07:47:02 2016Time calculated using ctime() is : Tue Aug 2 07:47:02 20165.sleep(sec):-This method is used tohalt the programexecutionfor the time specified in the arguments.munotes.in

Page 168

 Python# Python code to demonstrate the working of# sleep()#importing "time" module for time operationsimport time# using ctime() toshow present timeprint ("Start Execution : ",end="")print (time.ctime())# using sleep() to hault executiontime.sleep(4)# using ctime() to show present timeprint ("Stop Execution : ",end="")print (time.ctime())Python# Python code todemonstrate the working of# sleep()#importing "time" module for time operationsimport time# using ctime() to show present timeprint ("Start Execution : ",end="")print (time.ctime())# using sleep() to hault executiontime.sleep(4)# using ctime() to show present timeprint ("Stop ExecutionOutput:Start Execution : Tue Aug 2 07:59:03 2016Stop Execution : Tue Aug 2 07:59:07 201612.7 SUMMARYAmoduleis aPythonobject with arbitrarily named attributesthat you can bind and reference.Simply, amoduleis a file consistingofPythoncode.Amodulecan define functions, classes and variables.Again, we have seen various in-built module like math, time, randommodules.munotes.in

Page 169


12.8 UNIT END EXERCISE1.Explain the concept of Module in detailwith examples.2.Write a python code to execute module as script.3.Explain the dir ( ) Function in details.4.What is package? Write a python code to create package of FRUITand create two modules APPLE and ORANGE in it and it containsapple and orange classes respectively. Create test script.py fileaccess both the module in it.5.Write shortnotes:a) Standard moduleb) Intra package referencesc) Module search path12.9BIBLIOGRAPHY1.https://docs.python.org/3/tutorial/modules.html2.https://www.geeksforgeeks.org/import-module-python/3.https://realpython.com/python-modules-packages/#executing-a-module-as-a-script4.https://www.programiz.com/python-programming/modules5.https://www.javatpoint.com/python-math-modulemunotes.in

Page 170

UNIT V13CREATING THE GUI FORMAND ADDING WIDGETSUnit Structure13.1Objectives13.2Introduction13.3Widgets1.Label2.Button3.Entry Textbox4.Combobox5.Check Button6.Radio Button7.Scroll bar8.List box9.Menubutton10.Spin Box11.Paned Window12.Tk Message Box13.4Summary13.5Questions13.6References13.1OBJECTIVESAt the end of this unit, the student will able to•Design GUI form using any widgets like button, label, checkbutton•Demonstrate the properties of widget learned in chapter13.2 INTRODUCTION1.In python GUI recipes are build using standard built in library ofpython known as Tkinter.2.Tkinter is used for creating desktop application.3.Steps to install python and environment for Tkintermunotes.in

Page 171


3.1 Prequisite to have installed python in your machine, but check versionmust be above 3.0 to run tkinter properly3.2 Next download the python IDE known as pycharm from the linkgiven-https://www.jetbrains.com/pycharm/
3.3Download Pycharm Community version for trial of 30 days.3.4Once the download is complete, run the exe for install pycharm.The setup wizard should have started. Click Next as shown in figurebelow
3.5 On the next screen, change the installation path if required. ClickonNext as shown in figure below
munotes.in

Page 172

 3.6 On the Next Screen, you can create a desktop shortcut if you want andclick on “Next”
3.7 Choose the start menu folder. Keep selected Jetbrains and click on“Install”
munotes.in

Page 173

 3.8Wait for the Installation to finish
3.9Once installation finished, you should receive a message screen thatpycharm is installed. If you want to go ahead and run it, Click the“Run Pycharm Community edition” box first and click finish.
munotes.in

Page 174

 3.10After you click on “Finish”, the Followingscreen will appear
4An empty Tkinter top-level window can be created by using thefollowing steps4.1import the Tkinter Module4.2Create the main application window4.3Add the widgets like labels, buttons, frames etc to the window4.4Call themain event loop so that the actions can take place on theusers computer screen
munotes.in

Page 175

13.3 WIDGETSThere are various widgets like button, canvas, check button, entry etc. thatare used to build the python GUI application1Label1A label is a text used todisplay some message or information aboutthe other widgets2Syntax w= Label(master,options)3A list of optionare as followsSr.NoOptionDescription1AnchorIt specifies the exact position of the text withinthe size provided to the widget. Thedefaultvalue is CENTER, which is used to center thetext within the specified space2bgThe background color displayed behind thewidget3bitmapIt is used to set the bitmap to the graphical objectspecified so that, the label can represent thegraphics instead of text.4bdIt represents the width of the border. The defaultis 2 pixels.5cursorThe mouse pointer will be changed to the type ofthe cursor specified, i.e., arrow, dot, etc.6fontThe font type of the text written inside thewidget7fgThe foreground color of the text written insidethe widget.8heightThe height of the widget9imageThe image that is to be shown as the label10justifyIt is used to represent the orientation of the textif the text contains multiple lines. It can be set toLEFT for left justification, RIGHT for rightjustification, and CENTER for centerjustification11PadxThe horizontal padding of the text. The defaultvalue is 112PadyThe vertical padding of the text. The defaultvalue is 1.13ReleifThe type of the border. The default value isFLAT.14TextThis is set to the string variable which maycontain one or more line of text.15textvariableThe text written inside the widget is set to thecontrol variable StringVar so that it can beaccessed and changed accordingly.munotes.in

Page 176

16underlineWe can display a line under the specified letterof the text. Set this option to the number of theletter under which the line will be displayed.17widthThe width of the widget. It is specified as thenumber of characters.18WraplengthInstead of having only one line as the label text,we can break it to the number of lines whereeach line has the number of characters specifiedto this option.3 Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Add a titlewin.title("Label GUI")#Adding a labelttk.Label(win,text="A label").grid(column=0,row=0)#start GUIwin.mainloop()After executing this program on pycharm using run command, the outputof above code as shown belowFig 1 Label Widget2 Button:1. The button widget is used to add various types of buttons to the pythonapplication. Python allows the look of the button according to ourrequirements.2.Various options can be set or reset depending upon the requirements.3.We can also associate a method or function with a button which iscalled when the button is pressed.4SyntaxW=Button(parent,options)5.A list of possible options is illustrated in table below
16underlineWe can display a line under the specified letterof the text. Set this option to the number of theletter under which the line will be displayed.17widthThe width of the widget. It is specified as thenumber of characters.18WraplengthInstead of having only one line as the label text,we can break it to the number of lines whereeach line has the number of characters specifiedto this option.3 Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Add a titlewin.title("Label GUI")#Adding a labelttk.Label(win,text="A label").grid(column=0,row=0)#start GUIwin.mainloop()After executing this program on pycharm using run command, the outputof above code as shown belowFig 1 Label Widget2 Button:1. The button widget is used to add various types of buttons to the pythonapplication. Python allows the look of the button according to ourrequirements.2.Various options can be set or reset depending upon the requirements.3.We can also associate a method or function with a button which iscalled when the button is pressed.4SyntaxW=Button(parent,options)5.A list of possible options is illustrated in table below
16underlineWe can display a line under the specified letterof the text. Set this option to the number of theletter under which the line will be displayed.17widthThe width of the widget. It is specified as thenumber of characters.18WraplengthInstead of having only one line as the label text,we can break it to the number of lines whereeach line has the number of characters specifiedto this option.3 Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Add a titlewin.title("Label GUI")#Adding a labelttk.Label(win,text="A label").grid(column=0,row=0)#start GUIwin.mainloop()After executing this program on pycharm using run command, the outputof above code as shown belowFig 1 Label Widget2 Button:1. The button widget is used to add various types of buttons to the pythonapplication. Python allows the look of the button according to ourrequirements.2.Various options can be set or reset depending upon the requirements.3.We can also associate a method or function with a button which iscalled when the button is pressed.4SyntaxW=Button(parent,options)5.A list of possible options is illustrated in table below
munotes.in

Page 177

Sr.NoOptionDescription1.activebackgroundIt represents the background of the buttonwhen the mouse hover the button.2.activeforegroundIt represents the font color of the buttonwhen the mouse hover the button.3.BdIt represents the border width in pixels.4.BgIt represents the background color ofthebutton.5.CommandIt is set to the function call which isscheduled when the function is called.6.FgForeground color of the button.7.FontThe font of the button text8.HeightThe height of the button. The height isrepresented in the numberof text lines forthe textual lines or the number of pixelsfor the images.9.HighlightColorThe color of the highlight when thebutton has the focus.10.ImageIt is set to the image displayed on thebutton.11.justifyIt illustrates the way by whichthemultiple text lines are represented. It isset to LEFT for left justification, RIGHTfor the right justification, and CENTERfor the center.12.PadxAdditional padding to the button in thehorizontal direction.13.PadyAdditional padding to the button in thevertical direction.14.ReliefIt represents the type of the border. It canbe SUNKEN, RAISED, GROOVE, andRIDGE.15.StateThis option is set to DISABLED to makethe button unresponsive. The ACTIVErepresents the active state of the button.16.UnderlineSet this option to make the button textunderlined.17.WidthThe width of the button. It exists as anumber of letters for textual buttons orpixels for image buttons.18.WraplengthIf the value is set to a positive number,the text lines will be wrapped to fit withinthis length.munotes.in

Page 178

6.Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Adding a label that will get modifieda_label=ttk.Label(win,text="A Label")a_label.grid(column=0,row=0)#Button click Event Functiondefclick_me():action.configure(text="** I have been clicked! **")a_label.configure(foreground='red')a_label.configure(text='A Red Label')#Adding a Buttonaction=ttk.Button(win,text="Click Me!",command=click_me)action.grid(column=1,row=0)#start Guiwin.mainloop()Here Win is the parent of Button. The output of above code is shownbelow
Fig 2 Button Widget3.Entry TextBox:1.The Entry widget is used to provide the single line text-box to the userto accept a value fromthe user.2.We can use this widget to accept the text strings from the user. It canonly be used for one line of text from the user.3.For multiple lines of text, we must use the text widget.4.SyntaxW=Entry(parent,options)5.A list of possibleoptions is given belowSr.NoOptionDescription1.bgThe background color of the widget2.bdThe border width of the widget inpixels
6.Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Adding a label that will get modifieda_label=ttk.Label(win,text="A Label")a_label.grid(column=0,row=0)#Button click Event Functiondefclick_me():action.configure(text="** I have been clicked! **")a_label.configure(foreground='red')a_label.configure(text='A Red Label')#Adding a Buttonaction=ttk.Button(win,text="Click Me!",command=click_me)action.grid(column=1,row=0)#start Guiwin.mainloop()Here Win is the parent of Button. The output of above code is shownbelow
Fig 2 Button Widget3.Entry TextBox:1.The Entry widget is used to provide the single line text-box to the userto accept a value fromthe user.2.We can use this widget to accept the text strings from the user. It canonly be used for one line of text from the user.3.For multiple lines of text, we must use the text widget.4.SyntaxW=Entry(parent,options)5.A list of possibleoptions is given belowSr.NoOptionDescription1.bgThe background color of the widget2.bdThe border width of the widget inpixels
6.Code:importtkinterastkfromtkinterimportttk#create Instancewin=tk.Tk()#Adding a label that will get modifieda_label=ttk.Label(win,text="A Label")a_label.grid(column=0,row=0)#Button click Event Functiondefclick_me():action.configure(text="** I have been clicked! **")a_label.configure(foreground='red')a_label.configure(text='A Red Label')#Adding a Buttonaction=ttk.Button(win,text="Click Me!",command=click_me)action.grid(column=1,row=0)#start Guiwin.mainloop()Here Win is the parent of Button. The output of above code is shownbelow
Fig 2 Button Widget3.Entry TextBox:1.The Entry widget is used to provide the single line text-box to the userto accept a value fromthe user.2.We can use this widget to accept the text strings from the user. It canonly be used for one line of text from the user.3.For multiple lines of text, we must use the text widget.4.SyntaxW=Entry(parent,options)5.A list of possibleoptions is given belowSr.NoOptionDescription1.bgThe background color of the widget2.bdThe border width of the widget inpixels
munotes.in

Page 179

3.cursorThe mouse pointer will be changed tothe cursor type set to the arrow, dot etc.4.exportselectionThetext written inside the entry boxwill be automatically copied to theclipboard by default. We can set theexportselection to 0 to not copy this.5.fgIt represents the color of the text6.fontIt represents the font type of the text7.highlightbackgroundIt represents the color to display in thetraversal highlight region when thewidget does not have the input focus.8.highlightcolorIt represents the color to display in thetraversal highlight region when thewidget does not have the input focus.9.highlightthicknessIt represents a non-negative valueindicating the width of the highlightrectangle to draw around the outside ofthe widget when it has the input focus.10.InsertbackgroundIt represents the color to use asbackground in the areacovered by theinsertion cursor. This color willnormally override either the normalbackground for the widget.11.insertbackgroundIt representsthe color to use asbackground in the are covered by theinsertion cursor. This color willnormally overrideeither the normalbackground for the widget.12.justifyIt specifies how the text is orgranized ifthe text contains multiple lines.13.reliefIt specifies the type of the border. Itsdefault value is flat.14.selectbackgroundThe background color of the selectedtext.15.showIt is used to show the entry text of someother type instead of the string. Forexample the password is typed usingstars(*).16.textvariableIt is set to the instance of the Stringvarto retrieve the text from the entry.17.WidthThe width of the displayed text orimage.18.xscrollcommandThe entry widget can be linked to thehorizontal scrollbar if we want the userto enter more text then the actual widthof the widget.munotes.in

Page 180

6 Code Snippet:14768::215:-8)9:2.864:215:-814768:::2+8-):- 59:)5+-=15:2 $2!6,1.1-, ;::65 31+2 ;5+:165,-.+31+2(4-)+:165 +65.1/;8-:->:-3365)4- /-:+0)5/15/ 6;8 3)*-3::2 )*-3=15:->:5:-8 ) 5)4- /81,+63;45
86=
,,15/ ) :->: *6> 5:8? '1,/-:5)4-:2 #:815/&)85)4-(-5:-8-,::2 5:8?=15=1,:0 :->:<)81)*3-5)4-5)4-(-5:-8-, /81,+63;45
86= ),,15/ ) ;::65)+:165::2 ;::65=15:->:31+2 !-+644)5,+31+2(4-)+:165 /81,+63;45 86=
#:)8: %=15 4)153667";:7;:Fig 3 Text boxWidget13.4 COMBOBOX1code snippet:
6 Code Snippet:14768::215:-8)9:2.864:215:-814768:::2+8-):- 59:)5+-=15:2 $2!6,1.1-, ;::65 31+2 ;5+:165,-.+31+2(4-)+:165 +65.1/;8-:->:-3365)4- /-:+0)5/15/ 6;8 3)*-3::2 )*-3=15:->:5:-8 ) 5)4- /81,+63;45
86=
,,15/ ) :->: *6> 5:8? '1,/-:5)4-:2 #:815/&)85)4-(-5:-8-,::2 5:8?=15=1,:0 :->:<)81)*3-5)4-5)4-(-5:-8-, /81,+63;45
86= ),,15/ ) ;::65)+:165::2 ;::65=15:->:31+2 !-+644)5,+31+2(4-)+:165 /81,+63;45 86=
#:)8: %=15 4)153667";:7;:Fig 3 Text boxWidget13.4 COMBOBOX1code snippet:
6 Code Snippet:14768::215:-8)9:2.864:215:-814768:::2+8-):- 59:)5+-=15:2 $2!6,1.1-, ;::65 31+2 ;5+:165,-.+31+2(4-)+:165 +65.1/;8-:->:-3365)4- /-:+0)5/15/ 6;8 3)*-3::2 )*-3=15:->:5:-8 ) 5)4- /81,+63;45
86=
,,15/ ) :->: *6> 5:8? '1,/-:5)4-:2 #:815/&)85)4-(-5:-8-,::2 5:8?=15=1,:0 :->:<)81)*3-5)4-5)4-(-5:-8-, /81,+63;45
86= ),,15/ ) ;::65)+:165::2 ;::65=15:->:31+2 !-+644)5,+31+2(4-)+:165 /81,+63;45 86=
#:)8: %=15 4)153667";:7;:Fig 3 Text boxWidget13.4 COMBOBOX1code snippet:
munotes.in

Page 181


OuputFig 4 output of Combobox5.Checkbutton:1.The checkbutton is used to display the checkbutton on the window.2.It is used to track the user’s choices provided to the application. Inother words, we can say that checkbutton is used to implement theon/off selections.3.The checkbutton can obtain the text or images. The checkbutton ismostly used to provide many choices to the user among which, theuser needs to choose the one. It generally implementsmany of manyselections.4.syntaxW=checkbutton(master,options)5.A list of possible options is given belowSr.NoOptionDescription1.bitmapIt displays an image (monochrome)on the button.2.commandIt is associated with a function to becalled when the state of thecheckbutton is changed.3.highlightcolorThe color of the focus highlight whenthe checkbutton is under focus.4.justifyThis specifies the justification of thetext if the text contains multiple lines.5.offvalueThe associatedcontrol variable is setto 0 by default if the button isunchecked. We can change the stateof an unchecked variable to someother one.6.onvalueThe associated control variable is setto 1 by default if the button ischecked. We can change the state ofthe checked variable to some otherone.7.VariableIt represents the associated variablethat tracks the state of the checkbutton8.WidthIt represents the width of thecheckbutton. It is represented in thenumber of characters that arerepresented inthe form of texts. 
OuputFig 4 output of Combobox5.Checkbutton:1.The checkbutton is used to display the checkbutton on the window.2.It is used to track the user’s choices provided to the application. Inother words, we can say that checkbutton is used to implement theon/off selections.3.The checkbutton can obtain the text or images. The checkbutton ismostly used to provide many choices to the user among which, theuser needs to choose the one. It generally implementsmany of manyselections.4.syntaxW=checkbutton(master,options)5.A list of possible options is given belowSr.NoOptionDescription1.bitmapIt displays an image (monochrome)on the button.2.commandIt is associated with a function to becalled when the state of thecheckbutton is changed.3.highlightcolorThe color of the focus highlight whenthe checkbutton is under focus.4.justifyThis specifies the justification of thetext if the text contains multiple lines.5.offvalueThe associatedcontrol variable is setto 0 by default if the button isunchecked. We can change the stateof an unchecked variable to someother one.6.onvalueThe associated control variable is setto 1 by default if the button ischecked. We can change the state ofthe checked variable to some otherone.7.VariableIt represents the associated variablethat tracks the state of the checkbutton8.WidthIt represents the width of thecheckbutton. It is represented in thenumber of characters that arerepresented inthe form of texts.

OuputFig 4 output of Combobox5.Checkbutton:1.The checkbutton is used to display the checkbutton on the window.2.It is used to track the user’s choices provided to the application. Inother words, we can say that checkbutton is used to implement theon/off selections.3.The checkbutton can obtain the text or images. The checkbutton ismostly used to provide many choices to the user among which, theuser needs to choose the one. It generally implementsmany of manyselections.4.syntaxW=checkbutton(master,options)5.A list of possible options is given belowSr.NoOptionDescription1.bitmapIt displays an image (monochrome)on the button.2.commandIt is associated with a function to becalled when the state of thecheckbutton is changed.3.highlightcolorThe color of the focus highlight whenthe checkbutton is under focus.4.justifyThis specifies the justification of thetext if the text contains multiple lines.5.offvalueThe associatedcontrol variable is setto 0 by default if the button isunchecked. We can change the stateof an unchecked variable to someother one.6.onvalueThe associated control variable is setto 1 by default if the button ischecked. We can change the state ofthe checked variable to some otherone.7.VariableIt represents the associated variablethat tracks the state of the checkbutton8.WidthIt represents the width of thecheckbutton. It is represented in thenumber of characters that arerepresented inthe form of texts.munotes.in

Page 182

 9.WraplengthIf this option is set to an integernumber, the text will be broken in tothe number of pieces.6.Code Snippet:
Output:Fig 5 Output of checkbutton6.Radio Button:1.The Radiobutton is different from a checkbutton. Here the user isprovided with various options and the user can select only one optionamong them.2.It is used to implement one-of-many selection in the pythonapplication. It shows multiple choices to the user out of which, the usercan select only one out of them.3.We can associate different methods with each of the radiobutton.4.We can display the multiple line text or images on the radiobuttons.Each button displays a single value for that particular variable.5.Syntax
 9.WraplengthIf this option is set to an integernumber, the text will be broken in tothe number of pieces.6.Code Snippet:
Output:Fig 5 Output of checkbutton6.Radio Button:1.The Radiobutton is different from a checkbutton. Here the user isprovided with various options and the user can select only one optionamong them.2.It is used to implement one-of-many selection in the pythonapplication. It shows multiple choices to the user out of which, the usercan select only one out of them.3.We can associate different methods with each of the radiobutton.4.We can display the multiple line text or images on the radiobuttons.Each button displays a single value for that particular variable.5.Syntax
 9.WraplengthIf this option is set to an integernumber, the text will be broken in tothe number of pieces.6.Code Snippet:
Output:Fig 5 Output of checkbutton6.Radio Button:1.The Radiobutton is different from a checkbutton. Here the user isprovided with various options and the user can select only one optionamong them.2.It is used to implement one-of-many selection in the pythonapplication. It shows multiple choices to the user out of which, the usercan select only one out of them.3.We can associate different methods with each of the radiobutton.4.We can display the multiple line text or images on the radiobuttons.Each button displays a single value for that particular variable.5.Syntax
munotes.in

Page 183

 W=Radiobutton(top,options)6.The list of possible options given belowSr.NoOptionDescription1.commandThis option is set to the procedurewhich must be called every-timewhen the state of the radiobutton ischanged2.cursorThe mouse pointer is changed to thespecified cursor type. It can be set tothe arrow, dot, etc.3.fontIt represents the font type of thewidget text.4.fgThe normal foreground color of thewidget text5.heightThe vertical dimension of thewidget. It is specified as the numberof lines(not pixel).6.highlightcolorIt represents the color of the focushighlight when the widget has thefocus.7.stateIt represents the state of the radiobutton. The default state of theRadiobutton is NORMAL.However, we can set this toDISABLED to make theradiobutton unresponsive.8.textThe text to be displayed on theradiobutton.9.TextvariableIt is of String type that representsthe text displayed by the widget.10.ValueThe value of each radiobutton isassigned to the control variablewhenit is turned on by the user.7.Code snippet:1.fromtkinterimport*2.3.defselection():4.selection="Youselectedtheoption"+str(radio.get())5.label.config(text=selection)6.7.top=Tk()8.top.geometry("300x150")9.radio=IntVar()10.lbl=Label(text="Favouriteprogramminglanguage:")munotes.in

Page 184

 11.lbl.pack()12.R1=Radiobutton(top,text="C",variable=radio,value=1,13.command=selection)14.R1.pack(anchor=W)15.16.R2=Radiobutton(top,text="C++",variable=radio,value=2,17.command=selection)18.R2.pack(anchor=W)19.20.R3=Radiobutton(top,text="Java",variable=radio,value=3,21.command=selection)22.R3.pack(anchor=W)23.24.label=Label(top)25.label.pack()26.top.mainloop()Output:
Fig 6 Output of radiobutton13.3.7 Scrollbar:1It provides the scrollbar to the user so that the user can scroll thewindow up and down.2This widget is used to scroll down the content of the other widgets likelistbox, text and canvas. However, wecan also create the horizontalscrollbars to the entry widget.3The syntax to use the scrollbar widget is give belowW=Scrollbar(top,options)4A list of possible options is given below
munotes.in

Page 185

Sr.No.optionDescription1orientIt can be set to HORIZONTAL orVERTICAL depending upon the orientationof the scrollbar.2jumpIt is used to control the behavior of the scrolljump. If it set to 1, then the callback is calledwhen the user releases the mouse button.3repeatdelayThis option tells the duration up to which thebutton is to be pressed before the slider startsmoving in that direction repeatedly. Thedefault is 300 ms.4takefocusWe can tab the focus through this widget bydefault. We can set this option to 0 if we don'twant this behavior.5troughcolorIt represents the color of the trough.6widthIt represents the width of the scrollbar5.Code snippet:fromtkinterimport*top=Tk()sb=Scrollbar(top)sb.pack(side=RIGHT,fill=Y)mylist=Listbox(top,yscrollcommand=sb.set)forlineinrange(30):mylist.insert(END,"Number"+str(line))mylist.pack(side=LEFT)sb.config(command=mylist.yview)mainloop()Output:
Fig 7 Output of scrollbar
munotes.in

Page 186

8.Listbox:1.The listbox widget is used to display a list of options to the user.2.It is used to display the list items to the user. We can place only textitems in the ListBox and all text items contain the same font and color.3.The user can choose one or more items from the list depending uponthe configuration.4.The syntax to use the listbox is given belowW=ListBox(parent,options)5.A list of possible options is given belowSr.NoOptionsDescription1selectbackgroundThe background color that is used todisplay the selected text2selectmodeIt is used to determine the number ofitems that can be selected from the list. Itcan set to BROWSE, SINGLE,MULTIPLE, EXTENDED.3widthIt represents the width of the widget incharacters.4XscrollCommandIt isused to let the user scroll the Listboxhorizontally.5YscrollcommandIt is used to let the user scroll the Listboxvertically.6.Code Snippet:fromtkinterimport*top=Tk()top.geometry("200x250")lbl=Label(top,text="Alistoffavouritecountries...")listbox=Listbox(top)listbox.insert(1,"India")listbox.insert(2,"USA")listbox.insert(3,"Japan")listbox.insert(4,"Austrelia")#thisbuttonwilldeletetheselecteditemfromthelistbtn=Button(top,text="delete",command=lambdalistbox=listbox:listbox.delete(ANCHOR))munotes.in

Page 187

lbl.pack()listbox.pack()btn.pack()top.mainloop()output
Fig 8 Listbox button output
Fig 9After pressing delete button-output13.3.9 Menubutton:1.The menubutton is used to display the menu items to the user. lbl.pack()listbox.pack()btn.pack()top.mainloop()output
Fig 8 Listbox button output
Fig 9After pressing delete button-output13.3.9 Menubutton:1.The menubutton is used to display the menu items to the user.
lbl.pack()listbox.pack()btn.pack()top.mainloop()output
Fig 8 Listbox button output
Fig 9After pressing delete button-output13.3.9 Menubutton:1.The menubutton is used to display the menu items to the user.munotes.in

Page 188

2.It can be defined as the drop-down menu that is shown to the user allthe time. It is used to provide the user a option to select the appropriatechoice exist within the application.3.The Menubutton is used to implement various types of menus in thepython application. A Menu is associated with the menubutton that candisplay the choices of the menubutton when clicked by the user.4.The syntax to use the python tkinter menubutton is given belowW=Menubutton(Top,options)5.code snippetfromtkinterimport*top=Tk()top.geometry("200x250")menubutton=Menubutton(top,text="Language",relief=FLAT)menubutton.grid()menubutton.menu=Menu(menubutton)menubutton["menu"]=menubutton.menumenubutton.menu.add_checkbutton(label="Hindi",variable=IntVar())menubutton.menu.add_checkbutton(label="English",variable=IntVar())menubutton.pack()top.mainloop()output
Fig 10 Output-Menubutton 2.It can be defined as the drop-down menu that is shown to the user allthe time. It is used to provide the user a option to select the appropriatechoice exist within the application.3.The Menubutton is used to implement various types of menus in thepython application. A Menu is associated with the menubutton that candisplay the choices of the menubutton when clicked by the user.4.The syntax to use the python tkinter menubutton is given belowW=Menubutton(Top,options)5.code snippetfromtkinterimport*top=Tk()top.geometry("200x250")menubutton=Menubutton(top,text="Language",relief=FLAT)menubutton.grid()menubutton.menu=Menu(menubutton)menubutton["menu"]=menubutton.menumenubutton.menu.add_checkbutton(label="Hindi",variable=IntVar())menubutton.menu.add_checkbutton(label="English",variable=IntVar())menubutton.pack()top.mainloop()output
Fig 10 Output-Menubutton
2.It can be defined as the drop-down menu that is shown to the user allthe time. It is used to provide the user a option to select the appropriatechoice exist within the application.3.The Menubutton is used to implement various types of menus in thepython application. A Menu is associated with the menubutton that candisplay the choices of the menubutton when clicked by the user.4.The syntax to use the python tkinter menubutton is given belowW=Menubutton(Top,options)5.code snippetfromtkinterimport*top=Tk()top.geometry("200x250")menubutton=Menubutton(top,text="Language",relief=FLAT)menubutton.grid()menubutton.menu=Menu(menubutton)menubutton["menu"]=menubutton.menumenubutton.menu.add_checkbutton(label="Hindi",variable=IntVar())menubutton.menu.add_checkbutton(label="English",variable=IntVar())menubutton.pack()top.mainloop()output
Fig 10 Output-Menubuttonmunotes.in

Page 189

13.3.10 Spinbox:1It is an entry widget used to select from options of values.2.The Spinbox widget is an alternative to the Entry widget. It providesthe range of values to the user, out of which, the user can select theone.3.It is used in the case where a user is given some fixed number ofvalues to choose from.4.We can use various options with the Spinbox to decorate the widget.The syntax touse the Spinbox is given below5.SyntaxW=spinbox(top, options)6.Code snippetfromtkinterimport*top=Tk()top.geometry("200x200")spin=Spinbox(top,from_=0,to=25)spin.pack()top.mainloop()
Fig 11 Menubutton
munotes.in

Page 190

13.3.11PanedWindow:1It is like a container widget that contains horizontal or vertical panes.2The PanedWindow widget acts like a Container widget which containsone or more child widgets (panes) arranged horizontally or vertically.The child panes can beresized by the user, by moving the separatorlines known as sashes by using the mouse.3Each pane contains only one widget. The PanedWindow is used toimplement the different layouts in the python applications.4The syntax to use the PanedWindow is given belowW=PanedWindow(master,options)5Code Snippetfromtkinterimport*defadd():a=int(e1.get())b=int(e2.get())leftdata=str(a+b)left.insert(1,leftdata)w1=PanedWindow()w1.pack(fill=BOTH,expand=1)left=Entry(w1,bd=5)w1.add(left)w2=PanedWindow(w1,orient=VERTICAL)w1.add(w2)e1=Entry(w2)e2=Entry(w2)w2.add(e1)w2.add(e2)bottom=Button(w2,text="Add",command=add)w2.add(bottom)mainloop()Output:
Fig 12 PanedWindow
munotes.in

Page 191


13.3.13. TkMessagebox:1. This module is used to display the message-box in the desktop basedapplications2.The messagebox module is used to display the message boxes in thepython applications. There are the various functions which are used todisplay the relevant messages depending upon the applicationrequirements.3. The syntax to use the messagebox is given below.Messagebox.function_name(title,message,[,options])4.Parameter explanation4.1function_name-It represents an appropriate message box functions4.2title-It is a string which is shown as a title of a messagebox4.3 message-It is the string to be displayed as a message on themassagebox4.4Options-There are various options which can be used toconfigure the message dialog box.5.Code Snippetfromtkinterimport*fromtkinterimportmessageboxtop=Tk()top.geometry("100x100")messagebox.askquestion("Confirm","Areyousure?")top.mainloop()Output:
Fig 12 Output-Tkmessagebox
munotes.in

Page 192

 13.4 SUMMARY1In this chapter we discussed about various widgets used in python forhandling GUI in python programming.2This chapter also revising the concept of each widget with its syntax,options, methods, code and output3In this chapter, one section is briefed about installation of pycharmrequired to handle the python tkinter for GUI purpose13.6QUESTIONSQ1Design a calculator using widget of pythonQ2Design a pendulum clockQ3Design a PingPonggame in tkinterQ4List down the various options of button widgetQ5Compare and contrast between the listbox and combobox13.5 REFERENCES1.Python GUI programming Cookbook-Burkahard A Meier, PacktPublication, 2ndEditionUseful Links1.https://www.javatpoint.com/python-tkintermunotes.in

Page 193

 14LAYOUT MANAGEMENT & LOOK& FEEL CUSTOMIZATIONUnit structure14.1Objectives14.2Introduction14.3Layout Management-Designing GUI Application with properlayoutManagement features14.4Look & Feel customization-Enhancing look & feel of GUIusingdifferent appearances of widgets.14.5Summary14.6Questions14.7References14.1 OBJECTIVESAt the end of this unit, the student will be able to•Demonstrate the appearance of Label widget•Illustrate how widgets dynamically expand the GUI•Use the grid layout manager•Describe about the message box, progress bar, canvas widget etc.14.2INTRODUCTION1.In this chapter we will explore how to manage widgets within widgetsto create our python GUI.2.Learning the fundamentals of GUI layoutdesign will enable us tocreate great-looking GUI’s3.There are certain techniques that will help us in achieving this layoutdesign better.4.The grid layout manager is one of the most important layout tools builtin to tkinter that will be used in thischapter.5.In this chapter we also going to learn how to customize some of thewidgets in our GUI by changing some of their properties.munotes.in

Page 194

 14.3 LAYOUT MANAGEMENT-DESIGNING GUIAPPLICATION WITH PROPER LAYOUTMANAGEMENT FEATURES1 Arranging severallabels within a label frame widget1.1The LabelFrame widget allows us to design our GUI in an organizedfashion. We are still using the grid layout manager as our main layoutdesign tool, but by using LabelFrame widgets, will get much morecontrol over our GUI design.1.2Pseudocode for LabelFrame is
If we run the above pseudo code the output will simulated as
Fig 1 Output-Label Frame1.3We can easily align the labels vertically by changing our code, asshown below in pseudocode
munotes.in

Page 195

 Fig 2 Output of GUILabel Frame2.Using padding to add space around widgets:1.4The procedural way of adding space around widgets is shown hereand then use of loop is done to achieve the same thing in a muchbetter way.1.5buttons_frame.grid(column=0,row=7,padx=20,pady=40), withthisstatement labelFrame gets some breathing space.
Fig 3 LabelFrame output1.6In tkinter, adding space horizontally and vertically is done by usingbuilt-in properties named padx and pady. These can be used to addspace around many widgets, improvinghorizontal and verticalalignments, respectively. We hardcoded 20 pixels of space to the leftand right of LabelFrame, and we added 40 pixels to the top andbottom of the frame. Now our LabelFrame stands out better than itdid before.1.7We can use a loop toadd space around the labels contained withinLabelFrame
munotes.in

Page 196

 Pseudocode for adding space around the labels
Fig 4 Label Frame widget with Space1.8The grid_configure() function enables us to modify the UI elementsbefore the main loop displays them. So, instead of hardcoding valueswhen we first create a widget, we can work on our layout and thenarrange spacing towards the end of our file, just before the GUI iscreated.1.9The winfo_children() function returns a list of all the childrenbelonging to the buttons_frame variable. This enables us to loopthrough them and assign the padding to each label.3.How widgets dynamically expand the GUI:1.10Javaintroduced the concept of dynamic GUI layout management. Incomparison, visual development IDEs, such as VS.NET, layout theGUI in a visual manner and basically hardcode the x and ycoordinates of the UI elements.1.11Using tkinter, this dynamic capability creates both an advantage and alittle bit of a challenge because sometimes our GUI dynamicallyexpands when we would rather it not be so dynamic.1.12We are using the grid layout manager widget and it lays out ourwidgets in a zero based grid. This is very similar to an excelspreadsheet on a data base table.1.13The following is an example of a grid layout manager with two rowsand three columns
munotes.in

Page 197

 Row0,Col0Row 0, Col 1Row 0, Col2Row 1, Col 0Row 1, Col 1Row 1, Col21.14Using the grid layout manager, what happensis that the width of anygiven column is determined by the longest name or widget in thatcolumn. This affects all the rows.1.15By adding our LabelFrame widget and giving it a title that is longerthan some hardcoded size widget, such as the top-left label and thetext entry below it, we dynamically move those widgets to the centerof column 0, adding space on the left-and right-hand side of thosewidgets1.16The following code can be added to Label frame code shown aboveand then placed labels in to his frame4.Aligning the GUI widgets by embedding frames within frames:1.17The dynamic behavior of Python and its GUI modules can create alittle bit of a challenge to really get our GUI looking the way wewant. Here, we will embed frames within frames to get morecontrolof our layout. This will establish a stronger hierarchy among thedifferent UI elements, making the visual appearance easier to achieve.1.18Here, we will create a top-level frame that will contain other framesand widgets. This will help us get our GUI layout just the way wewant.1.19In order to do so, we will have to embed our current controls within acentral frame called ttk.LabelFrame. This frame ttk.LabelFrame is thechild of the main parent window and all controls will be the childrenof this ttk.LabelFrame.1.20We will only assign LabelFrame to our main window and after that,we will make this LabelFrame the parent container for all the widgets.
Fig 5 Hierarchy Layout in GUI
munotes.in

Page 198


In the diagram shown above,win is the variable that holds areference to our main GUI tkinter window frame, mighty is the variablethat holds a reference to our LabelFrame and is a child of the mainwindow frame (win), and Label and all other widgets are now placed intothe LabelFrame container (mighty).
Next, we will modify the following controls to use mighty as the parent,replacing win. Here is an example of how to do this
Fig 6 Output of above code5.Creating Menu bars:1We will add a menu bar to our main window,add menus to the menubar, and then add menu items to the menus.2We are creating a Menuitem for functionalities like File, Exit andHelp.
munotes.in

Page 199

 3We have to import the Menu class from tkinter. Add the following lineof code to the top of the python module, where the import statementliveas shown below in pseudocode
Next, we will create the menu bar, Add the following code towards thebottom of the module, just above where we create the main event loop
In order to make above code in workable condition,we also have to addthe menu bar and give it a label.
Fig 7 Menu item with File optionNext, we will add a second menu item to the first menu that weadded to the menu bar
munotes.in

Page 200

 Fig 8 Menu item with Exit optionNext, we will add a helpfunctionalities to our existing menu
munotes.in

Page 201

Fig 9 Menu item with Help optionNext, we will add menu bar exit functionalities
6.Creating tabbed widgets:1.21We will create tabbed widgets to further organize our expandingGUI written in tkinter1.22Pseudocode forSame
munotes.in

Page 202

Fig 10 Tabbed GUI7.Using the grid layout manager1.23The grid layout manager is one of the most useful layout tools.1.24Pseudocode to add grid layout in any python GUI codeTkinter automatically adds the missing row where we did not specify anyparticular row.14.4 Look & Feel customization-Enhancing look & feel ofGUI using different appearances of widgets1.Creating message boxes-information warning and error1.1A message box is a pop-up window that gives feedback to the user. Itcan beinformational, hinting at potential problems as well ascatastrophic errors.1.2Using python to create message boxes is very easy.1.3Add the following line of code to the top of the module where theimport statement live
Next, create a callback functionthat will display a message box.We have to locate the code of the call back above the code where weattach the callback to the menu item, because this is still procedural andnot OOP code.
munotes.in

Page 203

Add the following code just above the lines where we create thehelp menu
Fig 11 A Help Message boxNext, transform the above code in to a warning message box pop-upwindow, instead.
Fig 12 A warning MessageNext we will add error message code to show error message box
munotes.in

Page 204

Fig 13 A error message box2.How to create independent message boxes:1.4We will create out tkinter message boxes as stand-alone top-level GUIwindows.1.5So, why would we wish to create an independent message box? Onereason is that we might customize our message boxes and reuse themin several of our GUIs. Instead of having to copy and paste the samecode in to every python GUI we design.
Fig 14 Undesired Output of Message box1.6We still need a title and we definitely want to get rid of thisunnecessary second window. The secondwindow is caused by awindows event loop. We can get rid of it by suppressing it.
munotes.in

Page 205

Fig 15 Independent Message window got by adding withdraw()in code2.How to create the title of a tkinter window form:1.6The principle of changing the title of a tkintermain root window is thesame as what discussed in topic presented above.1.7Here we create the main root window and give it a title
Fig 16 GUI title3.Changing the icon of the main root window:1.8Wewill use an icon that ships with python but you can use any iconyou find useful.1.9Place the following code somewher above the main event loop
Fig 17 Icon added to the main root window
munotes.in

Page 206

4.Using a Spin box control:1.10We will use a spinbox widget andwe will also bind the Enter key onthe keyboard to one of our widget.1.11We will use tabbed GUI code and will add further a spinbox widgetabove the scrolledtext control. This simply requires us to incrementthe ScrolledTextrow value by one and to insert our new spinboxcontrol in the row above the entry widget.1.12First, we add the Spinbox control. Place the following code abovethe ScrolledText widget
Fig 18 SpinBox ControlNext, we will reduce the sixe of the spinbox widget, by addingfollowingcode snippetspin=spinbox(mighty, from=0,to=10,width=5)
Fig 19 Spin box control with reduce size
munotes.in

Page 207

Next, we add another property to customize our widget further, bd isshort-hand notation for the borderwidth propertyspin=Spinbox(mighty,from=0, to=0,width-5, bd=8)
Fig 20 Spin box with borderHere, we add functionality to the widget by creating a callback and linkingit to the control
Fig 21 spinbox with small borderwidthInstead of using a range, we can also specify a set ofvalues
munotes.in

Page 208


Fig 22 Spinbox with small border width5.Relief, Sunken and raised appearance of widgets1.10We can control the appearance of our spinbox widgets by using aproperty that makes them appear in different sunken or raisedformats.1.11We will add onemore spinbox control to demonstrate the availableappearance of widgets using the relief property of the spinboxcontrol
Fig 23 Two Sunken Spinbox
munotes.in

Page 209

 3.8Here are the available relief property options that can be settk.SUNKENtk.RAISEDtk.FLATtk.GROOVEtk.RIDGEBy assigning the different available options to the relief property,we can create different appearances for this widget. Assigning thetk.RIDGE relief and reducing the border width to the same value as ourfirst spinbox widget resultsin the following GUI
Fig 24 spinbox with two ridge8.Creating tooltips using python:1.12We will be adding more useful functionality to our GUI.Surprisingly, adding a tooltip to our controls should be simple, butit is not as simple as we wouldwish it to be .1.13In order to achieve this desired functionality, we will place ourtooltip code in to its own OOP class
munotes.in

Page 210

 In an object oriented programming (OOP) approach, we create anew class in ourpython module. Python allows us to place more thanoneclass in to same pyhton module and it also enables us to mix-and-matchclasses and regular functions in the same module.In our tooltip code, we declare a Python class and explicitly makeit inherit from object, which is the foundation of all Pythonclasses. Wecan also leave it out, as we did in the AClass code example, because it isthe default for all Python classes.After all the necessary tooltip creation code that occirs within theTooltip class, we switch over to non-OOP python programming bycreating a function just below itWe can add a tooltip for our Spinbox widget, as follows#Add a TooltipCreate_ToolTip(spin, ‘This is a spin control’)We could do the same for all of our other GUI widgets in the verysame manner. We just have to pass in a reference to the widget we wish tohave a tooltip, displaying some extra information. For our ScrolledTextwidget, we made the scrol variable point toit, so this is what we pass intothe constructor of our tooltip creation function:
munotes.in

Page 211

Fig 25 ToolTip Output9.Adding a Progressbar to the GUI7.1Progressbar is typically used to show the current status of a long-running process.7.2Add four buttonsin to Label frame and set the label frame textproperty to progressbar.7.3We connect each of our four new buttons to a new callback function,which we assign to their command property
munotes.in

Page 212

Fig 26 Progress Bar10.How to use the Canvas Widget:1.11.1First,we will create a third tab in our GUI in order to isolate ournew code1.12Here is the code to create the new third tab
Next, we use another built-in widget of tkinter:canvas. A lot ofpeople like this widget as it has powerful capabilities
munotes.in

Page 213

Fig 27Canvas output14.5 SUMMARY•In this chapter we discuss how to add messagebox, tooltip, progressbar, grid layout and other layout management and customized GUIfeatures.•Codes for every widget is covered with output.14.6QUESTIONSQ1Design acalculator with proper grid layoutQ2Change the title of main screen. Write a small code for thatQ3Discuss how to change the border width of the spin boxQ4Difference between spinbox and combo boxQ5Create a Menu driven program for addition, substraction,multiplication and division using Menu bar14.7REFERENCES1.Python GUI programming Cookbook-Burkahard A Meier, PacktPublication, 2ndEdition.
munotes.in

Page 214

15STORING DATA IN OUR MYSQLDATABASE VIA OUR GUIUnit Structure15.0Objectives15.1Introduction15.2Connecting to a MySQL database from Python15.3Configuring the MySQL connection, Designing the Python GUIdatabase15.4Using the INSERTcommand15.5Using the UPDATE command15.6Using the DELETE command15.7Storing and retrieving data from MySQL database.15.8Summary15.9Questions15.10References15.0 OBJECTIVESAt the end of this unit, the learner will be able to●Demonstrate the steps forconnecting python code to MySQL.●Implement the Insert command●Implement the Update command●Implement the Delete command15.1 INTRODUCTION1.Before we can connect to a MySQL server, we have to have access toa MySQL server. The first thing in thischapter will show you how toinstall the free MySQL Server Community Edition.2.After successfully connecting to a running instance of our MySQLserver, we will design and create a database that will accept a booktitle, which could be our own journal ora quote we found somewhereon the Internet. We will require a page number for the book, whichcould be blank, and then we will insert the quote we like from abook, journal, website or friend into our MySQL databaseusing ourGUI built in Python3.Wewill insert, modify, delete and display our favorite quotes usingour Python GUI to issue these SQL commands and to display the data.munotes.in

Page 215

4.CRUD is a database term you might come across that abbreviates thefour basic SQL commands and stands for Create , Read, Update, andDelete.15.2 CONNECTING TO A MYSQL DATABASE FROMPYTHON1.Before we can connect to a MySQL database, we have to connect tothe MySQL server.2.In order to do this, we need to know the IP address of the MySQLserver as well as the portit is listening on.3.We also have to be a registered user with a password in order to getauthenticated by the MySQL server.4.You will need to have access to a running MySQL server instance andyou also need to have administrator privileges in order to createdatabases and tables.5.There is a free MySQL Community Edition available from the officialMySQL website. You can download and install it on your local PCfrom h:ttp://dev.mysql.com/downloads/.6.In order to connect to MySQL, we first need toinstall a special Pythonconnector driver. This driver will enable us to talk to the MySQLserver from Python.7.The driver is freely available on the MySQL website and comes with avery nice online tutorial. You can install it from: http://dev.mysql.com/doc/connector-python/en/index.html9.There is currently a little bit of a surprise at the end of the installationprocess. When we start the .msi installer we briefly see aMessageBoxshowing the progress of the installation, but then it disappears. We getno confirmation that the installation actually succeeded.10.One way to verify that we installed the correct driver, that lets Pythontalk to MySQL, is by looking into thePython site-packages directory.11.If your site-packages directory looks similar to the followingscreenshot and you see some new files thathavemysql_connector_python in their name, well, then we did indeedinstall something…
!&""#/.*"+$%+"&%&-&$*."+!+,+&)"#++!&##&."%  !++'-$/*(#&$&&%%+&)'/+!&%%&%%+&)'/+!&%tutorials.html
"$'&)+$/*(#&%%+&)*$/*(#&%%$/*(#&%%+,*)$"%*)'**.&)$"%.!&*+
  
')"%+&%%&%%#&*munotes.in

Page 216


If running the preceding code results in the following output printed tothe console, then we are good.14.If you are not able to connect to the MySQL server, then somethingprobably went wrong during the installation. If this is the case, tryuninstalling MySQL, reboot your PC, and then run the MySQLinstallation again. Double-check that you downloaded the MySQLinstaller to match your version of Python. If you have more than oneversion of Python installed, that sometimes leads to confusion as theone you installed last gets prepended to the Windows pathenvironmental variable and some installers just use the first Pythonversion they can find in this location.15.In order to connect our GUI to a MySQL server, we need to be able toconnect to the server with administrative privileges if we want tocreate our own database.16.If the database already exists, then we just need the authorizationrights to connect, insert, update, and delete data.
Fig.1 Place of MySQL in drive folder
Fig.2 After Installation of MysQLmunotes.in

Page 217

15.3 CONFIGURING THE MYSQL CONNECTION,DESIGNING THE PYTHON GUI DATABASE1.Weused the shortest way to connect to a MySQL server by hard-coding the credentials required for authentication into the connectionmethod. While this is afast approach for early development, wedefinitely do not want to expose our MySQL server credentialstoanybody unless wegrantpermission to databases, tables, views, andrelated database commands to specific users.2.A much safer way to get authenticated by a MySQL server is bystoring the credentials in a configuration file, which is what we will doin this recipe.3.We will use our configuration file to connect to the MySQL server andthen create our own database on the MySQL server.4.First, we create a dictionary in the same module of thMe ySQL.pycode.a.# create dictionary tohold connection infodbConfig = {b.'user': ,# use your adminname 'password': , # useyour admin password 'host': '127.0.0.1',#IP address oflocalhostc.}5.Next, in the connection method, we unpack the dictionary values.Instead of writing,a.mysql.connect('user': , 'password':, 'host': '127.0.0.1')6.we use(**dbConfig) , which does the same as above but is muchshorter.a.importmysql.connectoras mysql #unpackdictionarycredentialsconn= mysql.connect(*munotes.in

Page 218


*dbConfig)print(conn)7.This results in the same successful connection to the MySQL server,but the difference is that the connection method no longer exposes anymission-critical information.8.Now, placing the sameusername, password, database, and so on into adictionary in thesame Python module does not eliminate the risk ofhaving thecredentials seen by any one per using the code.9.In order to increase database security, we first move the dictionary intoitsown Python module. Let's call the new Python modulGeuiDBConfig.py .10.We then import this module and unpack the credentials, as we didbefore.11.import GuiDBConfigas guiConf # unpackdictionary credentialsconn=mysql.connect(**guiConf.dbConfig)print(conn)12.Now that we know how to connect to MySQL and have administratorprivileges, we can create our own database by issuing the followingcommands:13.GUIDB ='GuiDB'# unpack dictionary credentialsconn =mysql.connect(**guiConf.dbConfig) cursor = conn.cursor()try:cursor.execute("CREATE DATABASE {} DEFAULT CHARACTERSET 'utf8'".format(GUIDB))except mysql.Error as err:print("Failed to create DB:{}".format(err))conn.close()14.In order to execute commands to MySQL, we create a cursor objectfrom the connection object.A cursor is usually a place in a specific row in a database table, whichmunotes.in

Page 219

 we move up or down the table, but here we use it tocreate the databaseitself.15.We wrap the Python code into tary…except block and use the built-inerror codes of MySQL to tell us if anything went wrong.16.We can verify that this block works by executing the database-creatingcode twice. The firsttime, it will create a new database in MySQL,and the second time it will print out an error message stating that thisdatabase already exists.17.We can verify which databases exist by executing the followingMySQL command using the very same cursorobject syntax.18.Instead of issuing the CREATE DATABASE command, we create acursor and use it to execute the SHOW DATABASE command, theresult of which we fetch and print to the console output.19..import mysql.connectoras mysql importGuiDBConfig asguiConf# unpack dictionary credentialsconn = mysql.connect(**guiConf.dbConfig)cursor = conn.cursor()cursor.execute("SHOWDATABASES")print(cursor.fetchall())conn.close()20.Running this code shows us which databases currentlyexist in ourMySQL server instance. As we can see from the output, MySQL shipswith several built-in databases, such as information_schema , and soon. We have successfully created our owuidb database, which isshown in the output. All other databases illustrated come shipped withMySQL.15.4 USING THE INSERT COMMAND1. Creating New databases1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google")4.#creatingthecursorobjectmunotes.in

Page 220

 5.cur=myconn.cursor()6.try:7.dbs=cur.execute("showdatabases")8.except:9.myconn.rollback()10.forxincur:11.print(x)12.myconn.close()Output
Fig 3 Already Existing Output2.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#creatinganewdatabase8.cur.execute("createdatabasePythonDB2")9.#gettingthelistofallthedatabaseswhichwillnowincludethenewdatabasePythonDB10.dbs=cur.execute("showdatabases")11.except:12.myconn.rollback()
munotes.in

Page 221

13.forxincur:14.print(x)15.myconn.close()output:
Fig 4 Created new database3 Creating the table:We will create the new table Employee. We have to mention thedatabase name while establishing the connection object.We can create the new table by using the CREATE TABLEstatement of SQL. In our database PythonDB, the table Employee willhave the four columns, i.e., name, id, salary, and department_id initially.1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#CreatingatablewithnameEmployeehavingfourcolumnsi.e.,name,id,salary,anddepartmentid8.dbs=cur.execute("createtableEmployee(namevarchar(20)notnull,idint(20)notnullprimarykey,salaryfloatnotnull,Dept_idintnotnull)")
munotes.in

Page 222

9.except:10.myconn.rollback()11.myconn.close()
Fig 5 Output of create Table3.Insert Operation:1.TheINSERT INTOstatement is used to add a record to the table. Inpython, we can mention the format specifier (%s) in place of values.2.We provide the actual values in the form of tuple in the execute()method of the cursor3.Consider the Following example1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"7.#Therowvaluesareprovidedintheformoftuple
9.except:10.myconn.rollback()11.myconn.close()
Fig 5 Output of create Table3.Insert Operation:1.TheINSERT INTOstatement is used to add a record to the table. Inpython, we can mention the format specifier (%s) in place of values.2.We provide the actual values in the form of tuple in the execute()method of the cursor3.Consider the Following example1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"7.#Therowvaluesareprovidedintheformoftuple
9.except:10.myconn.rollback()11.myconn.close()
Fig 5 Output of create Table3.Insert Operation:1.TheINSERT INTOstatement is used to add a record to the table. Inpython, we can mention the format specifier (%s) in place of values.2.We provide the actual values in the form of tuple in the execute()method of the cursor3.Consider the Following example1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"7.#Therowvaluesareprovidedintheformoftuple
munotes.in

Page 223

8.val=("John",110,25000.00,201,"Newyork")9.try:10.#insertingthevaluesintothetable11.cur.execute(sql,val)12.#committhetransaction13.myconn.commit()14.except:15.myconn.rollback()16.print(cur.rowcount,"recordinserted!")17.myconn.close()
Fig 6 Insert Operation Output3.1 Insert Multiple rows1.We can also insert multiple rows at onceusing the python script. Themultiple rows are mentioned as the list of various tuples.2.Each element of the list is treated as one particular row, whereas eachelement of the tuple is treated as one particular column value(attribute).• importmysql.connector
8.val=("John",110,25000.00,201,"Newyork")9.try:10.#insertingthevaluesintothetable11.cur.execute(sql,val)12.#committhetransaction13.myconn.commit()14.except:15.myconn.rollback()16.print(cur.rowcount,"recordinserted!")17.myconn.close()
Fig 6 Insert Operation Output3.1 Insert Multiple rows1.We can also insert multiple rows at onceusing the python script. Themultiple rows are mentioned as the list of various tuples.2.Each element of the list is treated as one particular row, whereas eachelement of the tuple is treated as one particular column value(attribute).• importmysql.connector
8.val=("John",110,25000.00,201,"Newyork")9.try:10.#insertingthevaluesintothetable11.cur.execute(sql,val)12.#committhetransaction13.myconn.commit()14.except:15.myconn.rollback()16.print(cur.rowcount,"recordinserted!")17.myconn.close()
Fig 6 Insert Operation Output3.1 Insert Multiple rows1.We can also insert multiple rows at onceusing the python script. Themultiple rows are mentioned as the list of various tuples.2.Each element of the list is treated as one particular row, whereas eachelement of the tuple is treated as one particular column value(attribute).• importmysql.connector
munotes.in

Page 224

#Createtheconnectionobjectmyconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")#creatingthecursorobjectcur=myconn.cursor()sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"val=[("John",102,25000.00,201,"Newyork"),("David",103,25000.00,202,"Portofspain"),("Nick",104,90000.00,201,"Newyork")]try:#insertingthevaluesintothetablecur.executemany(sql,val)#committhetransactionmyconn.commit()print(cur.rowcount,"recordsinserted!")except:myconn.rollback()myconn.close()
Fig 7 Multiple Insertion Output
#Createtheconnectionobjectmyconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")#creatingthecursorobjectcur=myconn.cursor()sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"val=[("John",102,25000.00,201,"Newyork"),("David",103,25000.00,202,"Portofspain"),("Nick",104,90000.00,201,"Newyork")]try:#insertingthevaluesintothetablecur.executemany(sql,val)#committhetransactionmyconn.commit()print(cur.rowcount,"recordsinserted!")except:myconn.rollback()myconn.close()
Fig 7 Multiple Insertion Output
#Createtheconnectionobjectmyconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")#creatingthecursorobjectcur=myconn.cursor()sql="insertintoEmployee(name,id,salary,dept_id,branch_name)values(%s,%s,%s,%s,%s)"val=[("John",102,25000.00,201,"Newyork"),("David",103,25000.00,202,"Portofspain"),("Nick",104,90000.00,201,"Newyork")]try:#insertingthevaluesintothetablecur.executemany(sql,val)#committhetransactionmyconn.commit()print(cur.rowcount,"recordsinserted!")except:myconn.rollback()myconn.close()
Fig 7 Multiple Insertion Output
munotes.in

Page 225

15.5 USING THEUPDATE COMMANDThe UPDATE-SET statement is used to update any column inside thetable. The following SQL query is used to update a column.1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#updatingthenameoftheemployeewhoseidis1108.cur.execute("updateEmployeesetname='alex'whereid=110")9.myconn.commit()10.except:11.myconn.rollback()12.myconn.close()
Fig 8 Update command output
15.5 USING THEUPDATE COMMANDThe UPDATE-SET statement is used to update any column inside thetable. The following SQL query is used to update a column.1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#updatingthenameoftheemployeewhoseidis1108.cur.execute("updateEmployeesetname='alex'whereid=110")9.myconn.commit()10.except:11.myconn.rollback()12.myconn.close()
Fig 8 Update command output
15.5 USING THEUPDATE COMMANDThe UPDATE-SET statement is used to update any column inside thetable. The following SQL query is used to update a column.1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#updatingthenameoftheemployeewhoseidis1108.cur.execute("updateEmployeesetname='alex'whereid=110")9.myconn.commit()10.except:11.myconn.rollback()12.myconn.close()
Fig 8 Update command output
munotes.in

Page 226

15.6 USING THE DELETE COMMANDThe DELETE FROM statement is used to delete a specific recordfrom the table. Here, we must impose a condition using WHERE clauseotherwise all the records from the table will be removed.The following SQL query is used to delete the employee detail whose id is110 from the table.importmysql.connector#Createtheconnectionobjectmyconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")#creatingthecursorobjectcur=myconn.cursor()try:#Deletingtheemployeedetailswhoseidis110cur.execute("deletefromEmployeewhereid=110")myconn.commit()except:myconn.rollback()myconn.close()15.7 STORINGAND RETRIEVING DATA FROMMYSQL DATABASE.The SELECT statement is used to read the values from the databases.We can restrict the output of a select query by using various clause inSQL like where, limit, etc.2.Python provides the fetchall() methodreturns the data stored inside thetable in the form of rows. We can iterate the result to get the individualrows.importmysql.connector#Createtheconnectionobjectmyconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")#creatingthecursorobjectcur=myconn.cursor()try:#ReadingtheEmployeedatacur.execute("select*fromEmployee")munotes.in

Page 227

#fetchingtherowsfromthecursorobjectresult=cur.fetchall()#printingtheresultforxinresult:print(x);except:myconn.rollback()myconn.close()2 Reading specific column1We can read the specific columns by mentioningtheir names insteadof using star (*)1.importmysql.connector2.#Createtheconnectionobject3.myconn=mysql.connector.connect(host="localhost",user="root",passwd="google",database="PythonDB")4.#creatingthecursorobject5.cur=myconn.cursor()6.try:7.#ReadingtheEmployeedata8.cur.execute("selectname,id,salaryfromEmployee")9.#fetchingtherowsfromthecursorobject10.result=cur.fetchall()11.#printingtheresult12.forxinresult:13.print(x);14.except:15.myconn.rollback()16.myconn.close()
Fig 9 Select operation Output
munotes.in

Page 228


15.8 SUMMARY●In this chapter, CRUD (Create,Read, Update, Delete) operation isdisccused along with example.●Also chapter discusses the installationsteps and configuring steps ofMYSQL in python15.9QUESTIONS1.Create a Library data base, perform CRUD Operations?2.Discuss the steps of installation of Mysql in python3.Why there is need to configure the Python Mysql Data base?15.10REFERENCES1.Python GUI programming Cookbook-Burkahard A Meier, PacktPublication, 2ndEdition.munotes.in