id
int64
0
25.6k
text
stringlengths
0
4.59k
4,300
def argument_test_natural_number( )def helper( )if type(xis int and return (xelseraise exception("argument is not an integer"return helper @argument_test_natural_number def factorial( )if = return elsereturn *factorial( - factorial( out[ ] in [ ]factorial(- exception traceback (most recent call lastin ---- factorial(- in helper( return ( else---- raise exception("argument is not an integer" return helper exceptionargument is not an integer in [ ]def sum_aritmetic_series( )return *( + )/ sum_aritmetic_series( out[ ] in [ ]sum_aritmetic_series( out[ ] in [ ]@argument_test_natural_number def sum_aritmetic_series( )return *( - )/ sum_aritmetic_series( out[ ]
4,301
sum_aritmetic_series( exception traceback (most recent call lastin ---- sum_aritmetic_series( in helper( return ( else---- raise exception("argument is not an integer" return helper exceptionargument is not an integer fixing the fibonacci series in [ ]def memoize( )memo {def helper( )if not in memomemo[nf(nreturn memo[nreturn helper arguments [@memoize def fib( )arguments append(nif = return elif = return elsereturn fib( - fib( - [fib(ifor in range( )out[ ][ in [ ]counts {iarguments count(ifor in range(max(arguments)+ )counts out[ ]{ in [ ]sum(counts values()out[ ] there is built-in cache decorator
4,302
built-in least-recently used cache decorator import functools @functools lru_cache(maxsize= typed=falsedef fib( )if return elsereturn fib( - fib( - static variables in [ ]exercise write decorator counting the number of times function was called the same but for varying number of parameters and keyword-arguments def counter(func)first define function def helper( *args**kwargs)helper count + return func( *args**kwargsreturn function as it is thendefine an attribute to be incremented with every call this attribute behaves like static variable helper exist only after the function definition once definedthen we can attach an attribute helper count return helper @counter def fun( )return fun( fun( fun( fun count out[ ] generators in [ ] "pythonitero iter(sitero what write isfor char in swhat python doesfor char in iter(sin fact it is while loop until stop is reached out[ ]in [ ]next(iteroout[ ]'
4,303
next(iteroout[ ]'yin [ ]next(iteroout[ ]'tin [ ]next(iteroout[ ]'hin [ ]next(iteroout[ ]'oin [ ]next(iteroout[ ]'nin [ ]next(iterostopiteration traceback (most recent call lastin ---- next(iterostopiterationown generator in [ ]def abc_generator()yield "ayield "byield "cx abc_generator(we call like function function returns an object for in xprint(ia
4,304
next(xstopiteration traceback (most recent call lastin ---- next(xstopiterationin [ ]print(next( )<-yield "aprint(next( )<-yield "bprint(next( )<-yield "cthis is co-process this function creates code waiting to be executedwhen we assign abc_generatorafter it reaches yieldit returns value and stops then next is positioned fter the yield abc_generator(print(next( )print(next( )print(next( )print(next( ) stopiteration traceback (most recent call lastin print(next( ) print(next( )--- print(next( )stopiterationa function is also single-value generator in [ ]def abc_generator()return "ax abc_generator(for in xprint(iworksbecause the returned value is iterable in [ ]type(abc_generator()out[ ]str in [ ]def abc_generator()for char in [" "" "" "]yield char for in abc_generator()print(ia
4,305
type(abc_generator()out[ ]generator in ]generate pi value pi/ / / / def pi_series()sum while truesum sum / yield *sum - runs forever we can break with counterbut it is not good idea for in pi_series()print(iin ]def firstn(gn)for in range( )yield next(gprint(list(firstn(pi_series() )) context manager is used to allocate and release some sort of resource when we need it which means that before we start block we open fileand when we are going outthe file is automatically released if we don' closeit remains open in file system closing programit would close good practice is to always close with context managersthe benefit is no need to close the issue is with the exceptions with withthe exception is caught and handled context manager is general concept the concept is as follows with device()before check device start device we enter the block we do something after we execute stop block in case of exceptions we are sure that the after part will be executed in ]import csv with open('example txt'' 'as outcsv_out csv writer(outcsv_out writerow(['date''events']
4,306
for sciencfic compucngrapid development easyreadable syntax versacle tools for experimentacon/learning comprehensive libraries powerful features process data at near "nacve codespeeds excellent visualizacon packages comprehensive libraries
4,307
program interaccvely with ipython understand the basics of numpy and scipy efficiently compute with large arrays of data load and save data to/from files on disk use matplotlib to plot data take advantage of supercompucng resources with parallel compu ng know where to turn for more help with these topics
4,308
we are describing enthought python distribucon essencallypre--assembled compilacon of python numpyscipyother useful libraries free for academic usea basic version is free for non-commercial use your computersdepartmentsetc may have different version of python installed everything we will see today is open source in msimodule load python--epd
4,309
unix shell commands are indicated with the percent sign ipython interpreter commands have in/out labels neither sign indicates python code that should be entered into text file
4,310
powerful environment for interaccve work run as "ipythonfrom any terminal ----pylab opcon auto-loads numpysets up graphics for ploang inspect any object with "?or help(
4,311
build up workspace of objects and funccons full history access through out[]%recallup/down arrow keys %load%editor %run external files lots moretype %magic
4,312
numpy providesthe basic array and matrix data types efficient implementacons of low--level math operacons large library of high--level math funccons built from efficient primicves scipy providesa home for wide variety of open--source mathemaccal and sciencfic algorithms modules for opcmizaconsignal processinglinear algebrastacsccsinterpolaconand more
4,313
array data type with vectorized operacons(similar to matlab or idlsupports same operacons as python list type except every element is of same data type so they can be stored in memory packed like arrays
4,314
here we are comparing "pure pythonloop to the equivalent in numpy
4,315
numpy arrays are rectangles in arbitrarily many dimensions -operate element--by-element for same--shape arrays
4,316
index notacon gives access to any "sliceof an array array slices can be assigned this changes the original array [ ,:,:copy(would avoid changing
4,317
numpy arrays have many useful built--in methods
4,318
and the numpy module provides more
4,319
vectorized logical operators indexing funccons output of index funccons can be used to slice arrays
4,320
vectorized logical operators indexing funccons output of index funccons can be used to slice arrays
4,321
numpy fft fftsforward/inverse -- and -- numpy random generate random numbersmany distribucons to choose from numpy matrix special arrays that obey matrix math numpy polynomial module for represencng and manipulacng arbitrary polynomials
4,322
matplotlib provides high--quality -- (and some --dploang display in window or output to pdfsvgpngetc implemented as modular object--oriented system pylab provides matlab--ish interaccve interface to matplotlib access with ipython ----pylab defaults to popping up plots in separate window
4,323
4,324
these examples are from the matplotlib org examples seccon
4,325
4,326
4,327
4,328
4,329
clustering algorithms (scipy clusterintegracon and odes (scipy integrateinterpolacon (scipy interpolateinput and output (scipy iolinear algebra (scipy linalgmulc--dimensional image processing (scipy ndimageopcmizacon and root finding (scipy opcmizesignal processing (scipy signalsparse matrices (scipy sparsespacal algorithms and data structures (scipy spacalspecial funccons (scipy specialstacsccal funccons (scipy statsand then some
4,330
most scipy roucnes use fast numpy low--level math operacons some scipy roucnes use highly opcmized external libraries scipy linalg links to blaslapack or mkl behind the scenes
4,331
chances are you want to load and save data numpy and scipy io offer variety of facilices
4,332
very common for smaller data setssimple columns of numbers numpy loadtxt(simple interfacegood defaults numpy genfromtxt(more complexhandles unusual formaangcommentsmissing valuesetc
4,333
numpy savetxt(write to columns of numbers
4,334
binary data is much more scalable smaller files on disk faster to load and save may be necessary to exchange data with other sopware scck to portable (machine--independentformats
4,335
numpy na ve format npynumpy load(and numpy save(or use numpy savez(to store many arrays in compressed npz fastportablebut mostly only supported by python scipy io matlab support for matlab matscipy io loadmat(and scipy io savemat(scipy io idl read (no saveidl sav files scipy io readsav(
4,336
many standard formats supported scipy io netcdf netcdf interface py exposes hdf api pytables is an excellent high--level interface to hdf pyfits for fits datasets etc
4,337
for big jobs you will eventually want to parallelize your code the python interpreter has trouble with mulcthreading mulc--process is usually best approach depends on the problem you need to solve
4,338
many jobs need to process lots of datadon' need to communicate amongst themselves somecmes called "embarrassingly parallelgnu parallel --- simple way to launch jobs launch one job for every file in dirline in fileetc can work with pbs on itasca to use many nodes
4,339
4,340
-- should match ppn (unless you know what you're doingthis is processes per node will run one job per line of input on stdin or in argfile max of nodes ppn running at once see "man parallelfor more features
4,341
mpi "message passing interfaceenables parallel processes to communicate efficiently commonly one process will be "controllerand manage worker processes inherent support for scaser--gather operacons mpi is well--supported on our clusters mpi py interfaces to mpi from inside python caveat for mpi gurusnumpy does not have distributed arrays yetcomplicates some algorithms
4,342
simple "hello worldscript
4,343
simple "hello worldscript
4,344
possible to pass numpy arrays like buffers
4,345
also works with (pickle--ablepython objects much slower than --based arraysbut very convenient
4,346
ipython notebook connect to ipython with browser for mathemacca--like notebook interface pycuda and pyopencl gpu compucng sympy mathemacca--style symbolic math databases are easy to connect to pythonor use advanced big data toolkit like pandas or pytables
4,347
exampleipython notebook with pylab and sympy notebook creates graphical log in browser sympysymbolic cas to try this
4,348
non-data descriptor __getattribute__ breaks the descriptor usage use more than one instance for testing examples conclusion more examples generalized attribute validation function decorators @property descriptors generalized validation summary inheritance with super super child before parent inherit __init__ inherit __init__ of multiple classes math problem conclusion generators feed iterations receive values send and receive values return values in generator 'yield fromcommand unix commands introduction 'argparse find command details python implementation grep cat caffe installation in ubuntu prerequisite install packages create virtualenv install virtualenv modify bashrc create virtualenv install opencv install caffe index
4,349
python review introduction python is the programming language which can be used for various purposes web designmathematical modelingcreating documents and game designs etc in this we will review some of the basic features of python thenfrom next we will write some good coding styles with advance features of python notethis presents short review of python along with some good coding practices actual tutorial begins from next if you have basic knowledge of python and oops then you can skip this download and installation we will use python in this tutorial alsothese codes may not run in python ( or etc versions furtherthere are several useful libraries available for python for examplenumpy and scipy libraries contain various mathematical functions which are very useful in simulations matplotlib library is required to plot results and save these in various formats pdfjpeg or ps etc lastlyspyder environment is very helpful for storing the results obtained by the simulations alsospyder can save data as matfilewhich can be used by matlab software as well all these topics are briefly discussed in this tutorial for installationsimplest option is to download and install anaconda softwareas it contains various useful python libraries (including the libraries which are mentioned in above paragraph basics in this section'printcommand is used to show the code execution in python in pythoncode can be run in two waysi through 'python shellor 'by executing the python files'which are discussed next run code from python shell (go to terminal/command-prompt and type python as shown in listing this command will start the python shell with three 'greater thansigns nowwe can write our first command print('hello world')which prints the 'hello worldon the screen as shown in the listing further in line two placeholder '%sare usedwhich are replaced by the two words world and python as shown in line alsoafter executing the commandappear againwhich indicates that python shell is ready to get more commands notechoose correct command to open python
4,350
python (linuxor python (linuxor :\>python (in windowslisting hello world print("hello world"hello world print("hello % simulation can be done using % ("world""python")hello worldsimulation can be done using python running python files we can also save the code in python file with extension py'which can be run from python shell for examplelet file 'hello pyis saved in the folder name as 'pythoncodesat cdrive content of the 'hello pyis shown in listing '#in the file is used for comments (which increases the readability of the code)and has no effect in the execution of the code to run the 'hello py'we need to locate the folder 'pythoncodes(where we saved the hello py fileand then execute the file as shown in listing note that python codes work on indentations each block of code is defined by the line indentation (or spacesany wrong space will result in the error which can be seen by uncommenting the line listing listing hello py hello pyprints "hello worldsave this file to any location :\>pythoncodes print("hello world" #following line will be error because of extra space in the beginning print("hello world with spaces is error"error listing run hello py python hello py hello world notesince this method stores the code which can be used latertherefore this method is used throughout the tutorial please read the comments in the listings to understand the codes completely variables variables are used to store some data as shown in listing heretwo variables and are defined in line and respectivewhich store the values and respectively then various operations are performed on those variables basics
4,351
listing variables #variableex pya and are the variables which stores and respectively = = following line will add value of with print( + following line will perform ( + )/ print(( + )/ following line will perform ( + )/ and then display the interger value only print(int(( + )/ ) built-in object types table shows the various built-in object types available in python various operations can be performed on these object depending on their types add operations can be performed on number-object-typeor collection of data ( username-password-emailcan be created using list-object-type etc all these object types are discussed in this section table built-in object types object type exmaple number " + string 'python''make your codelist "[ 'username''password''email']tuple "( 'username''password''email')dictionary "{'subject':python'subjectcode': }file "text=opern('python'' 'read()numbers python supports various number types integerfloat (decimal numbers)octalhexadecimal and complex numbers as shown in listing the list also shows the method by which one format can be converted to another format listing number formats #numformat py #integer print(hex( )# xb float(decimal#print(oct( )errorcan' convert float to oct or hex integer can be convertedtherefore first convert float to int and then to hex/oct print(oct(int( ))# hexadecimal' xis used before number print( #add hex and float print( + # (continues on next page basics
4,352
(continued from previous page octal' ois used before number print command shows the integer value print( #to see octal form use `octprint(oct( )# + imagenary print( #( + jprint(abs( )# round above value upto decimal =round(abs( ), print( # string string can be very useful for displaying some output messages on the screen as shown listing here messages are displayed on screen (using 'inputcommandto get inputs from user and finally output is shown using % placeholder (see line for better understand of %slisting strings #strex py firstname "meher#firstname is variable of string type print(firstnamemeher fullname "meher krishna patelprint(fullnamemeher krishna patel #input is used to take input from user score input("enter the score "#enter some value score input("enter the score "#enter some value totalstring score score add score and score messagestring "total score is % #in below printtotalstring will be assinge to % of messagestring print(messagestring totalstring (undesired result #score and score are saved as string above #first we need to convert these into integers as below totalint int(score int(score )add score and score messagestring "total score is % print(messagestring totalint #change the input as integer immediately score int(input("enter the score ")#enter some value score int(input("enter the score ")#enter some value total score score add score and score messagestring "score (% score [% % print(messagestring (score score total)#score ( score [ list variables can store only one datawhereas list can be used to store collection of data of different types list contains items separated by commasand enclosed within the square brackets listing defines list along with access to it' elements basics
4,353
listing list #listex py [ "as it is""abc" + jindex start with location of number is ' in the list print( [ ] print( [ ]abc #replace 'abcwith 'xyza[ ]='xyzprint( [ ]xyz add at the end of list append( print( [ 'as it is''abc'( + ) tuple tuple is similar to the list tuple consists of values separated by commas as shown in listing tuple can be considered as 'read-onlylist because it' values and size can not be changed after defining it listing tuple #tupleex py "as it is""abc" + #some times (brackets are used to define tuple as shown below # ( "as it is""abc" + index start with location of number is ' in the list print( [ ] print( [ ]abc ##following lines will give error ##as value can be changed in tuple # [ ]='xyzerror ##as size of the tuple can not be changed append( error dictionary dictionary can be seen as unordered list with key-value pairs in the other workssince list' elements are ordered therefore it' elements can be access through index as shown in listing on the other handlocation of the elements of the dictionary get changed after defining ittherefore key-value pairs are requiredand the values can be accessed using keys as shown in listing listing dictionary #dictex py mydict {define new dictionary mydict[ "one is called key"oneis called value mydict[' '"alphabet print(mydict{ 'one'' ''alphabet'(continues on next page basics
4,354
(continued from previous page print(mydict items()dict_items([( 'one')(' ''alphabet')]print(mydict keys()dict_keys([ ' ']print(mydict values()dict_values(['one''alphabet'] print(mydict[ ]#one print(mydict[' ']alphabet add key-value while creating the dictionary subjectdict {'py''python''np''numpy''sp':'scipy'print(subjectdict{'py''python''sp''scipy''np''numpy' number conversion following are the patterns to convert the numbers in different formats direct conversion decimal to binary conversion with places print('{: }format( ) if ' bis used instead of ' 'then initial will not be displayed print('{: }format( ) decimal to hex conversion with places print('{: }format( ) binary to hexadecimal with places print('{: }format( ) zfill {:bbinary print("{: }format( zfill( ) number total places print("{: }format(xzfill( ) number xtotal places {:xhexadecimal print("{: }format(xzfill( ) number xtotal places {:ooctal print("{: }format(xzfill( ) number xtotal places {:ddecimal print("{: }format(xzfill( )number xtotal places (continues on next page number conversion
4,355
(continued from previous page {:ddecimal print("{: }format(xzfill( ) number xtotal places {:ddecimal print("{: }format(xzfill( ) number xtotal places control structure in this sectionvarious simple python codes are shown to explain the control structures available in python if-else 'if-elsestatements are used to define different actions for different conditions symbols for such conditions are given in table which can be used as shown in listing three examples are shown in this section for three types of statements ifif-else and if-elif-else table symbols for conditions condition symbol equal =not equal !greater smaller greater or equal >smaller or equal < if statement in this sectiononly if statement is used to check the even and odd number listing checks whether the number stored in variable 'xis even or not listing if statement #ifex py brackets are not necessary (used for clarity of the codeif ( % = )sign gives the value of the remainder % #if above condition is trueonly then following line will execute print('number is even ' #this line will execute always as it is not inside 'ifprint('bye bye' ''number is even bye bye '' ''if you put then output will be(continues on next page control structure
4,356
(continued from previous page bye bye number is even will not be printed as 'ifcondition is not satisfied ''explanation listing an if statement is made up of the 'ifkeywordfollowed by the condition and colon (:at the endas shown in line alsothe line is indented which means it will execute only if the condition in line is satisfied (see listing for better understanding of indentationlast print statement has no indentationtherefore it is not the part of the 'ifstatement and will execute all the time you can check it by changing the value of 'xto in line three quotes (in line and are used to comment more than one lines in the codee 'results here 'is used at the end of the code (see line - which contain the results of the code warningnote thatthe comments inside the 'is known as 'docstrings'which are displayed when help command is used thereforedo not use it for multiline comments it is better to use at each line multiple if statements listing checks the even and odd numbers using 'ifstatements since there are two conditions (even and odd)therefore two 'ifstatements are used to check the conditions as shown in listing finally output is shown as the comments at the end of the code listing multiple if statements #ifonly pyuses multiple if to check even and odd nubmer "inputcommand takes input as string int is used for type conversion =int(input('enter the number:\ ')#\ is used for tab in the output is used to calculate remainder if % == print ("number is even"if % != print ("number is odd" ''output- st runenter the numbernumber is even output- nd runenter the numbernumber is odd '' explanation listing this code demonstrate that one can use multiple 'ifconditions in codes in this codevalue of 'xis taken from using line in the code 'intis used in this line because 'inputcommand takes the value as string and it should be changed to integer value for mathematical operations on it if-else as we know that number can not be even and odd at the same time in such cases we can use 'if-elsestatement control structure
4,357
code in listing can be written using if-else statement as show in listing listing if-else statement ifelse pyuse if-else to check even and odd nubmer "inputcommand takes input as string xint(input('enter the number:\ ') is used to calculate remainder if % == print("number is even"elseprint("number is odd" ''output- st runenter the numbernumber is even output- nd runenter the numbernumber is odd '' explanation listing line takes the input from the user after that remainder is checked in line if condition is true remainder is zerothen line will be executedotherwise print command inside 'elsestatement (line will be executed if-elif-else in previous casethere were two contions which are implemented using if-else statement if there are more than two conditions then 'elifblock can be used as shown in next example further'if-elif-elseblock can contain any number of 'elifblocks between one 'ifand one 'elseblock listing checks whether the number is divisible by and using nested 'if-elsestatement listing if-elif-else statement #elif pychecks divisibility with and "int(input())command takes input as number =int(input('enter the number:\ ') is used to calculate remainder if % == #check divisibility with if % == if % = then check this line print("number is divisible by and "elseprint("number is divisible by only"print(" % " % elif % == #check this if % is not zero print("number is divisible by only"elseprint("number is not divisible by and "print(" % " % print(" % " % print("thank you" ''(continues on next page control structure
4,358
(continued from previous page output enter the number number is divisible by and thank you output enter the number number is divisible by only % thank you output enter the number number is not divisible by and % % thank you output enter the number number is divisible by only thank you ''explanation listing let' discuss the indentation first first look at the indentation at lines ' and ' since line ' is shifted by one indentation after line ' 'therefore it belongs to line ' 'which represents that pythoninterpreter will go to line ' only if line ' is true similarlyprint statements at line ' and ' are indented with respect to line ' 'therefore both the print statement will be executed when pythoninterpreter reaches to 'elsecondition now we will see the output for ' = for ' = ''ifstatement is satisfied at line ' 'therefore python-interpreter will go to line ' 'where the divisibility of the number is checked with number ' the number is divisible by ' alsohence corresponding print statement is executed as shown in line ' after thispython-interpreter will exit from the 'if-elsestatements and reached to line ' and output at line ' will be printed lets consider the input ' = in this case number is not divisible by ' and ' therefore pythoninterpreter will reached to line ' since lines ' '' and ' are indented with respect to line ' 'hence all the three line will be printed as shown in line ' - finallypython-interpreter will reach to line ' and print this line also lastlyuse as the input number since it is not divided by it will go to elif statement and corresponding print statement will be executed since there are three conditions in this example therefore 'elifstatement is used remember that 'if-elsecan contain only one 'ifand one 'elsestatement but there is no such restriction of 'elifstatement henceif there higher number of conditionsthen we can increase the number of 'elifstatement listing can be written as listing and listing as well here 'orand 'andkeywords are used to verify the conditions the 'andkeyword considers the statement as trueif and only ifall the conditions are true in the statementwhereas 'orkeyword considers the statement as trueif any of the conditions are true in the statement listing 'andlogic #andlogic pycheck divisibility with and =int(input('enter the number:\ ') if % == and % == #check divisibility with both and print("number is divisible by and "(continues on next page control structure
4,359
(continued from previous page elif % == #check this if % is not zero print("number is divisible by only"elif % == #check this if % is not zero print("number is divisible by only"elseprint("number is not divisible by and "print(" % " % print(" % " % print("thank you"listing 'andand 'orlogic #orlogic pycheck divisibility with and =int(input('enter the number:\ ') is used to calculate remainder if % == or % == #check divisibility with or if % == and % == #check if divided by both and print("number is divisible by and "elif % == #check this if % is not zero print("number is divisible by only"elif % == #check this if % is not zero print("number is divisible by only"elseprint("number is not divisible by and "print(" % " % print(" % " % print("thank you"while loop 'whileloop is used for recursive actionand the loop repeat itself until certain condition is satisfied listing uses 'whileloop to print numbers to for printing numbers upto value of initial number should be increased by at each iterationas shown in line listing while loop #whileexample pyprint numbers upto = #initial value of number print("numbers upto "while < print(nend=")#end="to stop row change after print = + print("\ncode ended at % ''outputnumbers upto code ended at '' explanation listing in the codeline ' sets the initial value of the number ' = line ' indicates that 'whileloop will be executed until 'nis less than next two lines line ' and ' 'are indented with respect to line ' hence these line will be executed if and only if the condition at line ' is satisfied since the value of 'nis one therefore while loop be executed firstnumber is printed by line ' ' control structure
4,360
then value of 'nis incremented by ' = 'nis still less than therefore loop will be executed again in this iteration value of 'nwill become which is still less than in the same mannerloop will continue to increase the value of 'nuntil ' = when ' = 'then loop condition at line ' will not be satisfied and loop will not be executed this time at this point python-interpreter will reach to line ' 'where it will print the value stored in variable 'ni as shown in line ' alsolook at 'printcommands at lines ' and ' at line ' '"end 'is placed at the endwhich results in no line change while printing outputs as shown at line ' at line ' ''\nis used to change the lineotherwise this print output will be continued with output of line ' for loop repetitive structure can also be implemented using 'forloop for loop requires the keyword in and some sequence for execution lets discuss the range command to generate sequencesthen we will look at 'forloop some outputs of 'rangecommands are shown in listing listing range command range( [ range( , [ range( [ range( - [ explanation listing from the outputs of 'rangecommands in the listingit is clear that it generates sequences of integers python indexing starts from zerotherefore command 'range( )at line ' generates five numbers ranging from ' to ' at line ' 'two arguments are given in 'rangecommands ' and ' note that output for this at line ' starts from ' and ends at ' last number is not included by python in the output list at line ' and ' 'three arguments are provided to 'rangefunction in these casesthird argument is the increment value line ' indicates that the number should start from ' and stop at number ' with decrement of ' at each step note that last value ' is not included in the output again similarlyoutput of line ' does not include ' listing prints numbers from ' to ' in forward and reverse direction using range command listing for loop #forexample pyprint numbers - print("numbers in forward order"for in range( )print( + end="print("\nfinal value of is" print ("\nnumbers in reverse order"for in range( - )print(jend=")print("\nfinal value of is" ''outputs(continues on next page control structure
4,361
(continued from previous page numbers in forward order final value of is numbers in reverse order final value of is '' fruits=["apple""banana""orange"print("list of fruits are shown below:"for in fruitsprint( ''list of fruits are shown belowapple banana orange ''explanation listing at line ' 'command 'range( )generates the five numberstherefore loop repeats itself five times sinceoutput of range starts from ' 'therefore 'iis incremented by one before printing line ' shows that the variable 'istores only one value at timeand the last stored value is ' last value of 'range( )at line ' 'variable 'jis used instead of 'iand range command generates the number from to again but in reverse order note that number of iteration in for loop depends on the number of elements length of the 'rangecommand' output and independent of the element values line ' prints the current value of 'jat each iteration finallyline ' prints the last value stores in variable 'ji ' = 'which is the last value generated by command 'range( , ,- )code in line ' shows thathow the values are assigned to the iterating variable 'ifrom list the list 'fruitscontains three itemstherefore loop will execute three timesand different elements of the list are assigned to variable 'iat each iteration apple is assign firstthen banana and lastly orange will be assigned function some logics may be used frequently in the codewhich can be written in the form of functions thenthe functions can be called whenever requiredinstead of rewriting the logic again and again in listing the function 'addtwonumadds two numbers listing function #funcex py def addtwonum(ab)sum + return(sum result addtwonum( , print("sum of numbers is % result ''sum of numbers is ''explanation listing function
4,362
in pythonfunction is defined using keyword 'defline defines the function with name 'addtwonumwhich takes two parameter and line add the values of 'aand 'band stores the result in variable 'sumfinally line returns the value to function call which is done at line in line function 'addtwonumis called with two values ' and ' which are assigned to variable 'aan 'brespectively in line alsofunction returns the 'sumvariable from line which is stored in variable 'resultsin line (as line called the functionfinallyline prints the result in listing the function is defined with some default valueswhich means if user does not provide all the argumentsvaluesthen default value will be used for the execution of the function listing function with default arguments #funcex pydefault argument can be defined only after non-default argument addtwonum(num = num )is wrong must have some defined value def addtwonum(num num = )return(num +num result addtwonum( print("result =% result result addtwonum( , print("result =% result ''result = result = ''explanation listing function of this listing is same as listing only difference is that the line contains default value for num 'num default value indicates thatif function is called without giving the second value then it will be set to by defaultas shown in line line pass only one value therefore num will be assign whereas num will be assigned default value rest of the the working is same as listing notethere are various other important python features classesdecorators and descriptors etc which are not explained here as we are not going to use these in the coding furtherusing these features we can make code more efficient and reusable along with less error-prone numpyscipy and matplotlib in this sectionwe will use various python librariesi numpyscipy and matplotlibwhich are very useful for scientific computation with numpy librarywe can define array and matrices easily alsoit contains various useful mathematical function random number generator 'randand 'randnetc matplotlib is used for plotting the data in various format some of the function of these libraries are shown in this section furtherscipy library can be used for more advance features complementary error function (erfcand lu factorization etc listing generates the sine wave using numpy librarywhereas the matplotlib library is used for plotting the data listing sine wave using numpy and matplotlibfig numpymatplot py import numpy as np import matplotlib pyplot as plt (continues on next page numpyscipy and matplotlib
4,363
(continued from previous page np linspacedevide line from to *pi into equidistant points np linspace( *np pi sinx np sin(xfind sin(xfor above points plt plot( ,sinxplot (xsin( )plt xlabel("time"label for axis plt ylabel("amplitude"label for axis plt title('sine wave'title plt xlim([ *np pi] -axis display range plt ylim([- ] -axis display range plt show(to show the plot on the screen explanation listing first line import numpy library to the code alsoit is imported with shortname 'np'which is used in line as 'np linspaceif line is written as 'import numpy'then line should be written as 'numpy linspacefurtherthird line import 'pyplotfunction of 'matplotliblibrary as plt rest of the lines are explained as comments in the listing fig sine wave using numpy and matplotliblisting arrays arrays can be created using 'arangeand 'arraycommands as shown below arange one dimensional array can be created using 'arangeoption as shown below numpyscipy and matplotlib
4,364
listing arange arangeex py import numpy as np =np arange( , last element is not included in result print( [ print( shape( , total entries =np arange( , , print to with the spacing of print( [ print( shape( , total entries =np arange( - last element is not included in result self print( [ array multidimensional array can not be created by 'arangealso'arangecan only generate sequences and can not take user-defined data these two problems can be solved by using 'arrayoption as shown in listing listing array arrayex py import numpy as np anp array([ ]print( [ print(np shape( )( , =np array([ ][ ][ ] can be written as follow as wellbut above is more readable =np array([[ ],[ ]]print(np shape( )#( row and column row of array can have different number of elements =np array([[np arange( , )],[np arange( )]]print( ''[[array([ ])[array([ ])]'' matrix similar to arraywe can define matrix using 'matfunction of numpy library as shown in listing alsolu factorization of the matrix is shown in listing using scipy library there are differences in results of mathematical operations on the matrices defined by 'arrayand 'mat'as shown in the listing 'dotfunction is required for matrix multiplication of arraywhereas '*sign performs matrix multiplication for 'matfunction listing matrix matrixex py import numpy as np (continues on next page numpyscipy and matplotlib
4,365
(continued from previous page from scipy linalg import lu anp mat(' 'define matrix print(np shape( )( at np transpose(atranspose of matrix 'aprint(np shape(at)( eye(nis used for (nxnidentity matrix = *np eye( identity matrix print(np shape( )( * print(np shape( )( llu(aprint(llisting lu factorization of matrix scipyex py import numpy as np import lu factorization command from scipy linalg from scipy linalg import lu #define matrix 'aanp mat(' 'define matrix perform lu factorization and save the values in pl and as it returns values [plu]lu( print values of pl and print(" "pprint(" "lprint(" "np round( , ) print("type of "type( )#type of pndarray * * will give wrong results because types are not matrix (but ndarrayas shown above dot(ldot(uprint(" " #for * * we need to change the ndarray to matrix type as belowprint("type of after np mat"type(np mat( )) np mat( )*np mat( )*np mat(uprint(" " ''outputs [ ] [ - ] [ (continues on next page numpyscipy and matplotlib
4,366
(continued from previous page - ] type of [ ] type of after np mat [ ]'' good practices as oppose to other programming languagespython provides various ways to iterate over the listwhich are shown in this section avoid range command multiply to all elements of arr arr [ bad practice for in range(len(arr))print( *arr[ ] good practices for in arrprint( * print in reverse order for in reversed(arr)print( * enumerate in previous casewe do not have the access over index use 'enumerateto get access to index as wellmultiply to all elements of arr arr [ for ia in enumerate(arr)print( ':' * good practices
4,367
loop in sorted order multiply to all elements of arrbut in sorted order arr [ for in sorted(arr)print( * in reversed sorted order for in sorted(arrreverse=true)print( * loop over keys dc 'toy': 'play': 'games': print keys of dictionaries for in dcprint(dloop over keys and values dc 'toy': 'play': 'games': print keysvalues of dictionaries for kv in dc items()print(kvtoy play games create dictionaries from lists ['toy''game''tiger' ['toys''games''tigers'#create dict dc dict(zip(kv)print(dc{'game''games''tiger''tigers''toy''toys' dict(enumerate( )print( { 'toys' 'games' 'tigers'looping and modifying the list simultaneously we need to make copy of the list for such operations as shown belowloopupdate py animals ['tiger''cat''dog'am animals copy((continues on next page good practices
4,368
(continued from previous pagebelow line will go in infinite loop for in animalsfor in amif len( animals append(aprint(animalsor we can use 'animals[:]in the for loopinstead of 'animalas shown belowloopupdate py animals ['tiger''cat''dog'for in animals[:]if len( animals append(aprint(animalscheck items in the list the 'inkeyword can be used with 'ifstatementto check the value in the listloopupdate py def testnumber(num)if num in [ ]print("thanks"elseprint("number is not or "testnumber( testnumber( unpacking any iterable listtuple or set can be unpacked using assignment operator as belowx [ abc student ["tom" name*marksage student marks [ ( "two" ("five""six""seven") * (*cdy 'seven(continues on next page good practices
4,369
(continued from previous pagec ['five''six'update variables xyz yzx print(xyz object oriented programming object oriented programming (oopincreases the re-usability of the code alsothe codes become more manageable than non-oop methods butit takes proper planningand therefore longer timeto write the codes using oop method in this we will learn various terms used in oop along with their usages with examples class and object 'classis user defined template which contains variablesconstants and functions etc whereas an 'objectis the instance (or variableof the class in simple wordsa class contains the structure of the codewhereas the object of the class uses that structure for performing various tasksas shown in this section create class and object class is created using keyword 'classas shown in line of listing where the class 'jungleis created as ruleclass name is started with uppercase letterwhereas function name is started with lowercase letter currentlythis class does not have any structuretherefore keyword 'passis used at line thenat line an object of class 'jis createdwhose value is printed at line this print statement prints the class-name of this object along with it' location in the memory (see comments at line listing create class and object #ex py #class declaration class junglepass create object of class jungle jungle(print( add function to class nowwe will add one function 'welcomemessagein the class the functions inside the class are known as 'methodsthe functions inside the class are the normal functions (nothing special about them)as we can see at lines - to use the variables and functions etc outside the classwe need to create the object of the class firstas shown in line where object 'jis created when we create teh object of classthen all the functions and variables of that class is attached to the object and can be used by that object object oriented programming
4,370
the object 'jcan now use the function 'welcomemessageusing operatoras shown in line also'selfis used at line which is discussed in section section listing add function to class #ex py #class declaration class jungledef welcomemessage(self)print("welcome to the jungle" create object of class jungle jungle( welcomemessage(welcome to the jungle constructor the '__init__method is used to define and initialize the class variables this ''__init__method is known as constructor and the variables are known as attributes note thatthe self keyword is used in the 'init function(line along with the name of the variables (line further all the functionsshould have first parameter as 'selfinside the class although we can replace the word 'selfwith any other wordbut it is good practice to use the word 'selfas convention explanation listing wheneverthe object of class is create then all the attributes and methods of that class are attached to itand the constructor '__init__method is executed automatically herethe constructor contains one variable 'visitorname(line and one input parameter 'name(line whose value is initialized with 'unknownthereforewhen the object 'jis created at line the value 'meherwill be assigned to parameter 'nameand finally saved in 'visitornameas constructor is executed as soon as the object created furtherif we create the object without providing the name ' jungle()'then default value 'unknownwill be saved in attribute 'visitornamelastlythe method 'welcomemessageis slightly updatedwhich is now printing the name of the 'visitor(line as well object oriented programming
4,371
listing constructor with default values #ex py #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname create object of class jungle jungle("meher" welcomemessage(hello meherwelcome to the jungle if no name is passedthe default value unknown will be used jungle( welcomemessage(hello unknownwelcome to the jungle define 'mainfunction the above code can be written in 'mainfunction (lines - using standard-boiler-plate (lines - )which makes the code more readableas shown in listing this boiler-plate tells the python-interpretor that the 'mainis the starting point of the code listing main function #ex py #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname def main()create object of class jungle jungle("meher" welcomemessage(hello meherwelcome to the jungle if no name is passedthe default value unknown will be used jungle( welcomemessage(hello unknownwelcome to the jungle standard boilerplate to set 'mainas starting function if __name__=='__main__'main( keep classes in separate file to make code more manageablewe can save the class-code ( class jungleand application-files ( mainin separate file for thissave the class code in 'junglebook pyfileas shown in listing whereas save the 'main()in 'main pyfile as shown in listing sinceclass is in different file nowtherefore we need to import the class to 'main py fileusing keyword 'importas shown in line of listing object oriented programming
4,372
warningherewe kept the class and main function in separate files it is not good idea keep these small related-codes separate like this we will learn to manage the code as we will write some big codes in the tutorial listing save classes in separate file #junglebook py #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitornamelisting import class to main py #main py #import class 'junglefrom junglebook py from junglebook import jungle def main()create object of class jungle jungle("meher" welcomemessage(hello meherwelcome to the jungle if no name is passedthe default value unknown will be used jungle( welcomemessage(hello unknownwelcome to the jungle standard boilerplate to set 'mainas starting function if __name__=='__main__'main(inheritance supposewe want to write class 'ratejunglein which visitor can provide 'ratingbased on their visitingexperience if we write the class from the startingthen we need define attribute 'visitornameagainwhich will make the code repetitive and unorganizableas the visitor entry will be at multiple places and such code is more prone to error with the help of inheritancewe can avoid such duplication as shown in listing where class jungle is inherited at line by the class 'ratejunglenowwhen the object 'rof class 'ratejungleis created at line of listing then this object 'rwill have the access to 'visitornameas well (which is in the parent classlisting inheritance #junglebook py #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)(continues on next page object oriented programming
4,373
(continued from previous page print("hello % welcome to the jungleself visitorname class ratejungle(jungle)def __init__(selfnamefeedback)feedback ( - is the best self feedback feedback public attribute inheriting the constructor of the class super(__init__(name using parent class attribute visitorname def printrating(self)print("thanks % for your feedbackself visitornamelisting usage of parent-class method and attributes in childclass #main py #import class 'jungleand 'ratejunglefrom junglebook py from junglebook import jungleratejungle def main() ratejungle("meher" printrating(thanks meher for your feedback calling parent class method welcomemessage(hello meherwelcome to the jungle standard boilerplate to set 'mainas starting function if __name__=='__main__'main(polymorphism in oopwe can use same name for methods and attributes in different classesthe methods or attributes are invoked based on the object typee in listing the method 'scarysoundis used for class 'animaland 'birdat lines and respectively then object of these classes are created at line - of listing finallymethod 'scarysoundis invoked at lines - here line is the object of class animaltherefore method of that class is invoked and corresponding message is printed similarlyline invokes the 'scarymethodof class bird and corresponding line is printed listing polymorphism example with function 'move #scarysound py class animaldef scarysound(self)print("animals are running away due to scary sound " class birddef scarysound(self)print("birds are flying away due to scary sound " scaryscound is not defined for insect class insectpass object oriented programming
4,374
listing polymorphismmove function works in different ways for different class-objects #main py #import class 'animalbirdfrom scarysound py from scarysound import animalbird def main()create objects of animal and bird class animal( bird( polymorphism scarysound(animals are running away due to scary sound scarysound(birds are flying away due to scary sound standard boilerplate to set 'mainas starting function if __name__=='__main__'main(abstract class and method abstract classes are the classes which contains one or more abstract methodand abstract methods are the methods which does not contain any implemetationbut the child-class need to implement these methods otherwise error will be reported in this waywe can force the child-class to implement certain methods in it we can defineabstract classes and abstract method using keyword 'abcmetaand 'abstractmethodrespectivelyas shown in lines and respectively of listing since'scarysoundis defined as abstractmethod at line - therefore it is compulsory to implement it in all the subclasses notelook at the class 'insectin listing where 'scarysoundwas not defined but code was running correctlybut now the 'scarysoundis abstractmethodtherefore it is compulsory to implement itas done in line of listing listing abstract class and method #junglebook py from abc import abcmetaabstractmethod #abstract class and abstract method declaration class jungle(metaclass=abcmeta)#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname abstract method is compulsory to defined in child-class @abstractmethod def scarysound(self)pass object oriented programming
4,375
listing abstract methods are compulsory to define in childclass #scarysound py from junglebook import jungle class animal(jungle)def scarysound(self)print("animals are running away due to scary sound " class bird(jungle)def scarysound(self)print("birds are flying away due to scary sound " since jungle is defined as metaclass therefore all the abstract methods are compulsory be defined in child class class insect(jungle)def scarysound(self)print("insects do not care about scary sound "listing main function #main py #import class 'animalbirdfrom scarysound py from scarysound import animalbirdinsect def main()create objects of animal and bird class animal( bird( insect( polymorphism scarysound(animals are running away due to scary sound scarysound(birds are flying away due to scary sound scarysound(insects do not care about scary sound standard boilerplate to set 'mainas starting function if __name__=='__main__'main(public and private attribute there is not concept of private attribute in python all the attributes and methods are accessible to end users but there is convention used in python programming if variable or method name starts with ' 'then users should not directly access to itthere must be some methods provided by the class-author to access that variable or method similarly'__is designed for renaming the attribute with class name the attribute is automatically renamed as '_classname__attributenamethis is used to avoid conflict in the attribute names in different classesand is useful at the time of inheritancewhen parent and child class has same attribute name listing and listing show the example of attributes along with the methods to access them please read the comments to understand these codes listing public and private attribute #junglebook py (continues on next page object oriented programming
4,376
(continued from previous page #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname class ratejungledef __init__(selffeedback)feedback ( - is the best self feedback feedback public attribute public attribute with single underscore sign single signifies that author does not want to acecess it directly self _staffrating self __jungleguiderating private attribute self updatestaffrating(update staff rating based on feedback self updateguiderating(update guide rating based on feedback def printrating(self)print("feedback % \tguide rating% \tstaff rating% (self feedbackself __jungleguideratingself _staffrating) def updatestaffrating(self)""update staff rating based on visitor feedback""if self feedback self _staffrating + elseself _staffrating - def updateguiderating(self)""update guide rating based on visitor feedback""if self feedback self __jungleguiderating + elseself __jungleguiderating - listing accessing public and private attributes #main py import class 'jungleand 'ratejunglefrom junglebook py from junglebook import jungleratejungle def main()#create object of class jungle jungle("meher" welcomemessage(hello meherwelcome to the jungle ratejungle( printrating(feedback guide rating staff rating _staffrating can be accessed "directly"but not good practice use the method which is provided by the author below is the bad practice _staffrating directly change the _staffrating print("staff rating " _staffratingstaff rating (continues on next page object oriented programming
4,377
(continued from previous page #access to private attribute is not allowed #uncomment following line to see error print("jungle guide rating " __jungleguiderating #private attribute can still be accessed as below#objectname _classname __attributename print ("guide rating " _ratejungle__jungleguideratingguide rating standard boilerplate to set 'mainas starting function if __name__=='__main__'main(class attribute class attribute is the variable of the class (not of methodas shown in line of listing this attribute can be available to all the classes without any inheritance at line the class test (line is using the class-attribute 'sum_of_feedbackof class jungle (line note thatwe need to use the class name to access the class attribute jungle sum_of_feedback (lines and listing class attributes and it' access #junglebook py #class declaration class jungleclass attribute use __sum_of_feedback to hide it from the child class sum_of_feedback #constructor with default values def __init__(selfname="unknown")self _visitorname name please do not access directly def welcomemessage(self)print("hello % welcome to the jungleself visitorname def averagefeedback(self)#average feedback is hided for the the child class self __avg_feedback jungle sum_of_feedback/ratejungle total_num_feedback print("average feedback "self __avg_feedback class ratejungle(jungle)class attribute total_num_feedback def __init__(selfnamefeedback)feedback ( - is the best self feedback feedback public attribute add new feedback value to sum_of_feedback jungle sum_of_feedback +self feedback increase total number of feedback by ratejungle total_num_feedback + inheriting the constructor of the class super(__init__(name using parent class attribute visitorname (continues on next page object oriented programming
4,378
(continued from previous page def printrating(self)print("thanks % for your feedbackself _visitorname class testdef __init__(self)inheritance is not required for accessing class attribute print("sum_of_feedback (jungle class attribute"jungle sum_of_feedbackprint("total_num_feedback (ratejungle class attribute"ratejungle total_num_feedbacklisting main program #main py #import class 'jungle''ratejungleand 'testfrom junglebook py from junglebook import jungleratejungletest def main() ratejungle("meher" ratejungle("krishna" averagefeedback(average feedback test class is using other class attributes without inheritance test(''sum_of_feedback (jungle class attribute total_num_feedback (ratejungle class attribute '' standard boilerplate to set 'mainas starting function if __name__=='__main__'main(special methods there are some special methodwhich are invoked under certain cases __init__ method is invokedwhen an object of the instance is created in this sectionwe will see some more special methods __init__ and __del__ the __init__ method is invoked when object is createdwhereas __del__ is always invoked at the end of the codee we invoke the 'delat line of listing which deletes object ' and remaining objects are printed by line butafter line there is no further statementtherefore the 'delcommand will automatically executedand results at lines - will be displayed the 'delcommand is also known as 'destructorlisting __init__ and __del__ function delex py class studenttotalstudent def __init__(selfname)self name name student totalstudent + print("total students (init"self totalstudent (continues on next page object oriented programming
4,379
(continued from previous page def __del__(self)student totalstudent - print("total students (del"self totalstudent def main() student("meher"total students (init student("krishna"total students (init student("patel"total students (init #delete object del total students (del print( nameerror because object is deleted print( namekrishna print( namepatel #since there is no further statementstherefore #'delwill be executed for all the objects and #following results will be displayed total students (deltotal students (del standard boilerplate to set 'mainas starting function if __name__=='__main__'main( __str__ when __str__ is defined in the classthen 'printstatement for object ( print(jat line of listing )will execute the __str__ statementinstead of printing the address of objectas happened in listing this statement is very useful for providing the useful information about the class using print statement listing __str__ method is executed when 'printstatement is used for object #strex py #class declaration class jungledef __str__(self)return("it is an object of class jungle" def main()create object of class jungle jungle(print(jit is an object of class jungle standard boilerplate to set 'mainas starting function if __name__=='__main__'main( __call__ the __call__ method is executedwhen object is used as functionas shown in line of listing where object 'dis used as function ( object oriented programming
4,380
listing __call__ method is executed when object is used as function callex py #class declaration class calculatepricediscount in def __init__(selfdiscount)self discount discount def __call__(selfprice)discountprice price price*self discount/ return (pricediscountprice def main()create object of class calculateprice with discount calculateprice( using object as function ( since two variables are return by call fuctiontherefore unpack the return values in two variables pricepriceafterdiscount ( print("original price% price after discount % (pricepriceafterdiscount) #or use below methodif you do not want to unpack the return values getprices ( print("original price%sprice after discount % (getprices[ ]getprices[ ]) standard boilerplate to set 'mainas starting function if __name__=='__main__'main( __dict__ and __doc__ __dict__ is used to get the useful information about the class (line )whereas __doc__ prints the docstring of the class (line listing __dict__ and __doc__ #dictex py #class declaration class jungle""list of animal and pet information animal string ispet string ""def __init__(selfanimal="elephant"ispet="yes")self animal animal self ispet ispet def main()create object of class jungle jungle(print( __dict__{'ispet''yes''animal''elephant' jungle("lion""no"(continues on next page object oriented programming
4,381
(continued from previous page print( __dict__{'ispet''no''animal''lion' print(jungle __dict__""{'__doc__''__doc__'list of animal and pet information \ animal string\ ispet string\ ''__weakref__''__module__''__main__''__dict__''__init__'"" print(jungle __doc__"""list of animal and pet information animal string ispet string "" standard boilerplate to set 'mainas starting function if __name__=='__main__'main( __setattr__ and __getattr__ method __setattr__ is executedwhenever we set the value of an attribute __setattr__ can be useful for validating the input-types before assigning them to attributes as shown in line of listing please read the comments of listing for better understanding similarly__getattr__ is invoked whenever we try to access the value of an attributewhich is not in the dictionary listing __setattr__ and __getattr__ setattr py class studentiddef __init__(selfidnameage " ")self id id self firstname name self age age all the init parameters need to be specified in 'setattrdef __setattr__(selfnamevalue)if(name ="id")setting id if isinstance(valueintand value self __dict__["id"value elseprint("id must be positive integer"raise typeerror("id must be positive integer"elif (name ="firstname")setting firstname self __dict__["firstname"value elsesetting age self __dict__[namevalue getattr is executedwhen attribute is not found in dictionary def __getattr__(selfname)raise attributeerror("attribute does not exist" def main() studentid( "meher"print( ids firstnames age meher #uncomment below line to see the "typeerrorgenerated by 'setattr(continues on next page object oriented programming
4,382
(continued from previous page studentid(- "krishna" ""traceback (most recent call last)raise typeerror("id must be positive integer""" studentid( "krishna" print( ids firstnames age krishna #uncomment below line to see the "attributeerrorgenerated by 'getattrprint( lastnamefollowing message will be displayed ""traceback (most recent call last)attributeerrorattribute does not exist ""standard boilerplate to set 'mainas starting function if __name__=='__main__'main( conclusion in this we learn various features of python along with object oriented programming alsowe learn some of the good coding practices in python furtherwe saw that there is no concept of private attributes in python lastlywe discuss various special methods available in python which can enhance the debugging and error checking capability of the code we will see all these features in details in the subsequent conclusion
4,383
virtual environmentpackage and distribution anadconda virtual environment installation go to anaconda webpage and download the latest python version for your os ( linux or windowswindowsdouble click the downloaded exe file to install the anaconda during installationit will ask to include the anaconda in the environment variablepress "yesthere linuxdo the below for installation chmod (when askedpress yes to include the anaconda in the pathverify installation open terminal and run the 'pythoncommand it should show the install version of python python in the below result :\users\meherppython python |anacondainc (defaultmar : : exit(to exit from python shell creating virtual environment python applications will often use packages and modules that don' come as part of the standard library applications will sometimes need specific version of librarybecause the application may require that particular bug has been fixed or the application may be written using an obsolete version of the library' interface this means it may not be possible for one python installation to meet the requirements of every application if application needs version of particular module but application needs version then the requirements are in conflict and installing either version or will leave one application unable to run the solution for this problem is to create virtual environmenta self-contained directory tree that contains python installation for particular version of pythonplus number of additional packages creating virtual environment is very easy in anaconda as shown below(create env"conda create - python= xwhere is python versionconda create - myenv python= (continues on next page
4,384
(continued from previous pageproceed ([ ]/ ) downloading and extracting packages wincertstore- kb #####################################################################'-##### pip mb #####################################################################'-##### wheel kb #####################################################################'-##### certifi kb #####################################################################'-##### python mb #####################################################################'-##### setuptools kb #####################################################################'-##### preparing transactiondone verifying transactiondone executing transactiondone to activate this environmentuseactivate myenv to deactivate an active environmentusedeactivate for power-users using bashyou must source we need to activate this env to use it you can see the activate command in above result as well activate myenv (if activated successfullythen name of the env will be show as below (myenv)(myenvc:\users\meherp>deactivate note(see activate command in above resultsometimes below result are shown in different os/versionsource activate myenv conda activate myenv nowwe can install various libraries to this environment without affecting our original instillation (or other environments) the changes will remain within this environment only in the below result we can see that the 'wgetlibrary is not available in the current environment(myenvc:\users\meherp>python python |anacondainc (defaultaug : : [msc bit (amd )on win type "help""copyright""creditsor "licensefor more information import wget traceback (most recent call last)file ""line in importerrorno module named 'wgetexit(we can use 'conda installor 'pip installoption to install the libraries in the environment as shown below(myenvc:\users\meherp>pip install wget collecting wget (continues on next page anadconda virtual environment
4,385
(continued from previous pagedownloading da bcda ff cfe fb /wget- zip building wheels for collected packageswget running setup py bdist_wheel for wget done stored in directory'- :\users\meherp\appdata\local\pip\cache\wheels\ \ \ \ cea db fea ecb ef successfully built wget installing collected packageswget successfully installed wget- you are using pip version however version is available you should consider upgrading via the 'python - pip install --upgrade pipcommand 'nowwe can see that the 'wgetlibrary is installed in the environment(myenvc:\users\meherp>python python |anacondainc (defaultaug : : [msc bit (amd )on win type "help""copyright""creditsor "licensefor more information import wget exit(deactivate the environment (myenvc:\users\meherp>deactivate :\users\meherpnoteuse below based on the message which is shown while creating the environment source deactivate conda deactivate other commands below are some other useful command related to virtual environmentlist of environments (show the list of enviromentsconda env list conda environmentsbase :\users\meherp\appdata\local\continuum\anaconda audio :\users\meherp\appdata\local\continuum\anaconda \envs\audio caffe :\users\meherp\appdata\local\continuum\anaconda \envs\caffe myenv :\users\meherp\appdata\local\continuum\anaconda \envs\myenv tensorflow_env :\users\meherp\appdata\local\continuum\anaconda \envs\tensorflow_env wts :\users\meherp\appdata\local\continuum\anaconda \envs\wts install libraries using txt file let' create text file 'myenv txtat the desired location desktop with below content flask=django install the packages using this file as below note thatall the dependent libraries will be downloaded installed automatically django depends on 'pytzand 'sqlparselibrary anadconda virtual environment
4,386
(myenvc:\users\meherp>pip install - :\users\meherp\desktop\myenv txt installing collected packagesitsdangerousmarkupsafejinja clickwerkzeugflasksqlparsepytz'-django successfully installed jinja markupsafewerkzeugclick- djangoflask- '-itsdangerouspytz- sqlparsesee the list of installed libraries'freezecommand is used for it(myenvc:\users\meherp>pip freeze certifi=click== django=flask== itsdangerous=jinja =markupsafe=pytz== sqlparse=werkzeug=wget== wincertstore== export the list of install libraries to file( :\users\meherp\desktop\copymyenv txt is the saved location(myenvc:\users\meherp>pip freeze :\users\meherp\desktop\copymyenv txt 'copymyenv txtwill be created at desktop with below content certifi=click== django=flask== itsdangerous=jinja =markupsafe=pytz== sqlparse=werkzeug=wget== wincertstore== deactivate and remove the environment conda deactivate (delete the environmentconda remove --name myenv --all virtual environment using virtualenv and virtualenvw install virtualenv and virtualenvwrapper install virtualenv and virtualenvwrapper pip install virtualenv virtualenvwrapper virtual environment using virtualenv and virtualenvw
4,387
modify bashrc add below line at the end of bashrc file if virtual environment is installed in the anaconda environment replace /home/meherp/anaconda with correct installation location virtualenv and virtualenvwrapper export workon_home=$homevirtualenvs export virtualenvwrapper_python=/home/meherp/anaconda /bin/python source /home/meherp/anaconda /bin/virtualenvwrapper sh add below at the end of bashrc file if virtualenv environment is created outside the anaconda environment replace python with correct version python or python export workon_home=$homevirtualenvs source /usr/local/bin/virtualenvwrapper sh export virtualenvwrapper_python=/usr/bin/python create virtualenv test the installation by creating virtualenv and installing numpy to it source ~bashrc mkvirtualenv vtest - python pip install numpy activate the environmentworkon vtest deactivate the environment deactivate delete the environment rmvirtualenv vtest packages in this sectionwe will learn to create the 'packages'which are nothing but the collection of modules under the same name location of installed packages before creating our own packagelet' see the location of the installed packages the installed packages (using pip commandare saved in the folder 'lib/python /site-packages'as shown below(for environment 'pythondsp'pythondsp/lib/python /site-packages (without environment/home/anaconda /lib/python /site-packages apart from current working directorythe python look for the files in the folder 'site-packageswe will understand this in section the complete list of the directories can be seen using 'sys pathcommand packages
4,388
(pythondsppython import sys sys path '/home/pythondsp/lib/python /site-packages'create files in this sectionwe will write some python codesand then in next sectionwe will convert these python modules into package activate the environmentand create folder with any name 'bucketat desired location (pythondspmkdir - ~/desktop/bucket (pythondspcd ~/desktop/bucket now create two files inside the folder with following contentsbucket/my_calc py def sum num(xy)return ( +ydef diff num(xy)return ( -ybucket/my_work py from my_calc import sum numdiff num print("{ { { }format(xysum num(xy))print("{ { { }format(xydiff num(xy))nextcheck execute 'my_work pyto check the setupnotefirst 'import my_workwill import everything from the filetherefore 'printstatement will be executed but the second import will import the values from the 'cache(not from the file)therefore 'printstatements from the file will not be executed (pythondsppython my_work py alsocheck the below commands(pythondsppython from my_calc import sum num sum num( (continues on next page packages
4,389
(continued from previous pageimport my_work import my_work packages in this sectionwe will convert the python modules into the package notepackage name should be uniqueso that it will not collide with other package names create another folder inside the folder 'bucketwith any desired name 'wolfpack'and move the 'python filesinside it after running below commandswe will have following folder structure (after excluding the folder '__pycache__)notethe folder ( 'wolfpack'inside the 'root folder ( bucket)is called the 'packageand needs special settings to use it with root-folder bucketwolfpack my_calc py my_work py (pythondspmkdir wolfpack (pythondspmv my_work py my_calc py wolfpack nowrun the shell commands again as shown below note that the command at line is working finebut command at line is generating error listing import package and error (pythondsppython from wolfpack my_calc import sum num sum num( from wolfpack import my_work traceback (most recent call last)file ""line in file "/home/meher/desktop/bucket/wolfpack/my_work py"line in from my_calc import sum numdiff num modulenotfounderrorno module named 'my_calcnotethe error at line is 'no module named 'my_calc'as we are running the command from the 'root directory ( bucket)'therefore the line 'import my_calcin 'my_work pywill look for it in the root directory only (not inside the 'wolfpack'the error can be removed by modifying the code as belowin the below codewe used 'from my_calc import sum numdiff numthe 'dot operatortells python to look in the current directory ( wolfpack)not in the 'root directory packages
4,390
bucket/wolfpack/my_work py from my_calc import sum numdiff num print("{ { { }format(xysum num(xy))print("{ { { }format(xydiff num(xy))close the python terminal and open it again then execute the commands and it will work fine(pythondsppython from wolfpack import my_work warningnowthe folder 'wolfpackis 'packageand the files inside it can not be executed directlyas these files have 'dotoperators in the 'importstatement following error will be generated if we run the 'package-moduledirectly (pythondspcd wolfpack(pythondspls my_calc py my_work py (pythondsppython my_work py traceback (most recent call last)file "my_work py"line in from my_calc import sum numdiff num modulenotfounderrorno module named '__main__ my_calc'the files in the package module can be executed through root-folders ( bucketby importing the modules alsothe folder 'wolfpackcan be called as python-file in the codes 'import wolfpackwe will use following terms for the two foldersroot directory 'bucketpackage directory 'wolfpackglobally available package if we 'cut and pastethe package folder ( wolfpackinside the folder 'site-packages'then it will be available globally in the environmenti it can be imported into any project at any location notedo not cut and paste the folder now we will create the package in section and use 'setup pycommand to install the package __init__ file in listing we import the function 'sum numusing following command packages
4,391
from wolfpack my_calc import sum numcurrentlywe have only two files in the package therefore it' easy to import 'functionlike this butif we have files with folders in packagethen it will be difficult/inconvenient to remember the import-location of the 'methodsa better approach is to to use the '__init__ pyfile as shown belowfirst go to package folder and create an __init__ py with following contentwolfpack/__init__ py import functions from my_calc from my_calc import sum numdiff num nowwe can import the commands directly without knowing the file structurerun from root-folder 'bucketfrom wolfpack import sum numdiff num sum num( __all__ in __init__ file if we want to allow 'import *option for our packagethen we need to add the magic keyword '__all__in the __init__ py file wolfpack/__init__ py import sum num from my_calc from my_calc import sum num import 'my_calcand 'my_calcfor 'import *__all__ "sum num""my_calc""my_worknowuse the 'import *command in the python shell as below following items will be imported with commandmodule 'my_calcmodule 'my_workfunction 'sum numwarningin line of above codeonly 'sum numis imported if we do not include sum num in the '__all__ (line )'then '__all__will overwrite the line and 'sum numwill not be available and error (in below codesimilar to 'diff num( )will be shown for sum num (run from the root-folder 'bucket'(pythondsppython from wolfpack import my_work sum num( (continues on next page packages
4,392
(continued from previous page my_calc diff num( diff num( traceback (most recent call last)file ""line in nameerrorname 'diff numis not defined distribute the package in this sectionwe will convert our package to 'distributable package'which can be used by others as wellnotewe need to create the setup py file inside the root-folder 'bucketto generate the 'distributionsupposeif we have the following 'directory structurebucketdocumentation txt my_exec py my_file py my_file py readme txt setup py wolfpack __init__ py item py item py document the package here executable python file python file python file add tips here needs to create 'distributionpackage then our setup py file will be as followssetup py from distutils core import setup setup(name "wolf"choose any name version " "give version number py_modules ['my_file ''my_file ']python files packages ['wolfpack']add package here scripts ['my_exec py']executable since our project have only 'packagein ittherefore we will use below 'setup pyconfigurationsetup py from distutils core import setup setup(name "wolfpack"choose any name version " "give version number packages ['wolfpack']add package here nextrun the setup py as below and it will create 'distributionit will show some warning as we did not include the 'readme txtand 'manifest inetc distribute the package
4,393
(pythondsppython setup py sdist running sdist running check warningcheckmissing required meta-dataurl warningcheckmissing meta-dataeither (author and author_emailor (maintainer and maintainer_email'-must be supplied warningsdistmanifest template 'manifest indoes not exist (using default file listwarningsdiststandard file not foundshould have one of readmereadme txt writing manifest file 'manifestcreating wolfpack- creating wolfpack- /wolfpack making hard links in wolfpack- hard linking setup py -wolfpack- hard linking wolfpack/__init__ py -wolfpack- /wolfpack hard linking wolfpack/my_calc py -wolfpack- /wolfpack hard linking wolfpack/my_work py -wolfpack- /wolfpack creating dist creating tar archive removing 'wolfpack- (and everything under itthe resultant distribution will be saved as 'wolfpack- tar gzinside the 'distfolder extract the 'zippedfile then execute the setup py file in the unzipped folder as belowcd dist/wolfpack- python setup py install nextsee the 'site-packagesfolder for 'wolfpackpackageor use below command to check the list of packages (pythondsppip list wolfpack ( finallycheck the working of the package create folder at any location and run the below commands(pythondsppython from wolfpack import sum num( my_calc diff num( , conclusion in this we learn about the virtual environment and packages alsowe saw the method by which we can convert the 'packageinto the 'distribution conclusion
4,394
debugging introdution in this the 'sysmodule is discussed to read the input from the terminal then little overview of the debugging tool is providedwhich will be used in subsequent first code in the below codeperimeter and area of circular ring is calculated ring py from math import pi metal "copperradius perimeter *pi*radius area pi radius** print("metal "metalprint("pi "piprint("perimeter "perimeterprint("area "areafollowing is the output of the above codepython ring py metal copper pi perimeter area reading input from command line in the previous codethe inputsi radius and metalare hardwired in the code in this sectionwe will modify the codeso that the inputs values can be provided from the termial for thiswe need to import 'sysmodule note
4,395
the 'sys argvpass the command line argument to python script the argv[ is the file name alsothe arguments are passed as string-formattherefore these need to be converted into proper formatas done in line where the argv[ is converted into 'floatformat ring py import sys from math import pi if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" sys argv[ is the file name metal "coppermetal sys argv[ radius input is read as string therefore it is converted into float radius float(sys argv[ ] perimeter *pi*radius area pi radius** print("metal ="metalprint("pi ="piprint("perimeter ="perimeterprint("area ="areanowrun the command and we will get the following outputs python ring py usage ring py "metalradius python ring py "gold metal gold perimeter area debugging in this sectiontwo basic methods are shown for debugging the code in the later we will see use some advance topics such as decorator and descriptor etc to debug the design run script and go to python shell one of the way to debug the code is to use python shell for this we can use the '-ioption as shown below after executing of the code using 'ioptionthe python shell will be openwhere we can check the various values or behavior of the implemented logics we will use this method extensively in the tutorial python - ring py "gold metal gold perimeter area print(sys argvprint the arguments read from terminal ['ring py''gold'' '(continues on next page debugging
4,396
(continued from previous pageprint(metalgold python debugger (pdbanother way to debug the code is to use the 'pdb'as shown belowherepython debugger module is imported at line nextpdb set_trace is used to set the starting location for the debuggingi the code will stop after reaching this point line here ring py import pdb python debugger import sys from math import pi if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" print arguments print("entered values"sys argv manual debugging starts from here pdb set_trace( sys argv[ is the file name metal "coppermetal sys argv[ radius input is read as string therefore it is converted into float radius float(sys argv[ ] perimeter *pi*radius area pi radius** print("metal ="metalprint("pi ="piprint("perimeter ="perimeterprint("area ="areanowrun the code as below press 'sand then enter to execute the next line python ring py "gold entered values['ring py''gold'' '/ring py( )(-metal sys argv[ (pdbs /ring py( )(-radius float(sys argv[ ] underscore operator (_the underscore operator stores the last value of the calculation and can be very useful while debugging the code in python shell underscore operator (
4,397
conclusion in this we saw the debugging tools which will be used in subsequent alsothe module 'sysis discussed for reading the inputs from the terminal conclusion
4,398
print statement introduction in this the print statement is discussed to print the output in nice format expansion calculation in the below codenumber of days are calculate in which the diameter of the ring becomes greater than or equal to cm expansion py find the number of days when radius cm due to heat-expansion import sys if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" sys argv[ is the file name metal sys argv[ input is read as string therefore it is converted into float radius float(sys argv[ ] list of expansion rate for different metal rate [ [coppergoldiron day while radius multiply by correct expansion rate if metal ="copper"expansion radius rate[ elif metal ="gold"expansion radius rate[ elif metal ="iron"expansion radius rate[ elseprint("enter the correct metal"break new radius (continues on next page
4,399
(continued from previous page radius +expansion day + increment the number of days by one print the number of days print("number of days ="dayfollowing are the outputs for different metals with same radiuspython expansion py "gold number of days python expansion py "iron number of days python expansion py "copper number of days python expansion py "silver enter the correct metal number of days print the expansion in the below codethe new radius after expansion is printed on the daily basis expansion py find the number of days when radius cm due to heat-expansion import sys if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" sys argv[ is the file name metal sys argv[ input is read as string therefore it is converted into float radius float(sys argv[ ] list of expansion rate for different metal rate [ [coppergoldiron day print("dayexpansionradius"while radius multiply by correct expansion rate if metal ="copper"expansion radius rate[ elif metal ="gold"expansion radius rate[ elif metal ="iron"expansion radius rate[ elseprint("enter the correct metal"break (continues on next page print the expansion