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 repea...
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 pr...
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 exam...
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...
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 changey...
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 ...
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 rec...
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 integ...
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 argum...
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 t...
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...
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 turn...
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("h...
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 ...
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 ...
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("...
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 p...
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 pa...
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 e...
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'...
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...
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...
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 sing...
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 i...
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 '...
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 t...
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 [ : ...
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 el...
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 operatorsconca...
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 operato...
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...
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 ...
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...
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 replac...
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 ma...
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 ...
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 li...
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 m...
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 diction...
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...
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 i...
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 m...
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(tu...
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 se...
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 a...
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 membersh...
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 differe...
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')#c...
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 (( )(' #'' ++''pyth...
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 t...
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 v...
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 int...
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 fol...
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 dictiona...
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'...
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...
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 u...
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 ...
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 proce...
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 ...
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([ ]th...
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 posit...
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 tr...
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 th...
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(meth...
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 ...
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...
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 recomme...
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-...
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 ...
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 sta...
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 ...
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 arg...
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 ...
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 extrac...
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 defin...
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 elabora...
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 o...
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 i...
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 (functio...
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 li...
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 us...
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 (resre...
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 ...
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...
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 meth...
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 fo...
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 ret...
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 whi...
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...
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(o...
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 de...
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 tr...
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 inc...
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 appr...
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 f...
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 per...