id
int64
0
25.6k
text
stringlengths
0
4.59k
11,200
pulling together the code fragments from the previous sectionthe whole program looks like thisdef print_lyrics ()print (" ' lumberjackand ' okay "print (" sleep all night and work all day "def repeat_lyrics ()print_lyrics (print_lyrics (repeat_lyrics (this program contains two function definitionsprint_lyrics and repeat_lyrics function definitions get executed just like other statementsbut the effect is to create function objects the statements inside the function do not get executed until the function is calledand the function definition generates no output flow of executionin order to ensure that function is defined before its first useyou have to know the order in which statements are executedwhich is called the flow of execution execution always begins at the first statement of the program statements are executed one at timein order from top to bottom function definitions do not alter the flow of execution of the programbut remember that statements inside the function are not executed until the function is called function call is like detour in the flow of execution instead of going to the next statementthe flow jumps to the body of the functionexecutes all the statements thereand then comes back to pick up where it left off when you read programyou don' always want to read from top to bottom sometimes it makes more sense if you follow the flow of execution parameters and argumentssome of the built-in functions we have seen require arguments for examplewhen you call math sin you pass number as an argument some functions take more than one argumentmath pow takes twothe base and the exponent
11,201
inside the functionthe arguments are assigned to variables called parameters here is an example of user-defined function that takes an argument def print_twice(bruce)print(bruceprint(brucethis function assigns the argument to parameter named bruce when the function is calledit prints the value of the parameter twice print_twice('spam'spam spam print_twice ( print_twice(math pi the same rules of composition that apply to built-in functions also apply to user-defined functionsso we can use any kind of expression as an argument for print_twice print_twice ('spam '* spam spamspamspam spam spamspamspam print_twice(math cos(math pi)- - the argument is evaluated before the function is calledso in the examples the expressions 'spam '* and math cos(math piare only evaluated once variables and parameters are localwhen you create variable inside functionit is localwhich means that it only exists inside the function for example def cat_twice(part part )cat part part print_twice(cat
11,202
result twice here is an example that uses itline 'bing tiddle line 'tiddle bang cat_twice(line line bing tiddle tiddle bang bing tiddle tiddle bang when cat_twice terminatesthe variable cat is destroyed if we try to print itwe get an exceptionprint cat nameerrorname 'catis not defined parameters are also local for exampleoutside print_twicethere is no such thing as bruce stack diagramsto keep track of which variables can be used whereit is sometimes useful to draw stack diagram like state diagramsstack diagrams show the value of each variablebut they also show the function each variable belongs to each function is represented by frame frame is box with the name of function beside it and the parameters and variables of the function inside it the stack diagram for the previous example is shown in figure fig stack diagram the frames are arranged in stack that indicates which function called whichand so on in this exampleprint_twice was called by cat_twiceand cat_twice was called by __main__which is special name for the topmost frame when you create variable outside of any functionit belongs to __main__
11,203
each parameter refers to the same value as its corresponding argument sopart has the same value as line part has the same value as line and bruce has the same value as cat if an error occurs during function callpython prints the name of the functionand the name of the function that called itand the name of the function that called thatall the way back to __main__ fruitful functions and void functions some of the functions we are usingsuch as the math functionsyield resultsfor lack of better namei call them fruitful functions other functionslike print_twiceperform an action but don' return value they are called void functions when you call fruitful functionyou almost always want to do something with the resultfor exampleyou might assign it to variable or use it as part of an expressionx math cos(radiansgolden (math sqrt( when you call function in interactive modepython displays the resultmath sqrt( but in scriptif you call fruitful function all by itselfthe return value is lost forever math sqrt( this script computes the square root of but since it doesn' store or display the resultit is not very useful void functions might display something on the screen or have some other effectbut they don' have return value if you try to assign the result to variableyou get special value called none result print_twice('bing'bing bing print(resultnone the value none is not the same as the string 'noneit is special value that has its own typeprint type(nonethe functions we have written so far are all void
11,204
it may not be clear why it is worth the trouble to divide program into functions there are several reasonscreating new function gives you an opportunity to name group of statementswhich makes your program easier to read and debug functions can make program smaller by eliminating repetitive code laterif you make changeyou only have to make it in one place dividing long program into functions allows you to debug the parts one at time and then assemble them into working whole well-designed functions are often useful for many programs once you write and debug oneyou can reuse it importing with fromreturn valuesincremental development importing with frompython provides two ways to import moduleswe have already seen oneimport math print math print math pi if you import mathyou get module object named math the module object contains constants like pi and functions like sin and exp but if you try to access pi directlyyou get an error print pi traceback (most recent call last)file ""line in nameerrorname 'piis not defined as an alternativeyou can import an object from module like thisfrom math import pi now you can access pi directlywithout dot notation print pi or you can use the star operator to import everything from the modulefrom math import
11,205
- the advantage of importing everything from the math module is that your code can be more concise the disadvantage is that there might be conflicts between names defined in different modulesor between name from module and one of your variables boolean functions syntax for boolean function is as follows bool([value]as we seen in the syntax that the bool(function can take single parameter (value that needs to be convertedit converts the given value to true or false if we don' pass any value to bool(functionit returns false bool(function returns boolean value and this function returns false for all the following values none false zero number of any type such as intfloat and complex for example empty list []empty tuple ()empty string empty dictionary { objects of classes that implements __bool__(or __len()__ methodwhich returns or false bool(function returns true for all other values except the values that are mentioned above examplebool(function in the following examplewe will check the output of bool(function for the given values we have different values of different data types and we are printing the return value of bool(function in the output empty list lis [print(lis,'is',bool(lis)empty tuple (print( ,'is',bool( )zero complex number
11,206
print( ,'is',bool( )num print(num'is'bool(num)val none print(val,'is',bool(val)val true print(val,'is',bool(val)empty string str 'print(str,'is',bool(str)str 'helloprint(str,'is',bool(str)output[is false (is false is false is true none is false true is true is false hello is true more recursionchecking typeswhat is recursionrecursion is the process of defining something in terms of itself physical world example would be to place two parallel mirrors facing each other any object in between them would be reflected recursively in pythonwe know that function can call other functions it is even possible for the function to call itself these types of construct are termed as recursive functions
11,207
following is an example of recursive function to find the factorial of an integer factorial of number is the product of all the integers from to that number for examplethe factorial of (denoted as !is * * * * * example of recursive function def factorial( )"""this is recursive function to find the factorial of an integer""if = return elsereturn ( factorial( - )num print("the factorial of"num"is"factorial(num)outputthe factorial of is in the above examplefactorial (is recursive function as it calls itself when we call this function with positive integerit will recursively call itself by decreasing the number each function multiplies the number with the factorial of the number below it until it is equal to one this recursive call can be explained in the following steps factorial ( st call with factorial ( nd call with
11,208
* * return from rd call as number= * return from nd call return from st call summary in this we studied function calltype conversion functions in python programming language in this we are more focused on math function and adding new function in python elaborating on definitions and uses of functionparameters and arguments in python also studied fruitful functions and void functionsimporting with fromboolean functions and recursion in python unit end exercise python provides built-in function called len that returns the length of stringso the value of len('allen'is write function named right_justify that takes string named as parameter and prints the string with enough leading spaces so that the last letter of the string is in column of the display right_justify('allen'allen write python function to sum all the numbers in list go to the editor sample list ( expected output write python program to reverse string sample string " abcdexpected output "dcba write python function to calculate the factorial of number ( non-negative integerthe function accepts the number as an argument write python program to print the even numbers from given list sample list[ expected result[
11,209
www journaldev com www edureka com www tutorialdeep com www xspdf com think python by allen downey st edition ****
11,210
strings unit structure string is sequence traversal with for loop string slices strings are immutable searching looping and counting string methods the in operator string comparison string operations summary questions references objectives 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 to learn the string traversal with for loop in python string is sequence there are numerous types of sequences in python strings are special type of sequence that can only store charactersand they have special notation strings are sequences of characters and are immutable string is sequence of characters we can access the characters one at time with the bracket operatorfood 'rotiletter food[ the second statement retrieves the character at index position one from the food variable and assigns it to the letter variable the expression
11,211
sequence you required example ' want to read bookthis is stringit has been surrounded in single quotes declaring python string string literals in python string literals are surrounded by single quotes or double-quotes ' want to read book" want to read book'you can also surround them with triple quotes (groups of single quotes or double quotes""" want to read book'""" want to read book'"or using backslashes >'thankgood morning sir !'thanksgood morning sir!you cannot start string with single quote and end it with double quote but if you surround string with single quotes and also want to use single quotes as part of the stringyou have to escape it with backslash (\'send message to madam\' son this statement causes syntaxerror'send message to madam' sonyou can also do this with double-quotes if you want to ignore escape sequencesyou can create raw string by using an 'ror 'rprefix with the string common escape sequences\backslash \ linefeed \ horizontal tab \single quotes \double quotes we can assign string to variable
11,212
you can also create string with the str(function str( output' str('shri'output'shri traversal and the for loopby item lot of computations involve processing collection one item at time for strings this means that we would like to process one character at time often we start at the beginningselect each character in turndo something to itand continue until the end this pattern of processing is called traversal we have previously seen that the for statement can iterate over the items of sequence ( list of names in the case belowfor aname in ["joe""amy""brad""angelina""zuki""thandi""paris"]invitation "hi aname please come to my party on saturday!print(invitationrecall that the loop variable takes on each value in the sequence of names the body is performed once for each name the same was true for the sequence of integers created by the range function for avalue in range( )print(avaluesince string is simply sequence of charactersthe for loop iterates over each character automatically for achar in "go spot go"print(achar
11,213
in the string "go spot gowe will refer to this type of sequence iteration as iteration by item note that it is only possible to process the characters one at time from left to right check your understanding strings- - how many times is the word hello printed by the following statementss "python rocksfor ch in sprint("hello"ans yesthere are charactersincluding the blank strings- - how many times is the word hello printed by the following statementss "python rocksfor ch in [ : ]print("hello"ans yesthe blank is part of the sequence returned by slice string slices python slice string syntax isstr_object[start_pos:end_pos:stepthe slicing starts with the start_pos index (includedand ends at end_pos index (excludedthe step parameter is used to specify the steps to take from start to end index python string slicing always follows this rules[:is[ := for any index 'iall these parameters are optional start_pos default value is the end_pos default value is the length of string and step default value is let' look at some simple examples of string slice function to create substring 'helloworldprint( [:]print( [::]
11,214
helloworld helloworld note that since none of the slicing parameters were providedthe substring is equal to the original string let' look at some more examples of slicing string 'helloworldfirst_five_chars [: print(first_five_charsthird_to_fifth_chars [ : print(third_to_fifth_charsoutputhello llo note that index value starts from so start_pos refers to the third character in the string reverse string using slicing we can reverse string using slicing by providing the step value as - 'helloworldreverse_str [::- print(reverse_stroutputdlrowolleh let' look at some other examples of using steps and negative index values [ : : print( outputloo here the substring contains characters from indexes , and [ : :- print(
11,215
lrowoll strings are immutable the standard wisdom is that python strings are immutable you can' change string' valueonly the reference to the string like sox "hellox "goodbyenew stringwhich implies that each time you make change to string variableyou are actually producing brand new string because of thistutorials out there warn you to avoid string concatenation inside loop and advise using join instead for performance reasons even the official documentation says sothis is wrong sort of there is common case for when strings in python are actually mutable will show you an example by inspecting the string object' unique id using the builtin id(functionwhich is just the memory address the number is different for each object (objects can be shared thoughsuch as with interning an unchanging article alludes to the item which is once made can' change its worth all its lifetime attempt to execute the accompanying codename_ "aarunname_ [ 'tyou will get mistake message when you need to change the substance of the string traceback (latest call last)record "/home/ca dc fa ad ca py"line in name_ [ 'ttypeerror'strobject doesn' uphold thing task arrangement one potential arrangement is to make another string object with vital alterationsname_ "aarunname_ "tname_ [ :print("name_ "name_ "and name_ "name_
11,216
to watch that they are various stringscheck with the id(workname_ "aarunname_ "tname_ [ :print("id of name_ "id(name_ )print("id of name_ "id(name_ )outputid of name_ id of name_ to see more about the idea of string permanencethink about the accompanying codename_ "aarunname_ "aarunprint("id of name_ "id(name_ )print("id of name_ "id(name_ )outputid of name_ id of name_ with new value searching searching is very basic necessity when you store data in different data structures the simplest approach is to go across every element in the data structure and match it with the value you are searching for this is known as linear search it is inefficient and rarely usedbut creating program for it gives an idea about how we can implement some advanced search algorithms linear searchin this type of searcha sequential search is made over all items one by one every item is checked and if match is found then that particular item is returnedotherwise the search continues till the end of the data structure example def linear_search(valuessearch_for)search_at search_res false
11,217
while search_at len(valuesand search_res is falseif values[search_at=search_forsearch_res true elsesearch_at search_at return search_res [ print(linear_search( )print(linear_search( )outputwhen the above code is executedit produces the following result true false interpolation searchthis search algorithm works on the probing position of the required value for this algorithm to work properlythe data collection should be in sorted form and equally distributed initiallythe probe position is the position of the middle most item of the collection if match occursthen the index of the item is returned if the middle item is greater than the itemthen the probe position is again calculated in the sub-array to the right of the middle item otherwisethe item is searched in the subarray to the left of the middle item this process continues on the sub-array as well until the size of subarray reduces to zero example there is specific formula to calculate the middle position which is indicated in the program below def intpolsearch(values, )idx idxn (len(values while idx values[idx and <values[idxn]find the mid point mid idx +int(((float(idxn idx )/values[idxnvalues[idx ]) values[idx ]))compare the value at mid point with search value if values[mid=
11,218
if values[midxidx mid return "searched element not in the listl [ print(intpolsearch( )outputfound at index looping and counting the following program counts the number of times the letter "rappears in stringword 'raspberrycount for letter in wordif letter =' 'count count print(countthis program demonstrates another pattern of computation called counter the variable count is initialized to and then incremented each time an "ris found when the loop exitscount contains the resultthe total number of ' "peanut buttercount for char in sif char =" "count count print(countoutputthe letter appears times in "peanut butter string methods python has set of built-in methods that you can use on strings noteall string methods returns new values they do not change the original string
11,219
capitalize(casefold(center(count(description converts the first character to upper case converts string into lower case returns centered string returns the number of times specified value occurs in string encode(returns an encoded version of the string endswith(returns true if the string ends with the specified value expandtabs(sets the tab size of the string find(searches the string for specified value and returns the position of where it was found format(formats specified values in string format_map(formats specified values in string index(searches the string for specified value and returns the position of where it was found isalpha(returns true if all characters in the string are in the alphabet isdecimal(returns true if all characters in the string are decimals isdigit(returns true if all characters in the string are digits isidentifier(returns true if the string is an identifier islower(returns true if all characters in the string are lower case isnumeric(returns true if all characters in the string are numeric isprintable(returns true if all characters in the string are printable isupper(returns true if all characters in the string are upper case join(joins the elements of an iterable to the end of the string ljust(returns left justified version of the string lower(converts string into lower case lstrip(returns left trim version of the string maketrans(returns translation table to be used in translations partition(returns tuple where the string is parted into three parts replace(returns string where specified value is replaced with specified value rfind(searches the string for specified value and returns the last position of where it was found rindex(searches the string for specified value and returns the last position of where it was found rjust(returns right justified version of the string rsplit(splits the string at the specified separatorand returns list rstrip(returns right trim version of the string split(splits the string at the specified separatorand returns list splitlines(splits the string at line breaks and returns list startswith(returns true if the string starts with the specified value strip(returns trimmed version of the string
11,220
swaps caseslower case becomes upper case and vice versa noteall string methods returns new values they do not change the original string the in operator not let us take an example to get better understanding of the in operator working in here "xis the element and "yis the sequence where membership is being checked let' implement simple python code to demonstrate the use of the in operator and how the outputs would look like vowels [' '' '' '' '' 'ch input('please enter capital letter:\ 'if ch in vowelsprint('you entered vowel character'elseprint('you entered consonants character'we can use the "inoperator with strings and tuples too because they are sequences name='journaldev'din name true 'xin name false primes=( , , , , in primes true in primes false can we use python "inoperator with dictionarylet' see what happens when we use "inoperator with dictionary dict {"name""pankaj""id" print("namein dict true
11,221
it looks like the python "inoperator looks for the element in the dictionary keys string comparison the following are the ways to compare two string in python by using =(equal tooperator by using !(not equal tooperator by using sorted(method by using is operator by using comparison operators comparing two strings using =(equal tooperator str input("enter the first string"str input("enter the second string"if str =str print ("first and second strings are equal and same"elseprint ("first and second strings are not same"outputenter the first stringaa enter the second stringaa first and second strings are equal and same comparing two strings using !(not equal tooperator str input("enter the first string"str input("enter the second string"if str !str print ("first and second strings are not equal "elseprint ("first and second strings are the same "outputenter the first stringab enter the second stringba first and second strings are not equal
11,222
if we wish to compare two strings and check for their equality even if the order of characters/words is differentthen we first need to use sorted(method and then compare two strings str input("enter the first string"str input("enter the second string"if sorted(str =sorted(str )print ("first and second strings are equal "elseprint ("first and second strings are not the same "outputenter the first stringengineering discipline enter the second stringdiscipline engineering first and second strings are equal comparing two strings using 'isoperator python is operator returns true if two variables refer to the same object instance str "deedstr "deedstr 'join([' '' '' '' ']print(str is str print("comparision result "str is str outputtrue comparision result false in the above examplestr is str returns false because object str was created differently comparing two strings using comparison operators input 'engineeringprint(input 'engineering'print(input 'engineering'print(input <'engineering'print(input >'engineering'outputfalse
11,223
true true string operations string is an array of bytes that represent the unicode characters in python python does not support character datatype single character also works as string python supports writing the string within single quote(''and double quote(""example "pythonor 'pythoncode singlequotes ='python in single quotesdoublequotes ="python in double quotesprint(singlequotesprint(doublequotesoutputpython in single quotes python in double quotes single character is simply string with length of the square brackets 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 syntax print('text or result'or print("text or result'indexing in string it returns particular character from the given string syntax getchar [indexmessage "hellopython!if want to fetch the characters of the th index from the given string syntax print(string[index]code print(message[ ]
11,224
summary python string is an array of bytes demonstrating unicode characters since there is no such data type called character data type in pythona single character is string of length one string handling is one of those activities in coding that programmersuse all the time in pythonwe have numerous built-in functions in the standard library to assist you manipulate if the string has length onethen the indices start from for the preliminary character and go to - for the rightmost character negative indices may be used to count from the right end (minus onefor the rightmost character through - for the leftmost character strings are immutableso specific characters could be readbut not set substring of or more successive characters of string may be referred to by specifying starting index and the index one earlier the last character of the substring if the starting and/or ending index is left out python uses and the length of the string correspondingly python assumes indices that would be beyond an end of the string essentially say the end of the string string formatting is the way we form instructions so that python can recognize how to integrate data in the creation of strings how strings are formatted determines the presentation of this data the basis of string formatting is its use of the formatting directives logical operators return true or false values comparison operators (==!=>>=<<=compare two values any value in python equates to boolean true or false false can be equal to nonea zero of numeric type ( )an empty sequence (''()[])or an empty dictionary ({}all other values are reflected true sequencestupleslistsand strings can be added and/or multiplied by numeric type with the addition and multiplication operators (+*)correspondingly strings should be formatted with tuples and dictionaries using the format directives % % %fand % formatting flags should be used with these directives questions find the index of the first occurrence of substring in string how would you check if each word in string begins with capital letter write python program to calculate the length of string write python program to get string from given string where all occurrences of its first char have been changed to '$'except the first char itself
11,225
write python program to change given string to new string where the first and last chars have been exchanged write python program to count the occurrences of each word in given sentence write python program to check all strings are mutually disjoint write program to find the first and the last occurence of the letter 'oand character ',in "goodmorning write program to check if the word 'openis present in the "this is open source software write program to check if the letter 'eis present in the word 'welcome references _immutability htm ****
11,226
list unit structure objectives values and accessing elements lists are mutable traversing list deleting elements from list built-in list operators concatenation repetition in operator built-in list functions and methods summary exercise references objectives to learn how python uses lists to store various data values to study usage of the list index to removeupdate and add items from python list to understand the abstract data types queuestack and list to understand the implementations of basic linear data structures to study the implementation of the abstract data type list as linked list using the node the list is most likely versatile data type available in the python which is can be written as list of comma-separated values between square brackets the important thing about list is that items in the list need not be of the same type creating list is as very simple as putting up different commaseparated by values between square brackets for example list ['jack''nick' ]list [ ]list [" "" "" "" "]
11,227
be slicedconcatenated values and accessing elements to access values in listsuse the square brackets for slicing along with the index or indices to obtain value available at that index for example list =['jack','nick', , ]list =[ , , , , , , ]print"list [ ]"list [ print"list [ : ]"list [ : output list [ ]jack list [ : ][ lists are mutablelists is mutable this means we can change item in list by accessing it directly as part of the assignment pf statement using the indexing operator (square bracketson the left of side an assignmentwe can update one of the list item examplecolor ["red""white""black"print(colorcolor [ "orangecolor [- "greenprint(coloroutput["red""white""black"["orange ""white""green " traversing list the mostly common way to traverse the elements of list with for loop the syntax is the same as for stringscolor ["red""white""blue""green"
11,228
print(colorthis works well if you only need to read the element of list but if you want to do write or update the elementyou need the indices common way to do that is to combine the functions range and lenfor in range(len(number))number [inumber[ output red white blue green deleting elements from list to delete list elementyou can use either the del statementdel removes the item at specific indexif you know exactly which element(syou are deleting or the remove(method if you do not know for example list ['red''green' ,]print(list del list[ print("after deleting element at index :")print(list output ['red''green' ,after deleting element at index ['red''green ,example numbers [ del numbers[ : print(numbersoutput[
11,229
one other method from removing elements from list is to take slice of the listwhich excludes the index or indexes of the item or items you are trying to remove for instanceto remove the first two items of listyou can do list list[ : built-in list operators in this lesson we will learn about built-in list operatorsconcatenation indexing repetition list operation membership testing slicing concatenationconcatenation or joining is process in which multiple sequence lists can be combined together '+is symbol concatenation operator examplelist [ list [ print(list list output[
11,230
this operator replication the list for specified number of times and creates new list '*is symbol of repletion operator examplelist [ list [ print(list list output[ , , ,] membership operatorthis operator used to check or test whether particular element or item is member of any list or not 'inand 'not inare the operators for membership operator examplelist [ list [ print( in list #false print( in list #true print( not in list #true print( not in list #false outputfalse true true false indexingindexing is nothing but there is an index value for each tem present in the sequence or list
11,231
list [ print(list [ ]output slicing operatorthis operator used to slice particular range of list or sequence slice is used to retrieve subset of values syntaxlist [start:stop:stepexamplelist [ print(list [ : ]output[ concatenation in this we will learn different methods to concatenate lists in python python list server the purpose of storing homogenous elements and perform manipulations on the same in generalconcatenation is the process of joining the elements of particular data-structure in an end-to-end manner the following are the ways to concatenate lists in python concatenation (+operatorthe '+operator can be used to concatenate two lists it appends one list at the end of the other list and results in new list as output
11,232
list =[ list =[ result =list +list print(str(result)output[ naive methodin the naive methoda for loop is used to be traverse the second list after thisthe elements from the second list will get appended to the first list the first list of results out to be the concatenation of the first and the second list examplelist [ list [ print("before concatenation:str(list )for in list list append(xprint ("after concatenation:str(list )outputbefore concatenation[ after concatenation[ list comprehensionpython list comprehension is an the alternative method to concatenate two lists in python list comprehension is basically the process of building generating list of elements based on an existing list it uses the for loop to process and traverses list in the element-wise fashion the below inline is for-loop is equivalent to nested for loop
11,233
list [ list [ result [ for in [list list for in iprint ("concatenated list:\ "str(result)outputconcatenated list[ extend(methodpython extend(method can be used to concatenate two lists in python the extend(function does iterate over the password parameter and add the item to the listextending the list in linear fashion syntaxlist extend(iterableexamplelist [ list [ print("list before concatenation:\nstr(list )list extend(list print ("concatenated list ,ist after concatenation:\ "str(list )all the elements of the list get appended to list and thus the list gets updated and results as output outputlist before concatenation[ concatenated list ,ist after concatenation[ '*operatorpython' '*operator can be used for easily concatenate the two lists in python
11,234
the index arguments for exampleconsider list list [ the statement *list would replace by the list with its elements on the index positions soit unpacks the items of the lists examplelist [ list [ res [*list *list print ("concatenated list:\ str(res)outputin the above snippet of codethe statement res [*list *list replaces the list and list with the items in the given order elements of list after elements of list this performs concatenation and results in the below output outputconcatenated list[ itertools chain(methodpython itertools modulesitertools chain(function can also be used to concatenate lists in python the itertools chain(function accepts different iterables such as listsstringtuplesetc as parameters and gives sequence of them as output it results out to be linear sequence the data type of the elements doesn' affect the functioning of the chain(method for examplethe statement itertools chain([ ]['john''bunny']would produce the following output john bunny exampleimport itertools list [
11,235
res list(itertools chain(list list )print ("concatenated list:\ str(res)outputconcatenated list[ repetition nowwe are accustomed to using the '*symbol to represent the multiplicationbut when the operand on the left of side of the '*is tupleit becomes the repetition operator and the repetition of the operator it will makes the multiple copies of tuple and joins them all together tuples can be created using the repetition operatorexamplenumber ( , we use the comma to denote that this is single valued tuple and not an '#'expression output print numbers ( [ is tuple with one element now repetition of the operator it will makes copies of this tuple and joins them all together into single tuple another example using multiple elements in the tuple examplenumbers ( output print numbers ( in operator python' in operator lets you loop through all the members of collection (such as list or tupleand check if there' member in the list that' equal to the given item
11,236
my_list [ print( in my_listprint( in my_listoutputtrue false notenote that in operator against dictionary checks for the presence of key examplemy_dict {'name''tutorialspoint''time'' years''location''india'print('namein my_dictoutputthis will give the output true built-in list functions and methods built-in functionsr no function with description cmp(list list compares elements of both lists len(list gives the total length of the list max(list returns item from the list with max value min(list returns item from the list with min value list(seq converts tuple into list
11,237
sr no methods with description list append(objappends object obj to list list count(objreturns count of how many times obj occurs in list list extend(seqappends the contents of seq to list list index(objreturns the lowest index in list that obj appears list insert(indexobjinserts object obj into list at offset index list pop(obj=list[- ]removes and returns last object or obj from list list remove(objremoves object obj from list list reverse(reverses objects of list in place list sort([func]sorts objects of listuse compare func if given summary python lists are commanding data structuresand list understandings are one of the furthermost convenient and brief ways to create lists in this we have given some examples of how you can use list comprehensions to be more easy-to-read and simplify your code the list is the common multipurpose data type available in python list is an ordered collection of items when it comes to creating listspython list are more compressed and faster than loops and other functions used such asmap()filter()and reduce(every python list can be rewritten in for loopsbut not every complex for loop can be rewritten in python list understanding writing very long list in one line should be avoided so as to keep the code user-friendly so list looks just like dynamic sized arraysdeclared in other languages lists need not be homogeneous always which makes it most powerful tool in python single list may contain datatype' like integersstringsand objects etc list loads all the elements into memory at one timewhen the list is too longit will reside in too much memory resourcesand we usually only need to use few elements list is data-structure that can be used to store multiple data at once the list will be ordered and there will be definite count of it the elements are indexed allowing to sequence and the indexing is done with as the first index each element will have discrete place in the sequence and if the same value arises multiple times in the sequence
11,238
explain list parameters with an example write program in python to delete first and last elements from list write python program to print the numbers of specified list after removing even numbers from it write python program using list looping write python program to check list is empty or not write python program to multiplies all the items in list write python program to remove duplicates from list write python program to append list to the second list write python program to find the second smallest number in list write python program to find common items from two lists references ****
11,239
tuples and dictionaries unit structure objectives tuples accessing values in tuples tuple assignment tuples as return values variable-length argument tuples basic tuples operations concatenation repetition in operator iteration built-in tuple functions creating dictionary accessing values in dictionary updating dictionary deleting elements from dictionary properties of dictionary keys operations in dictionary built-in dictionary functions built-in dictionary methods summary exercise references objectives to understand when to use dictionary to study how dictionary allows us to characterize attributes with keys and values to learn how to read value from dictionary to study how in python to assign key-value pair to dictionary to understand how tuples returns values
11,240
tuple in the python is similar to the list the difference between the two is that we cannot change the element of the tuple once it is assigned to whereas we can change the elements of list the reasons for having immutable types apply to tuplescopy efficiencyrather than copying an immutable objectyou can alias it (bind variable to referenceinterningyou need to store at most of one copy of any immutable value there' no any need to synchronize access to immutable objects in concurrent code creating tuplea tuple is created by the placing all the elements inside parentheses '()'separated by commas the parentheses are the optional and howeverit is good practice to use them tuple can have any number of the items and they may be different types (integerfloatliststringetc exampledifferent types of tuples empty tuple tuple (print(tupletuple having integers tuple ( print(tupletuple with mixed datatypes tuple ( "code" print(tuplenested tuple tuple ("color "[ ]( )print(tuple
11,241
(( ( 'code' ('color'[ ]( ) tuple can also be created without using parentheses this is known as tuple packing tuple "colorprint(tupletuple unpacking is also possible abc tuple print( # print( print(cdog output 'color' color accessing values in tuples there are various ways in which we can access the elements of tuple indexingwe can use the index operator [to access an item in tuplewhere the index starts from soa tuple having elements will have indices from to trying to access an index outside of the tuple index range( , in this examplewill raise an indexerror
11,242
types this will result in typeerror likewisenested tuples are accessed using nested indexingas shown in the example below accessing tuple elements using indexing tuple (' ',' ',' ',' ',' ',' 'print(tuple[ ]'aprint(tuple[ ]'findexerrorlist index out of range print(tuple[ ]index must be an integer typeerrorlist indices must be integersnot float tuple[ nested tuple tuple ("color"[ ]( )nested index print(tuple[ ][ ]'oprint(tuple[ ][ ]# outputa negative indexingpython allows negative indexing for its sequences the index of - refers to the last item- to the second last item and so on examplenegative indexing for accessing tuple elements tuple (' ',' ',' ',' ',' ',' '
11,243
print(tuple[- ]output'aprint(tuple[- ]outputf slicingwe can access the range of items from the tuple by using the slicing operator colonexampleaccessing tuple elements using slicing tuple (' ',' ',' ',' ',' ',' ',' ',' ',' 'elements nd to th output(' '' '' 'print(tuple[ : ]elements beginning to nd output(' '' 'print(tuple[:- ]elements th to end output(' '' 'print(tuple[ :]elements beginning to end output(' '' '' '' '' '' '' '' '' 'print(tuple[:]output(' '' '' '(' '' '
11,244
(' '' '' '' '' '' '' '' '' ' tuple assignment one of the unique syntactic features of the python language is the ability to have tuple on the left side of an assignment statement this allows you to assign more than one variable at time when the left side is sequence in this example we have two-element list (which is sequenceand assign the first and second elements of the sequence to the variables and in single statement exampletuple 'red''bluexy tuple outputx 'redy 'blueit is not magicpython roughly translates the tuple assignment syntax to be the followingm 'red''bluex [ [ outputx 'redy 'blue tuples as return values functions can return tuples as return values now we often want to know some batsman' highest and lowest score or we want to know to
11,245
monthand the dayor if we're doing some ecological modeling we may want to know the number of rabbits and the number of wolves on an island at given time in each casea function (which can only return single value)can create single tuple holding multiple elements for examplewe could write function that returns both the area and the circumference of circle of radius exampledef cirlce_info( )#return (circumferenceareaof circle of radius return (caprint(cirlce_info( )output( variable-length argument tuples functions can take variable number of arguments the parameter name that begins with the gather the argument into the tuple for examplethe print all take any number of the arguments and print themdef printall(*args)print args the gather parameter can have any name you likebut args is conventional here' how the function worksthe complement of gather is scatter if you have the sequence of values and you want to pass it to the function as multiple as argumentsyou can use the operator for exampledivmod take exactly two arguments it doesn' work with the tuplet ( divmod(ttypeerrordivmod expected argumentsgot but if you scatter the tupleit worksdivmod(*
11,246
example -many of the built-in functions are use variable-length argument tuples for examplemax and min it can take any of number argumentsmax( , sum( , , typeerrorsum expected at most argumentsgot , but sum does not basic tuples operations nowwe will learn the operations that we can perform on tuples in python membershipwe can apply the 'inand 'not inoperator on the items this tells us whether they belong to the tuple 'ain tuple("string"outputfalse 'xnot in tuple("string"outputtrue concatenationlike we've previously discussed on several occasionsconcatenation is the act of joining we can join two tuples using the concatenation operator '+( , , )+( , , output( noteother arithmetic operations do not apply on tuple logicalall the logical operators (like >,>=can be applied on tuple ( , , )>( , ,
11,247
false ( , )==(' ',' 'outputfalse identityremember the 'isand 'is notoperators we discussed about in our tutorial on python operatorslet' try that on tuples =( , ( , is outputthat did not make sensedid itso what really happenednowin pythontwo tuples or lists don' have the same identity in other wordsthey are two different tuples or lists as resultit returns false concatenation nowwe will learn different ways to concatenate or join tuples in the python language with code example we will use '+operator and built-in sum(function to concatenate or join tuples in python how to concatenate tuples into single/nested tuples using sum() sum(to concatenate tuples into single tuplein our first examplewe will use the sum(function to concatenate two tuples and result in single tuple let us jump to exampletupleint( , , , , , langtuple (' #',' ++','python','go'#concatenate the tuple tuples_concatenate sum((tupleintlangtuple)()print('concatenate of tuples \ =',tuples_concatenateoutputconcatenate of tuples
11,248
sum(to concatenate tuple into nested tuplenow let us understand how we can sum tuples to make nested tuple in this program we will use two tuples which are nested tuplesplease note the ',at the end of each tuples tupleint and langtuple let us understand exampletupleint( , , , , , )langtuple (' #',' ++','python','go')#concatenate the tuple tuples_concatenate sum((tupleintlangtuple)()print('concatenate of tuples \ =',tuples_concatenateoutputconcatenate of tuples (( )(' #'' ++''python''go')concatenate tuple using '+operator '+operator to concatenate two tuples into single tuplein our first examplewe will use the "+operator to concatenate two tuples and result in single tuple in this example we have two tuple tupleint and langtuple,we are the concatenating these tuples into the single tuple as we can see in output tupleint( , , , , , langtuple (' #',' ++','python','go'#concatenate the tuple tuples_concatenate tupleint+langtuple print('concatenate of tuples \ =',tuples_concatenateoutput '+operator with comma(,to concatenate tuples into nested tuplesthis examplewe have the two tuple tuple int and lang tuple now we are using the comma(,end of the each tuple to the concatenate them
11,249
as we can see in the resulting output comma(,after tuple to concatenate nested tuple tupleint( , , , , , )langtuple (' #',' ++','python','go')#concatenate the tuple into nested tuple tuples_concatenate tupleint+langtuple print('concatenate of tuples \ =',tuples_concatenateoutputconcatenate of tuples (( )(' #'' ++''python''go') repetition nowwe are going to explain how to use python tuple repetition operator with basic syntax and many examples for better understanding python tuple repetition operator (*is used to the repeat tuplenumber of times which is given by the integer value and create new tuple values syntaxn input parameterstuple_variable_name the tuples that we want to be repeated where is the number of times that we want that tuple to be repeated ex , , exampledata=( , , ,' ',' 'tuple after repetition print('new tuple:'data
11,250
new tuple[ ' '' ' ' '' 'in the above exampleusing repetition operator (*)we have repeated 'datatuple variable times by 'data in print statement and created new tuple as [ ' '' ' ' '' ' in operator the python in operator lets you loop through all to the members of the collection and check if there' member in the tuple that' equal to the given item examplemy_tuple ( print( in my_tupleprint( in my_tupleoutputtrue false note that in operator against dictionary checks for the presence of key exampleoutputtrue it can also be used to check the presence of sequence or substring against string examplemy_str "this is sample stringprint("samplein stringoutputtrue it can be uses in the many of other places and how it works in the those scenarios of varies lot this is the how in works in tuples it start
11,251
that the object in the tuple or reaches in the end of the tuple iteration there are many ways to iterate through the tuple object for statement in python has variant which traverses tuple till it is exhausted it is equivalent to for each statement in java its syntax is for var in tuplestmt stmt examplet ( , , , , for var in tprint ( index(var),varoutput built-in tuple functions tuples support the following build-in functionscomparisonif the elements are of the same typepython performs the comparison and returns the result if elements are different typesit checks whether they are numbers if numbersperform comparison if either the element is an numberthen the other element is returned otherwisetypes are sorted alphabetically
11,252
"larger if both are list are same it returns tuple (' '' '' ',' '' 'tuple (' ',' ',' 'tuple (' '' '' '' '' 'cmp(tuple tuple out cmp(tuple tuple out- cmp(tuple tuple out tuple lengthlen(tuple out max of tuplethe function min returns the item from the tuple with the min valuemin(tuple out'amin(tuple out' convert list into tuplethe built-in function tuple converts list into tuplelist [ , , , , tuple(listout( tuple concatenationuse to concatenate two tuplestuple tuple out(' '' '' ',' '' '' '' '' '
11,253
creating dictionaryto create the python dictionarywe need to pass the sequence of the items inside curly braces {}and to separate them using comma (,each item has key and value expressed as an "key:valuepair the values can belong to the any of data type and they can repeatbut the keys are must remain the unique the following examples are demonstrate how to create the python dictionariescreating an empty dictionarydict_sample {creating dictionary with integer keysdict_sample { 'mango' 'pawpaw'creating dictionary with mixed keysdict_sample {'fruit''mango' [ ]we can also create dictionary by explicitly calling the python' dict(methoddict_sample dict({ :'mango' :'pawpaw'} dictionary can also be created from sequence as shown belowdictionaries can also be nestedwhich means that we can create dictionary inside another dictionary for exampledict_sample { {'student 'nicholas''student 'john''student 'mercy'} {'course 'computer science''course 'mathematics''course 'accounting'}to print the dictionary contentswe can use the python' print(function and pass the dictionary name as the argument to the function for exampledict_sample "company""toyota""model""premio""year" print(dict_sampleoutput{'company''toyota''model''premio''year'
11,254
to access the dictionary itemswe need to pass the key inside square brackets [for exampledict_sample "company""toyota""model""premio""year" dict_sample["model"print(xoutputpremio we created dictionary named dict_sample variable named is then created and its value is set to be the value for the key "modelin the dictionary updating dictionary after adding value to dictionary we can then modify the existing dictionary element you use the key of the element to change the corresponding value for exampledict_sample "company""toyota""model""premio""year" dict_sample["year" print(dict_sampleoutput{'year' 'model''premio''company''toyota'in this example you can see that we have updated the value for the key "yearfrom the old value of to new value of
11,255
the removal of an element from dictionary can be done in several wayswhich we'll discuss one-by-one in this sectionthe del keyword can be used to remove the element with the specified key for exampledict_sample "company""toyota""model""premio""year" del dict_sample["year"print(dict_sampleoutput{'company''toyota''model''premio'we called the del keyword followed by the dictionary name inside the square brackets that follow the dictionary namewe passed the key of the element we need to delete from the dictionarywhich in this example was "yearthe entry for "yearin the dictionary was then deleted another type to delete key-value pair is to use the pop(method and pass the key of the entry to be deleted as the argument to the function for exampleoutputdict_sample "company""toyota""model""premio""year" dict_sample pop("year"print(dict_samplewe invoked that pop(method by appending it with the dictionary name andin this example the entry for "yearin the dictionary will be deleted
11,256
dictionarywithout needing to specify the key take look at the following exampledict_sample "company""toyota""model""premio""year" dict_sample popitem(print(dict_sampleoutput{'company''toyota''model''premio'the last entry into the dictionary was "yearit has been removed after calling the popitem(function but what if you want to delete the entire dictionaryit would be difficult and cumbersome to use one of these methods on every single key insteadyou can use the del keyword to delete the entire dictionary for exampledict_sample "company""toyota""model""premio""year" del dict_sample print(dict_sampleoutputnameerrorname 'dict_sampleis not defined the code returns an error the reason is we are trying to access the an dictionary which is doesn' exist since it is has been deleted howeveryour use-case may require you to just remove all dictionary elements and be left with an empty dictionary this can be achieved by calling the clear(function on the dictionary
11,257
"company""toyota""model""premio""year" dict_sample clear(print(dict_sampleoutput{the code is returns an empty dictionary since all the dictionary elements have been removed properties of dictionary keys dictionary values have no restrictions these can be any of erratically python objecteither they standard objects or user-defined objects howeversimilar is not true for the keys there are two important points to be remember about the dictionary keys( )more than one of the entry per key not allowed which means that no duplicate key isallowed when the duplicate keys are encountered during the assignmentandthe last assignment wins for exampledict {'name''zara''age' 'name''manni'}print "dict['name']"dict['name']outputdict['name']manni dict {['name']'zara''age' }print "dict['name']"dict['name'](bkeys must be immutable which mean by you can use stringsand the numbers or tuples as dictionary keys but something like ['key'is not allowed following is simple
11,258
traceback (most recent call last)file "test py"line in dict {['name']'zara''age' }typeerrorlist objects are unhashable operations in dictionary below is list of common dictionary operationscreate an empty dictionary {create three items dictionary {"one": "two": "three": access an element ['two'get list of all the keys keys(get list of all the value values(add an entry ["four"]= change an entry ["one""unodelete an entry del ["fourmake copy copy(remove all items
11,259
number of items len(xtest if has key has_key("one"looping over keys for item in keys()print item looping over values for item in values()print item using the if statement to get the values if "onein xprint ['one'if "twonot in xprint "two not foundif "threein xdel ['three' built-in dictionary functions function is procedure that can be applied on construct to get value furthermoreit doesn' modify the construct python gives us few functions that we can apply on python dictionary take look len()the len(function returns the length of the dictionary in python every key-value pair adds to the length len(dict output len({}any({false:false,'':''}an empty python dictionary has length of
11,260
like it is with lists an tuplesthe any(function returns true if even one key in dictionary has boolean value of true outputfalse outputany({true:false,"":""}true all()unlike the any(functionall(returns true only if all the keys in the dictionary have boolean value of true outputall({ : , :'',"": }false sorted()like it is with lists and tuplesthe sorted(function returns sorted sequence of the keys in the dictionary the sorting is in ascending orderand doesn' modify the original python dictionary dict ={ : , : , : but to see its effectlet' first modify dict nowlet' apply the sorted(function on it output[ as you can seethe original python dictionary wasn' modified dict this function returns the keys in sorted list to prove thislet' see what the type(function returns output
11,261
{ dict type(sorted(dict ) built-in dictionary methods method is set of the instructions to execute on the constructand it may be modify the construct to do thisthe method must be called on the constructlet' look at the available the methods for dictionaries dict keys(let' use dict for this example keys()dict_keys([ ]the keys(method returns list of keys in python dictionary dict values(output values()likewisethe values(method returns list of values in the dictionary outputdict_values([ ] items(this method returns list of key-value pairs outputdict_items([( )( )( )] summary tuplesin pythontuples are structured and accessed based on position tuple is collection of python objects separated by commas in some ways tuple is similar to list in terms of indexingnested objects and repetition but tuple is absolute unlike lists that are variable in python it is an unordered collection of data valuesused to store data values like mapwhich unlike other data types that hold only single value as an element tuples are absolute lists elements of list can be modifiedbut elements in tuple can only be accessednot modified the
11,262
structure dictionariesdictionaries in python are structured and accessed using keys and values dictionaries are defined in python with curly braces commas separate the key-value pairs that make up the dictionary dictionaries are made up of key and/or value pairs in pythontuples are organized and accessed based on position the location of pair of keys and values stored in python dictionary is unrelated key value is provided in the dictionary to make it more optimized python dictionary is basically hash table in some languagesthey might be mentioned to an associative arrays they are indexed with keyswhich can be any absolute type questions let list [' '' '' ',' '' '' 'find alist[ : bt[: ct[ : state the difference between lists and dictionary what is the benefit of using tuple assignment in python define dictionary with an example write python program to swap two variables define tuple and show it is immutable with an example create tuple with single element how can you access elements from the dictionary write python program to create tuple with different data types write python program to unpack tuple in several variables references ****
11,263
files and exceptions unit structure objective text files the file object attributes directories built-in exceptions handling exceptions exception with arguments user-defined exceptions summary exercise references objective to understand how python will raise an exception to create program to catch an exception using try/except block to study the python errors and exceptions to study creation and use of read and write commands for files in python to understand how to openwrite and close files in python text files now we will learn about various ways to read text files in python the following shows how to read all texts from the readme txt file into stringwith open('readme txt'as flines readlines(steps for reading text file in pythonto read the text file in the pythonyou have to follow these steps
11,264
open(method secondyou have to read the text from the text file using the file read()readline()or readlines(method of the file object thirdyou have to close the file using the file close(method open(function the open(function has many parameters but you'll be focusing on the first two open(path_to_filemodethe path to the file parameter is specifies the path to the text file if the file is in the same folder as is programyou have just need to specify the file name otherwiseyou have need to specify the path to the file specify the path to the fileyou have to use the forward-slash ('/'even if you are working in windows exampleif the file is in the readme txt stored in the sample folder as the programyou have need to specify the path to the file as :/sample/readme txt mode is in the optional parameter this is the string that is specifies the mode in which you want to open the file the following table shows available modes for opening text filemode description 'ropen for text file for reading text 'wopen text file for writing text 'aopen text file for appending text for exampleto open file whose name is the-zen-of-python txt stored in the same folder as the programyou use the following codef open('the-zen-of-python txt',' 'the open(function returns file object which you will use to read text from text file reading text methodsthe file object provides you with three methods for reading text from text file
11,265
have small file 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 list of strings close(methodthe file that you open will remain open until you close it using the close(method it' important to close the file that is no longer in use if you don' close the filethe program may crash or the file would be corrupted the following shows how to call the close(method to close the filef close(to close the file automatically without calling the close(methodyou use the with statement like thiswith open(path_to_fileas fcontents readlines(in practiceyou'll use the with statement to close the file automatically reading text file exampleswe'll use the-zen-of-python txt file for the demonstration the following example illustrates how to use the read(method to read all the contents of the the-zen-of-python txt file into stringwith open('the-zen-of-python txt'as fcontents read(print(contentsoutputbeautiful is better than ugly explicit is better than implicit simple is better than complex
11,266
and returns the file contents as list of stringslines [with open('the-zen-of-python txt'as flines readlines(count for line in linescount + print( 'line {count}{line}'outputline beautiful is better than ugly line explicit is better than implicit line simple is better than complex the file object attributes once file is opened and you have one file objectyou can get various information related to that file here is list of all attributes related to file objectattribute file closed file mode file name file softspace description returns true if file is closedfalse otherwise returns access mode with which file was opened returns name of the file returns false if space explicitly required with printtrue otherwise example open file fo open("foo txt""wb"print "name of the file"fo name print "closed or not "fo closed print "opening mode "fo mode print "softspace flag "fo softspace
11,267
name of the filefoo txt closed or not false opening mode wb softspace flag directories in this python directory tutorialwe will import the os module to be able to access the methods we will apply import os how to get current python directoryto find out which directory in python you are currently inuse the getcwd(method os getcwd(output' :\\users\\lifei\\appdata\\local\\programs\\python\\python - cwd is for current working directory in python this returns the path of the current python directory as string in python to get it as bytes objectwe use the method getcwdb(os getcwdb(outputb' :\\users\\lifei\\appdata\\local\\programs\\python\\python - herewe get two backslashes instead of one this is because the first one is to escape the second one since this is string object type(os getcwd()to render it properlyuse the python method with the print statement print(os getcwd()
11,268
changing current python directory to change our current working directories in pythonwe use the chdir(method this takes one argumentthe path to the directory to which to change output'unicodeescapecode can' decode bytes in position - truncated \uxxxxxxxx escape but remember that when using backward slashesit is recommended to escape the backward slashes to avoid problem outputhow to create python directorywe can also create new python directories with the mkdir(method it takes one argumentthat isthe path of the new python directory to create os mkdir('christmas photos'os listdir(output['adobe photoshop cs lnk''atom lnk''burn book txt''christmas photos''desktop ini''documents''eclipse cpp oxygen lnk''eclipse java oxygen lnk''eclipse jee oxygen lnk''for the book txt''items for trip txt''papers''remember to remember txt''sweet anticipation png''today txt''topics txt''unnamed jpg'how to rename python directory?to rename directories in pythonwe use the rename(method it takes two argumentsthe python directory to renameand the new name for it os rename('christmas photos','christmas 'os listdir(output['adobe photoshop cs lnk''atom lnk''burn book txt''christmas ''desktop ini''documents''eclipse cpp oxygen lnk''eclipse
11,269
trip txt''papers''remember to remember txt''sweet anticipation png''today txt''topics txt''unnamed jpg'how to remove python directorywe made file named 'readme txtinside our folder christmas to delete this filewe use the method remove(os chdir(' :\\users\\lifei\\desktop\\christmas 'os listdir(output['readme txt' built-in exceptions illegal operations can raise exceptions there are plenty of built-in exceptions in python that are raised when corresponding errors occur we can view all the built-in exceptions using the built-in local(function as print(dir(locals()['__builtins__'])followslocals()['__builtins__'will return module of built-in exceptionsfunctionsand attributes dir allows us to list these attributes as strings some of the common built-in exceptions in python programming along with the error that cause them are listed belowexception assertionerror fails cause of error raised when an assert statement attributeerror raised when attribute assignment or reference fails raised when the input(function hits end-of-file condition raised when floating point operation fails raise when generator' close(method is called raised when the imported module is not found raised when the index of sequence is out of range raised when key is not found in dictionary raised when the user hits the interrupt key (ctrl+ or deleteeoferror floatingpointerror generatorexit importerror indexerror keyerror keyboardinterrupt
11,270
nameerror raised when an operation runs out of memory raised when variable is not found in local or global scope notimplementederror raised by abstract methods oserror raised when system operation causes system related error overflowerror raised when the result of an arithmetic operation is too large to be represented referenceerror raised when weak reference proxy is used to access garbage collected referent runtimeerror raised when an error does not fall under any other category stopiteration raised by next(function to indicate that there is no further item to be returned by iterator syntaxerror raised by parser when syntax error is encountered indentationerror raised when there is incorrect indentation taberror raised when indentation consists of inconsistent tabs and spaces systemerror raised when interpreter detects internal error systemexit raised by sys exit(function typeerror raised when function or operation is applied to an object of incorrect type unboundlocalerror raised when reference is made to local variable in function or methodbut no value has been bound to that variable unicodeerror raised when unicode-related encoding or decoding error occurs unicodeencodeerror raised when unicode-related error occurs during encoding unicodedecodeerror raised when unicode-related error occurs during decoding unicodetranslateerror raised when unicode-related error occurs during translating valueerror raised when function gets an argument of correct type but improper value zerodivisionerror raised when the second operand of division or modulo operation is zero handling exceptions if you have some suspicious code that may raise an exceptionyou can defend your program by placing the suspicious code in tryblock after the tryblockinclude an exceptstatementfollowed by block of code which handles the problem as elegantly as possible syntaxhere is simple syntax of try except else blocks
11,271
you do your operations hereexcept exceptioniif there is exceptionithen execute this block except exceptioniiif there is exceptioniithen execute this block elseif there is no exception then execute this block here are few important points about the above-mentioned syntax single try statement can have multiple except statements this is useful when the try block contains statements that may throw different types of exceptions you can also provide generic except clausewhich handles any exception after the except clause( )you can include an else-clause the code in the else-block executes if the code in the tryblock does not raise an exception the else-block is good place for code that does not need the tryblock' protection examplethis example opens filewrites content in thefile and comes out gracefully because there is no problem at alltryfh open("testfile"" "fh write("this is my test file for exception handling!!"except ioerrorprint "errorcan\' find file or read dataelse
11,272
fh close(this produces the following resultwritten content in the file successfully exception with arguments why use argument in exceptionsusing arguments for exceptions in python is useful for the following reasonsit can be used to gain additional information about the error encountered as contents of an argument can vary depending upon different types of exceptions in pythonvariables can be supplied to the exceptions to capture the essence of the encountered errors same error can occur of different causesarguments helps us identify the specific cause for an error using the except clause it can also be used to trap multiple exceptionsby using variable to follow the tuple of exceptions arguments in buil-in exceptionsthe below codes demonstrates use of argument with built-in exceptionsexample tryb float( except exception as argumentprint'this is the argument\ 'argumentoutputthis is the argument division by zero arguments in user-defined exceptionsthe below codes demonstrates use of argument with user-defined exceptions
11,273
create user-defined exception derived from super class exception class myerror(exception)constructor or initializer def __init__(selfvalue)self value value __str__ is to print(the value def __str__(self)return(repr(self value)tryraise(myerror("some error data")value of exception is stored in error except myerror as argumentprint('this is the argument\ 'argumentoutput'this is the argument 'some error data user-defined exceptions creating user-defined exception programmers may name their own exceptions by creating new exception class exceptions need to be derived from the exception classeither directly or indirectly although not mandatorymost of the exceptions are named as names that end in "errorsimilar to naming of the standard exceptions in python for examplea python program to create user-defined exception class myerror is derived from super class exception class myerror(exception)constructor or initializer def __init__(selfvalue)
11,274
__str__ is to print(the value def __str__(self)return(repr(self value)tryraise(myerror( * )value of exception is stored in error except myerror as errorprint(' new exception occured',error valueouput(' new exception occured' summary filespython supports file handling and allows users to handle files for exampleto read and write filesalong with many other file handling optionsto operate on files the concept of file handling has justified by various other languagesbut the implementation is either difficult python delights file differently as text or binary and this is significant each line of code includes sequence of characters and they form text file each line of file is ended with special character like comma {,it ends the current line and expresses the interpreter new one has started in python file is contiguous set of bytes used to store data this data is organized in precise format and can be anything as simple as text file in the endthese byte files are then translated into binary and for simple for processing in pythona file operation takes place in the order like open file then read or write and finally close the file exceptionspython provides two important features to handle any unexpected error in python programs and to add debugging capabilities in them in pythonall exceptions must be occurrences of class that arises from baseexception in try statement with an except clause that references particular classthat clause further handles any exception classes derived from that class two exception classes that are not connected via sub classing are never equaleven if they have the same name user code can advance built-in exceptions this can be used to test an exception handler and also to report an error condition
11,275
write python program to read an entire text file write python program to append text to file and display the text write python program to read file line by line store it into variable write python program to count the number of lines in text file write python program to write list to file write python program to extract characters from various text files and puts them into list what are exceptions in python when would you not use try-except when will the else part of try-except-else be executed how can one block of except statements handle multiple exception references ****
11,276
regular expression unit structure objectives introduction concept of regular expression various types of regular expressions using match function summary bibliography unit end exercise objectives regular expressions are particularly useful for defining filters regular expressions contain series of characters that define pattern of text to be matched--to make filter more specializedor general the regular expression ^al]searches for all items beginning with al introduction regular expressions (called resor regexesor regex patternsare essentially tinyhighly specialized programming language embedded inside python and made available through the re module using this little languageyou specify the rules for the set of possible strings that you want to matchthis set might contain english sentencesor -mail addressesor tex commandsor anything you like you can then ask questions such as "does this string match the pattern?"or "is there match for the pattern anywhere in this string?you can also use res to modify string or to split it apart in various ways regular expression patterns are compiled into series of bytecodes which are then executed by matching engine written in for advanced useit may be necessary to pay careful attention to how the engine will execute given reand write the re in certain way in order to produce bytecode that runs faster optimization isn' covered in this documentbecause it requires that you have good understanding of the matching engine' internals
11,277
so not all possible string processing tasks can be done using regular expressions there are also tasks that can be done with regular expressionsbut the expressions turn out to be very complicated in these casesyou may be better off writing python code to do the processingwhile python code will be slower than an elaborate regular expressionit will also probably be more understandable concept of regular expression you may be familiar with searching for text by pressing ctrl- and typing in the words you're looking for regular expressions go one step furtherthey allow you to specify pattern of text to search for regular expressions are helpfulbut not many non-programmers know about them even though most modern text editors and word processorssuch as microsoft word or openofficehave find and findand-replace features that can search based on regular expressions regular expressions are huge time-saversnot just for software users but also for programmers finding patterns of text without regular expressions say you want to find phone number in string you know the patternthree numbersa hyphenthree numbersa hyphenand four numbers exampleregular expressionscalled regexes for shortare descriptions for pattern of text for examplea \ in regex stands for digit character-that isany single numeral to the regex \ \ \ -\ \ \ -\ \ \ \ is used by python to match the same text the string of three numbersa hyphenthree more numbersanother hyphenand four numbers any other string would not match the \ \ \ -\ \ \ -\ \ \ \ regex but regular expressions can be much more sophisticated
11,278
adding in curly brackets ({ }after pattern is like saying"match this pattern three times so the slightly shorter regex \ { }-\ { }-\ { also matches the correct phone number format symbol and it' meaningquantifiers various types of regular expressions the "repackage provides several methods to actually perform queries on an input string we will see the methods of re in pythonnotebased on the regular expressionspython offers two different primitive operations the match method checks for match only at the beginning of the string while search checks for match anywhere in the string
11,279
re search(function will search the regular expression pattern and return the first occurrence unlike python re match()it will check all lines of the input string the python re search(function returns match object when the pattern is found and "nullif the pattern is not found in order to use search(functionyou need to import python re module first and then execute the code the python re search(function takes the "patternand "textto scan from our main string the search(function searches the string for matchand returns match object if there is match if there is more than one matchonly the first occurrence of the match will be returnedexamplesearch for the first white-space character in the stringimport re txt "the rain in spainx re search("\ "txtprint("the first white-space character is located in position:" start()outputthe first white-space character is located in position the split(functionthe split(function returns list where the string has been split at each matchexamplesplit at each white-space characterimport re txt "the rain in spainx re split("\ "txtprint(xoutput['the','rain','in','spain'
11,280
findall(module is used to search for "alloccurrences that match given pattern in contrastsearch (module will only return the first occurrence that matches the specified pattern findall (will iterate over all the lines of the file and will return all non-overlapping matches of pattern in single step the findall (function returns list containing all matches exampleprint list of all matchesimport re txt "the rain in spainx re findall("ai"txtprint(xoutput['ai'ai'for examplehere we have list of -mail addressesand we want all the -mail addresses to be fetched out from the listwe use the method re findall(in python it will find all the -mail addresses from the list the sub (functionthe sub(function replaces the matches with the text of your choicereplace every white-space character with the number import re txt "the rain in spainx re sub("\ "" "txtprint(xoutputthe rain in spain you can control the the count parameternumber of examplereplace the first occurrences replacements by specifying
11,281
txt "the rain in spainx re sub("\ "" "txt print(xoutputthe rain inspain using match function re match(function of re in python will search the regular expression pattern and return the first occurrence the python regex match method checks for match only at the beginning of the string soif match is found in the first lineit returns the match object but if match is found in some other linethe python regex match function returns null example do search that will return match objectimport re txt "the rain in spainx re search("ai"txtprint( #this will print an object outputthe match object has properties and methods used to retrieve information about the searchand the resultspan(returns tuple containing the start-and end positions of the match string returns the string passed into the function group(returns the part of the string where there was match exampleprint the string passed into the functionimport re txt "the rain in spainx re search( "\bs\ +"txt
11,282
outputthe rain in spain exampleprint the part of the string where there was match the regular expression looks for any words that starts with an upper case " "import re txt "the rain in spainx re search( "\bs\ +"txtprint( group()outputspain email validation example validate the email from file as well from string by using regular expressionimporting the module re
11,283
regular expression in programming language is special text string used for describing search pattern it includes digits and punctuation and all special characters like $#@!%etc expression can include literal text matching repetition branching pattern-composition etc in pythona regular expression is denoted as re (resregexes or regex patternare embedded through python re module
11,284
python for beginners by shroff publishers unit end exercises explain the regular expression and pattern matching in details write code to validate mobile number by using regular expressions write code to validate url by using regular expressions write code to validate email by using regular expressions ****
11,285
classes and objects unit structure objectives overview of oop class definitioncreating objects instances as argumentsinstances as return values built-in class attributes inheritance method overriding data encapsulation data hiding summary unit end exercise bibliography objectives classes provide an easy way of keeping the data members and methods together in one place which helps in keeping the program more organized using classes also provides another functionality of this objectoriented programming paradigmthat isinheritance classes also help in overriding any standard operator overview of oop python is an object-oriented programming language it allows us to develop applications using object oriented approach in pythonwe can easily create and use classes and objects major principles of object-oriented programming system are given below object class method inheritance
11,286
data abstraction encapsulation objectobject is an entity that has state and behavior it may be anything it may be physical and logical for examplemousekeyboardchairtablepen etc classclass can be defined as collection of objects it is logical entity that has some specific attributes and methods inheritanceinheritance is feature of object-oriented programming it specifies that one object acquires all the properties and behaviors of parent object by using inheritance you can define new class with little or no changes to the existing class the new class is known as derived class or child class and from which it inherits the properties is alled base class or parent class it provides re-usability of the code polymorphismpolymorphism is made by two words "polyand "morphspoly means many and morphs means formshape it defines that one task can be performed in different ways for exampleyou have class animal and all animals talk but they talk differently herethe "talkbehavior is polymorphic in the sense and totally depends on the animal sothe abstract "animalconcept does not actually "talk"but specific animals (like dogs and catshave concrete implementation of the action "talkencapsulationencapsulation is also the feature of object-oriented programming it is used to restrict access to methods and variables in encapsulationcode and data are wrapped together within single unit from being modified by accident data abstractiondata abstraction and encapsulation both are often used as synonyms both are nearly synonym because data abstraction is achieved through encapsulation abstraction is used to hide internal details and show only functionalities abstracting something means to give names to thingsso that the name captures the core of what function or whole program does
11,287
classclass can be defined as collection of objects it is logical entity that has some specific attributes and methods for exampleif you have an employee class then it should contain an attribute and method an email idnameagesalary etc for exampleif you have an employee class then it should contain an attribute and method an email idnameagesalary etc syntaxclass classnamemethodmethod is function that is associated with an object in pythonmethod is not unique to class instances any object type can have methods objectobject is an entity that has state and behavior it may be anything it may be physical and logical for examplemousekeyboardchairtablepen etc everything in python is an objectand almost everything has attributes and methods all functions have built-in attribute __doc__which returns the doc string defined in the function source code syntax class classnameself instance_variable value #value specific to instance class_variable value #value shared across all class instances #accessing instance variable class_instance classname(class_instance instance_variable #accessing class variable classname class_variable example class carwheels class variable def __init__(selfmake)
11,288
newcar car("honda"print ("my new car is {}format(newcar make)print ("my carlike all carshas {%dwheelsformat(car wheels) instances as arguments and instances as return values functions and methods can return objects this is actually nothing new since everything in python is an object and we have been returning values for quite some time the difference here is that we want to have the method create an object using the constructor and then return it as the value of the method suppose you have point object and wish to find the midpoint halfway between it and some other target point we would like to write methodcall it halfway that takes another point as parameter and returns the point that is halfway between the point and the target exampleclass pointdef __init__(selfinitxinity)""create new point at the given coordinates ""self initx self inity def getx(self)return self def gety(self)return self def distancefromorigin(self)return ((self * (self * )* def __str__(self)return " =str(self " =str(self ydef halfway(selftarget)mx (self target my (self target return point(mxmyp point( point( mid halfway(qprint(midprint(mid getx()print(mid gety()
11,289
we can also use any other methods since mid is point object in the definition of the method halfway see how the requirement to always use dot notation with attributes disambiguates the meaning of the attributes and ywe can always see whether the coordinates of point self or target are being referred to instances as return valueswhen you call an instance method ( func from an instance object ( inst )python automatically passes that instance object as the first argumentin addition to any other arguments that were passed in by the user in the example there are two classes vehicle and truckobject of class truck is passed as parameter to the method of class vehicle in method main(object of vehicle is created then the add_truck(method of class vehicle is called and object of truck class is passed as parameter exampleclass vehicledef __init__(self)self trucks [def add_truck(selftruck)self trucks append(truckclass truckdef __init__(selfcolor)self color color def __repr__(self)return "{}format(self colordef main() vehicle(for in 'red blue blacksplit() truck(tv add_truck(tprint( trucksif __name__ ="__main__"main(
11,290
[redblueblack built-in class attributes every python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute __dict__ dictionary containing the class' namespace __doc__ class documentation string or noneif undefined __name__ class name __module__ module name in which the class is defined this attribute is "__main__in interactive mode __bases__ possibly empty tuple containing the base classesin the order of their occurrence in the base class list examplefor the above class let us try to access all these attributes classemployee'common base class for all employeesempcount = def __init__(selfnamesalary)self name name self salary salary employee empcount += def displaycount(self)print"total employee % "%employee empcount def displayemployee(self)print"name ",self name,"salary",self salary print"employee __doc__:",employee __doc__ print"employee __name__:",employee __name__ print"employee __module__:",employee __module__ print"employee __bases__:",employee __bases__ print"employee __dict__:",employee __dict__ outputwhen the above code is executedit produces the following result employee __doc__common base class for all employees employee __name__employee employee __module____main__ employee __bases__(employee __dict__{'__module__''__main__''displaycount'
11,291
'displayemployee''__doc__''common base class for all employees''__init__' inheritance what is inheritanceinheritance is feature of object oriented programming it is used to specify that one class will get most or all of its features from its parent class it is very powerful feature which facilitates users to create new class with few or more modification to an existing class the new class is called child class or derived class and the main class from which it inherits the properties is called base class or parent class the child class or derived class inherits the features from the parent classadding new features to it it facilitates re-usability of code python multilevel inheritancemultilevel inheritance is also possible in python like other object oriented programming languages we can inherit derived class from another derived classthis process is known as multilevel inheritance in pythonmultilevel inheritance can be done at any depth
11,292
python supports multiple inheritance too it allows us to inherit multiple parent classes we can derive child class from more than one base (parentclasses
11,293
method overriding is an ability of any object-oriented programming language that allows subclass or child class to provide specific implementation of method that is already provided by one of its super-classes or parent classes when method in subclass has the same namesame parameters or signature and same return type(or sub-typeas method in its super-classthen the method in the subclass is said to override the method in the super-class the version of method that is executed will be determined by the object that is used to invoke it if an object of parent class is used to
11,294
but if an object of the subclass is used to invoke the methodthen the version in the child class will be executed in other wordsit is the type of the object being referred to (not the type of the reference variablethat determines which version of an overridden method will be executed exampleclass parent()constructor def __init__(self)self value "inside parentparent' show method def show(self)print(self valuedefining child class class child(parent)constructor def __init__(self)self value "inside childchild' show method def show(self)print(self valuedriver' code obj parent(obj child(obj show(obj show(outputinside parent inside child data encapsulation encapsulation is one of the fundamental concepts in objectoriented programming (oopit describes the idea of wrapping data and the methods that work on data within one unit this puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data to prevent accidental changean object' variable
11,295
known as private variable class is an example of encapsulation as it encapsulates all the data that is member functionsvariablesetc consider real-life example of encapsulationin companythere are different sections like the accounts sectionfinance sectionsales section etc the finance section handles all the financial transactions and keeps records of all the data related to finance similarlythe sales section handles all the sales-related activities and keeps records of all the sales now there may arise situation when for some reason an official from the finance section needs all the data about sales in particular month in this casehe is not allowed to directly access the data of the sales section he will first have to contact some other officer in the sales section and then request him to give the particular data this is what encapsulation is creating base class class basedef __init__(self)protected member self _a creating derived class class derived(base)def __init__(self)calling constructor of base class base __init__(selfprint("calling protected member of base class"print(self _aobj derived(obj base(calling protected member outside class will result in attributeerror print(obj
11,296
calling protected member of base class traceback (most recent call last)file "/home/ fb dfba dd eb py"line in print(obj aattributeerror'baseobject has no attribute ' data hiding what is data hidingdata hiding is part of object-oriented programmingwhich is generally used to hide the data information from the user it includes internal object details such as data membersinternal working it maintained the data integrity and restricted access to the class member the main working of data hiding is that it combines the data and functions into single unit to conceal data within class we cannot directly access the data from outside the class this process is also known as the data encapsulation it is done by hiding the working information to user in the processwe declare class members as private so that no other class can access these data members it is accessible only within the class data hiding in pythonpython is the most popular programming language as it applies in every technical domain and has straightforward syntax and vast libraries in the official python documentationdata hiding isolates the client from part of program implementation some of the essential members must be hidden from the user programs or modules only reflected how we could use thembut users cannot be familiar with how the application works thus it provides security and avoiding dependency as well we can perform data hiding in python using the __ double underscore before prefix this makes the class members private and inaccessible to the other classes example class counterclass__privatecount
11,297
self __privatecount + print(self __privatecountcounter counterclass(counter count(counter count(print(counter __privatecountoutput traceback (most recent call last)file ""line in attributeerror'counterclassobject has no attribute '__privatecount summary it allows us to develop applications using an object-oriented approach in pythonwe can easily create and use classes and objects an object-oriented paradigm is to design the program using classes and objects the oops concept focuses on writing the reusable code unit end exercise explain the object oriented concept in details explain the instance return values in details explain the data hiding and data encapsulation with examples write python code to create animal class and in it create one instance variable and access it through object explain multiple and multilevel inheritance with examples bibliography basics/instancesasrreturnvalues html :text=when% % call% an% instance,passed% in% by% the% user ****
11,298
multithreaded programming unit structure objectives introduction thread module creating thread synchronizing threads multithreaded priority queue summary bibliography unit end exercise objectives to use multithreading to achieve multithreading to use the threading module to create threads address issues or challenges for threads introduction what is thread in computer sciencein software programminga thread is the smallest unit of execution with the independent set of instructions it is part of the process and operates in the same context sharing program' runnable resources like memory thread has starting pointan execution sequenceand result it has an instruction pointer that holds the current state of the thread and controls what executes next in what order what is multithreading in computer sciencethe ability of process to execute multiple threads parallelly is called multithreading ideallymultithreading can significantly improve the performance of any program and python multithreading mechanism is pretty user-friendlywhich you can learn quickly
11,299
it is started with python designated as obsoleteand can only be accessed with _thread that supports backward compatibility how to find nth highest salary in sql syntaxthread start_new_thread function_nameargs[kwargsto implement the thread module in pythonwe need to import thread module and then define function that performs some action by setting the target with variable example:thread py import thread import the thread module import time import time module def cal_sqre(num)define the cal_sqre function print(calculate the square root of the given number"for in numtime sleep( at each iteration it waits for time print(square is ' ndef cal_cube(num)define the cal_cube(function print(calculate the cube of the given number"for in numtime sleep( at each iteration it waits for time print(cube is " *narr [ given array time time(get total time to execute the functions cal_sqre(arrcall cal_sqre(function cal_cube(arrcall cal_cube(function print(total time taken by threads is :"time time( print the total time outputcalculate the square root of the given number square is square is square is square is