id
int64
0
25.6k
text
stringlengths
0
4.59k
12,200
find method findall method finditer method first crossing time first method flat is better than nested flattening float data type float function float data type float data type float data type float data type floor function floor_divide function flow control - exception handling - for loops - if statements - pass statements range function - ternary expressions while loops xrange function - flush method fmax function fmin function fname option for loops - format option frequencies - converting specialized frequencies - week of month dates frompyfunc function from_csv method functions - anonymous functions are objects - closures - currying of extended call syntax for lambda functions namespaces for - parsing in pandas returning multiple values from scope of - functools module future contract rolling - futures gamma function gcc command generators - defined generator expressions itertools module for - get method getattr function get_chunk method get_dummies function get_value method get_xlim method gil (global interpreter lock) global scope glue for code python as gov domain grangerbrian graphics chaco mayavi greater function greater_equal function grid argument group keys groupby method - iterating over groups - on column - on dict - on levels resampling with using functions with - with series - grouping federal election commission database example - bucketing donation amounts - donation statistics by occupation and employer - donation statistics by state - apply method - data aggregation - returning data in unindexed form using multiple functions - index www it-ebooks info
12,201
values - for financial applications - factor analysis with - quartile analysis - group weighted average - groupby method - iterating over groups - on column - on dict - on levels using functions with - with series - linear regression for - pivot tables - cross-tabulation - quantile analysis with - random sampling with - haiti earthquake crisis data example - half-open hasattr function hash mark (#) hashability hdf (hierarchical data format) - hdfstore class header argument heapsort sorting method hierarchical data format (hdf ) - hierarchical indexing in pandas - sorting levels - summary statistics by level with dataframe columns - reshaping data with - hist method histograms - history of commandssearching homogeneous data container how argument hsplit function hstack function html files - html notebook in ipython hunterjohn hyperbolic trigonometric functions icol method ides (integrated development environments) idxmax method idxmin method if statements - ifilter function iget_value method ignore_index argument imap function import directive in python - usage of in this book imshow function in keyword in-place sort in method indentation in python - indentationerror event index method index objects data structure - indexes defined for arrays - for axis - for timeseries class - hierarchical indexing - reshaping data with - sorting levels - summary statistics by level with dataframe columns - in pandas integer indexing - merging data on - index_col argument indirect sorts - input variables - insert method insort method int data type int data type int data type int data type int index index object int data type integer arraysindexing using (see fancy indexing index www it-ebooks info
12,202
integrated development environments (ides) interpreted languages defined python interpreter interrupting code intersect method intersection method intervals of time inv function inverse trigonometric functions ipynb files ipython bookmarking directories command history in - input and output variables - logging of - reusing command history design tips - flat is better than nested keeping relevant objects and data alive overcoming fear of longer files - development tools - debugger - profiling code - profiling function line-by-line - timing code - executing code from clipboard - html notebook in integration with ides and editors integration with mathplotlib - keyboard shortcuts for magic commands in - making classes output correctly object introspection in - profiles for - qt console for quick reference card for reloading module dependencies %run command in - shell commands in - tab completion in - tracebacks in - ipython_config py file irow method is keyword isdisjoint method isfinite function isin method - isinf function isinstance function isnull method issubdtype function issubset method issuperset method is_monotonic method is_unique method iter function iterating over groups - iterator argument iterator protocol itertools module - ix_ function join method json (javascript object notation) kde (kernel density estimateplots keep_date_col argument kernels key-value pairs keyboard shortcuts for deleting text for ipython keyboardinterrupt event keys argument for dicts method keyword arguments kind argument kurt method label argument lambda functions last method layout of arrays in memory - left argument left_index argument left_on argument legends in matplotlib index www it-ebooks info
12,203
less function less_equal function level keyword levels defined grouping on sorting - summary statistics by lexicographical sort defined lexsort method libraries - ipython matplotlib numpy pandas - scipy limit argument linalg function line plots - linear algebra - linear regression - - lineterminator option line_profiler extension linuxsetting up on - list comprehensions - nested list comprehensions - list function lists - adding elements to - binary search of combining insertion into sorted list comprehensions - removing elements from - slicing - sorting - ljust method load function load method loads function local scope localizing time series data - loffset argument log function log function log function logging command history in ipython - logical_and function logical_not function logical_or function logical_xor function logy argument long format long type longer files overcoming fear of - lower method lstrip method lstsq function lxml library - mad method magic methods - main function mainpulating structured arrays many-to-many merge many-to-one merge map method - margins markers match method - matplotlib - annotating in - axis labels in - configuring - integrating with ipython - legends in saving to file styling for - subplots in - ticks in - title in - matplotlibrc file matrix operations in numpy - max method maximum function mayavi mean method median method memmap object memorylayout of arrays in - memory-mapped files defined saving arrays to file - mergesort sorting method merging data - index www it-ebooks info
12,204
concatenating along axis - dataframe merges - on index - meshgrid function methods defined for tuples in python starting with underscore microsoft excel files mil domain min method minimum function missing data - filling in - filtering out - mod function modf function modules momentum mongodb movielens data set example - moving window functions - binary moving window functions - exponentially-weighted functions user-defined mpkg file mro method mul method multiindex index object multiple profiles multiply function munging mutable objects - na data type names argument namespaces defined in python - naming trends in us baby names - example boy names that became girl names measuring increase in diversity - revolution of last letter - nan (not number) na_values argument ncols option ndarray boolean indexing - creating arrays - data types for - fancy indexing - indexes for - operations between arrays - slicing arrays - swapping axes in - transposing - nested code nested data types - nested list comprehensions - new york mta (metropolitan transportation authority) none data type normal function normalized timestamps nosql databases not number (nan) notebookcloud notnull method not_equal function npy files npz files nrows argument nuisance column numeric data types - numpy arrays in - concatenating - c_ object layout of in memory - replicating - reshaping - r_ object saving to file - splitting - subsets for - broadcasting - over other axes - setting array values by data processing using where function - data processing using arrays - index www it-ebooks info
12,205
methods for boolean arrays sorting arrays - statistical methods unique function - data types for - file input and output with arrays - saving and loading text files - storing on disk in binary format linear algebra - matrix operations in - ndarray arrays boolean indexing - creating - data types for - fancy indexing - indexes for - operations between arrays - slicing arrays - swapping axes in - transposing - numpy-discussion (mailing list) performance of - contiguous memory - cython project - random number generation - random walks example - sorting - algorithms for - finding elements in sorted array indirect sorts - structured arrays in - benefits of mainpulating nested data types - universal functions for - - custom in pandas - instance methods for - object introspection - object model object type objectify function objs argument offsets for time series data - ohlc (open-high-low-closeresampling ols function olson database on argument ones function open function open-high-low-close (ohlcresampling operators in python or keyword order method os xsetting up python on - outer method outliersfiltering - output variables - pad method pairs plot pandas - arithmetic and data alignment - arithmetic methods with fill values operations between dataframe and series - data structures for - dataframe - index objects - panel - series - drop function filtering in - handling missing data - filling in - filtering out - hierarchical indexing in - sorting levels - summary statistics by level with dataframe columns - indexes in indexing options - integer indexing - numpy universal functions with - plotting with bar plots - density plots - histograms - index www it-ebooks info
12,206
scatter plots - ranking data in - reductions in - reindex function - selecting in objects - sorting in - summary statistics in correlation and covariance - isin function - unique function - value_counts function - usa gov data from bit ly example with panel data structure - panels parse method parse_dates argument partial function partial indexing pass statements passing by reference pasting keyboard shortcut for magic command for patches path argument path variable pct_change method pdb debugger pdf files percentileofscore function perezfernando performance and time series data - of numpy - contiguous memory - cython project - period class periodindex index object periods - converting timestamps to creating periodindex from arrays defined frequency conversion for instead of timestamps - quarterly periods - resampling with - period_range function permutation pickle serialization pinv function pivoting data cross-tabulation - defined pivot method - pivot_table method - pivot_table aggregation type plot method plotting haiti earthquake crisis data example time series data - with matplotlib - annotating in - axis labels in - configuring - legends in saving to file styling for - subplots in - ticks in - title in - with pandas bar plots - density plots - histograms - line plots - scatter plots - png files pop method positional arguments power function pprint module pretty printing and displaying through pager defined private attributes private methods prod method profiles defined for ipython - profile_default directory profiling code in ipython - pseudocode index www it-ebooks info
12,207
put method py files pydata (google group) pylab mode pymongo driver pyplot module pystatsmodels (mailing list) python benefits of using - glue for code solving "two-languageproblem with data types for - boolean data type dates and times - none data type numeric data types - str data type - type casting in dict comprehensions in - dicts in - creating default values for - keys for file input/output in - flow control in - exception handling - for loops - if statements - pass statements range function - ternary expressions while loops xrange function - functions in - anonymous functions are objects - closures - currying of extended call syntax for lambda functions namespaces for - returning multiple values from scope of - generators in - generator expressions itertools module for - ides for interpreter for list comprehensions in - lists in - adding elements to - binary search of combining insertion into sorted removing elements from - slicing - sorting - python vs python required libraries - ipython matplotlib numpy pandas - scipy semantics of - attributes in comments in functions in import directive - indentation - methods in mutable objects in - object model operators for references in - strict evaluation strongly-typed language - variables in - "ducktyping sequence functions in - enumerate function reversed function sorted function zip function - set comprehensions in - sets in - setting up - on linux - on os - on windows - tuples in - methods for unpacking pytz library index www it-ebooks info
12,208
qcut method qr function qt console for ipython quantile analysis - quarterly periods - quartile analysis - question mark (?) quicksort sorting method quotechar option quoting option file mode rfile mode ramachandranprabhu rand function randint function randn function random number generation - random sampling with grouping - random walks example - range function - ranking data defined in pandas - ravel method rc method re module read method read-only mode reading from databases - from text files in pieces - readline functionality readlines method readshapefile method read_clipboard function read_csv function read_frame function read_fwf function read_table function recfunctions module reduce method reduceat method reductions (see also aggregationsdefined in pandas - references defined in python - regress function regular expressions (regexdefined manipulating strings with - reindex method - reload function remove method rename method renaming axis indexes - repeat method replace method replicating arrays - resampling - defined ohlc (open-high-low-closeresampling upsampling - with groupby method with periods - reset_index function reshape method - reshaping arrays - defined with hierarchical indexing - resources return statements returns cumulative returns - defined return indexes - reversed function rfind method right argument right_index argument right_on argument rint function rjust method rollback method rollforward method rolling rolling correlation - rolling_apply function rolling_corr function index www it-ebooks info
12,209
rolling_cov function rolling_kurt function rolling_mean function rolling_median function rolling_min function rolling_mint function rolling_quantile function rolling_skew function rolling_std function rolling_sum function rolling_var function rot argument rows option row_stack function rstrip method r_ object save function save method savefig method savez function saving text files - scatter method scatter plots - scatter_matrix function scientific python base scipy library scipy-user (mailing list) scope - screenclearing scripting languages scripts search method searchsorted method seed function seek method semantics - attributes in comments in "ducktyping functions in import directive - indentation - methods in mutable objects in - object model operators for references in - strict evaluation strongly-typed language - variables in - semicolons sentinels sep argument sequence functions - enumerate function reversed function sorted function zip function - series data structure - arithmetic operations between dataframe and - grouping with - set comprehensions - set function setattr function setdefault method setdiff method sets/set comprehensions - setxor method set_index function set_index method set_title method set_trace function set_value method set_xlabel method set_xlim method set_xticklabels method set_xticks method shapefiles shapes sharex option sharey option shell commands in ipython - shifting in time series data - shortcutskeyboard for deleting text for ipython shuffle function sign function signal frontier analysis - sin function sinh function size method skew method skipinitialspace option index www it-ebooks info
12,210
skipna option skiprows argument skip_footer argument slice method slicing arrays - lists - social security administration (ssa) solve function sort argument sort method sorted function sorting arrays - finding elements in sorted array - in numpy - algorithms for - finding elements in sorted array indirect sorts - in pandas - levels - lists - sortlevel function sort_columns argument sort_index method spacesstructuring code with - spacing around subplots - span specialized frequencies data munging for - split method split-apply-combine splitting arrays - sql databases sql module sqlite databases sqrt function square function squeeze argument ssa (social security administration) stable sorting stacked format start index startswith method statistical methods std method stdout step index stop index strftime method strict evaluation/language strides/strided view strings converting to datetime - data types for - manipulating - methods for - vectorized string methods - with regular expressions - strip method strongly-typed languages - strptime method structs structured arrays - benefits of defined mainpulating nested data types - style argument styling for matplotlib - sub method subn method subperiod subplots - subplots method subplots_adjust method subplot_kw option subsets for arrays - subtract function sudo command suffixes argument sum method summary statistics by level correlation and covariance - isin function - unique function - value_counts function - superperiod svd function swapaxes method swaplevel function swapping axes in arrays - symmetric_difference method syntactic sugar index www it-ebooks info
12,211
copyright (ctutorialspoint com dear readersthese python programming language interview questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of python programming language as per my experience good interviewers hardly plan to ask any particular question during your interviewnormally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer what is pythonpython is high-levelinterpretedinteractive and object-oriented scripting language python is designed to be highly readable it uses english keywords frequently where as other languages use punctuationand it has fewer syntactical constructions than other languages name some of the features of python following are some of the salient features of python it supports functional and structured programming methods as well as oop it can be used as scripting language or can be compiled to byte-code for building large applications it provides very high-level dynamic data types and supports dynamic type checking it supports automatic garbage collection it can be easily integrated with cc++comactivexcorbaand java what is the purpose of pythonpath environment variablepythonpath it has role similar to path this variable tells the python interpreter where to locate the module files imported into program it should include the python source library directory and the directories containing python source code pythonpath is sometimes preset by the python installer what is the purpose of pythonstartup environment variablepythonstartup it contains the path of an initialization file containing python source code it is executed every time you start the interpreter it is named as pythonrc py in unix and it contains commands that load utilities or modify pythonpath what is the purpose of pythoncaseok environment variablepythoncaseok it is used in windows to instruct python to find the first case-insensitive match in an import statement set this variable to any value to activate it what is the purpose of pythonhome environment variablepythonhome it is an alternative module search path it is usually embedded in the pythonstartup or pythonpath directories to make switching module libraries easy is python case sensitive languageyespython is case sensitive programming language what are the supported data types in pythonpython has five standard data types numbers string
12,212
tuple dictionary what is the output of print str if str 'hello world!'it will print complete string output would be hello worldwhat is the output of print str[ if str 'hello world!'it will print first character of the string output would be what is the output of print str[ : if str 'hello world!'it will print characters starting from rd to th output would be llo what is the output of print str[ :if str 'hello world!'it will print characters starting from rd character output would be llo worldwhat is the output of print str if str 'hello world!'it will print string two times output would be hello world!hello worldwhat is the output of print str "testif str 'hello world!'it will print concatenated string output would be hello world!test what is the output of print list if list 'abcd' 'john' ]it will print complete list output would be ['abcd' 'john' what is the output of print list[ if list 'abcd' 'john' ]it will print first element of the list output would be abcd what is the output of print list[ : if list 'abcd' 'john' ]it will print elements starting from nd till rd output would be [ what is the output of print list[ :if list 'abcd' 'john' ]it will print elements starting from rd element output would be [ 'john' what is the output of print tinylist if tinylist [ 'john']it will print list two times output would be [ 'john' 'john'what is the output of print list tinylist if list 'abcd' 'john' and tinylist [ 'john']it will print concatenated lists output would be ['abcd' 'john' 'john'what are tuples in pythona tuple is another sequence data type that is similar to the list tuple consists of number of values separated by commas unlike listshowevertuples are enclosed within parentheses what is the difference between tuples and lists in pythonthe main differences between lists and tuples are lists are enclosed in brackets [and their elements and size can be changedwhile tuples are enclosed in parentheses and cannot be updated tuples can be thought of as read-only lists what is the output of print tuple if tuple abcd john
12,213
what is the output of print tuple[ if tuple abcd john it will print first element of the tuple output would be abcd what is the output of print tuple[ : if tuple abcd john it will print elements starting from nd till rd output would be what is the output of print tuple[ :if tuple abcd john it will print elements starting from rd element output would be john what is the output of print tinytuple if tinytuple john it will print tuple two times output would be john john what is the output of print tuple tinytuple if tuple abcd john and tinytuple john it will print concatenated tuples output would be abcd john john what are python' dictionariespython' dictionaries are kind of hash table type they work like associative arrays or hashes found in perl and consist of key-value pairs dictionary key can be almost any python typebut are usually numbers or strings valueson the other handcan be any arbitrary python object how will you create dictionary in pythondictionaries are enclosed by curly braces and values can be assigned and accessed using square braces [dict {dict['one'"this is onedict[ "this is twotinydict {'name''john','code': 'dept''sales'how will you get all the keys from the dictionaryusing dictionary keys functionwe can get all the keys from the dictionary object print dict keys(prints all the keys how will you get all the values from the dictionaryusing dictionary values functionwe can get all the values from the dictionary object print dict values(prints all the values how will you convert string to an int in pythonintx[baseconverts to an integer base specifies the base if is string how will you convert string to long in pythonlongx[baseconverts to long integer base specifies the base if is string how will you convert string to float in pythonfloatx converts to floating-point number how will you convert object to string in pythonstrx converts object to string representation
12,214
reprx converts object to an expression string how will you convert string to an object in pythonevalstr evaluates string and returns an object how will you convert string to tuple in pythontuples converts to tuple how will you convert string to list in pythonlists converts to list how will you convert string to set in pythonsets converts to set how will you create dictionary using tuples in pythondictd creates dictionary must be sequence of keyvalue tuples how will you convert string to frozen set in pythonfrozensets converts to frozen set how will you convert an integer to character in pythonchrx converts an integer to character how will you convert an integer to an unicode character in pythonunichrx converts an integer to unicode character how will you convert single character to its integer value in pythonordx converts single character to its integer value how will you convert an integer to hexadecimal string in pythonhexx converts an integer to hexadecimal string how will you convert an integer to octal string in pythonoctx converts an integer to an octal string what is the purpose of *operator*exponent performs exponential power calculation on operators ** to the power if and what is the purpose of /operator/floor division the division of operands where the result is the quotient in which the digits after the decimal point are removed what is the purpose of is operatoris evaluates to true if the variables on either side of the operator point to the same object and false otherwise is yhere is results in if idx equals idy what is the purpose of not in operatornot in evaluates to true if it does not finds variable in the specified sequence and false otherwise not in yhere not in results in if is not member of sequence
12,215
break statement terminates the loop statement and transfers execution to the statement immediately following the loop what is the purpose continue statement in pythoncontinue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating what is the purpose pass statement in pythonpass statement the pass statement in python is used when statement is required syntactically but you do not want any command or code to execute how can you pick random item from list or tuplechoiceseq returns random item from listtupleor string how can you pick random item from rangerandrange [start]stop[stepreturns randomly selected element from rangestartstopstep how can you get random number in pythonrandom returns random float rsuch that is less than or equal to and is less than how will you set the starting value in generating random numbersseed[xsets the integer starting value used in generating random numbers call this function before calling any other random module function returns none how will you randomizes the items of list in placeshufflelst randomizes the items of list in place returns none how will you capitalizes first letter of stringcapitalize capitalizes first letter of string how will you check in string that all characters are alphanumericisalnum returns true if string has at least character and all characters are alphanumeric and false otherwise how will you check in string that all characters are digitsisdigit returns true if string contains only digits and false otherwise how will you check in string that all characters are in lowercaseislower returns true if string has at least cased character and all cased characters are in lowercase and false otherwise how will you check in string that all characters are numericsisnumeric returns true if unicode string contains only numeric characters and false otherwise how will you check in string that all characters are whitespacesisspace returns true if string contains only whitespace characters and false otherwise how will you check in string that it is properly titlecasedistitle returns true if string is properly "titlecasedand false otherwise how will you check in string that all characters are in uppercaseisupper returns true if string has at least one cased character and all cased characters are in
12,216
how will you merge elements in sequencejoinseq merges concatenates the string representations of elements in sequence seq into stringwith separator string how will you get the length of the stringlenstring returns the length of the string how will you get space-padded string with the original string left-justified to total of width columnsljustwidth[fillcharreturns space-padded string with the original string left-justified to total of width columns how will you convert string to all lowercaselower converts all uppercase letters in string to lowercase how will you remove all leading whitespace in stringlstrip removes all leading whitespace in string how will you get the max alphabetical character from the stringmaxstr returns the max alphabetical character from the string str how will you get the min alphabetical character from the stringminstr returns the min alphabetical character from the string str how will you replaces all occurrences of old substring in string with new stringreplaceoldnew[maxreplaces all occurrences of old in string with new or at most max occurrences if max given how will you remove all leading and trailing whitespace in stringstrip[charsperforms both lstrip and rstrip on string how will you change case for all letters in stringswapcase inverts case for all letters in string how will you get titlecased version of stringtitle returns "titlecasedversion of stringthat isall words begin with uppercase and the rest are lowercase how will you convert string to all uppercaseupper converts all lowercase letters in string to uppercase how will you check in string that all characters are decimalisdecimal returns true if unicode string contains only decimal characters and false otherwise what is the difference between del and remove methods of listto remove list elementyou can use either the del statement if you know exactly which elements you are deleting or the remove method if you do not know what is the output of len[ ] what is the output of [ [ ]
12,217
what is the output of ['hi!' ['hi!''hi!''hi!''hi!'what is the output of in [ ]true what is the output of for in [ ]print what is the output of [ if [ , , ] offsets start at zero what is the output of [- if [ , , ] negativecount from the right what is the output of [ :if [ , , ] slicing fetches sections how will you compare two listscmplist list compares elements of both lists how will you get the length of listlenlist gives the total length of the list how will you get the max valued item of listmaxlist returns item from the list with max value how will you get the min valued item of listminlist returns item from the list with min value how will you get the index of an object in listlist indexobj returns the lowest index in list that obj appears how will you insert an object at given index in listlist insertindexobj inserts object obj into list at offset index how will you remove last object from listlist popobj list removes and returns last object or obj from list how will you remove an object from listlist removeobj removes object obj from list how will you reverse listlist reverse reverses objects of list in place how will you sort listlist sort[funcsorts objects of listuse compare func if given what is next
12,218
you are able to speak confidently on them if you are fresher then interviewer does not expect you will answer very complex questionsrather you have to make your basics concepts very strong second it really doesn' matter much if you could not answer few questions but it matters that whatever you answeredyou must have answered with confidence so just feel confident during your interview we at tutorialspoint wish you best luck to have good interviewer and all the very best for your future endeavor cheers :-processing math
12,219
interview questions common interview questions www bitdegree org
12,220
as you've probably expectedthis is one of the very first python interview questions that you're bound to get asked your employers are probably going to expect concise and thorough answerso let' provide them one python is portablehigh-level programming language that has inbuilt automatic memory managementthreadsstringsis object-based it is loved for the simplicity and builtin data structure the fact that python is open source also contributes to its fame why is python better than javasome of your python interview questions might involve comparisons with other programming languages these can be randombut java seems like the most common one that employers ask in shortpython (when compared with javais easier to use and has much better coding speeds alsowhen it comes to datajava is statically typedwhile python offers dynamic typing this is considered to be huge advancement how many data types are there in pythonone of the more common interview questions on python you might get asked to either say the number or actually name them python has five different data types string dictionary www bitdegree org list number tuple
12,221
"unpicklingpickling happens when module within python is accepted and converted into string moduleand then later dumped into the file as opposed to thatunpickling is when you retrieve the string module from the file for such comparison-based python interview questionstry to keep your explanations as simple as possible your potential employers will probably appreciate that you are able to explain tough topics in simple-to-understand manner what is 'lambda'this one' pretty straight forward to put it simply lambda is an anonymously performed function with just onesingle expression how is memory managed within pythonpython' private heap space is responsible for memory management it is only accessible by an interpreter if you're python programmeryou won' be able to reach it the language also has an inbuilt recycler that is responsible for creating more free heap space (this is done by recycling unused memory what is 'pass'pass simply indicates space that should be left blank within the compound statement www bitdegree org
12,222
object in pythoneven though it sounds like one of the basic python interview questionsyou would probably be surprised how many people actually manage to stumble with it yesyou can copy objects in pythonbut not all of them the most general and wellknown way to do it is to use the copy copy(command how to delete file in pythonto delete something in pythonuse the commandos remove(name_of_the_file what is 'dictionarya dictionary is an in-built data type dictionaries are comprised of keys and the key corresponding values here' an example how is 'tupleand 'listdifferentthe main difference is that lists are slowerbut they can be editedwhile tuples work fasterbut cannot be modified www bitdegree org
12,223
dictionary is an in-built data type dictionaries are comprised of keys and the key corresponding values here' an example is python an interpreted languageagainone of the most commonly asked python coding interview questions you should definitely keep this in mind yespython is an interpreted programming language what does this meanit' three-way process you write the source codepython converts it into an intermediate language (for easier understandingand then it' yet again changed into machine codes that are then executed bonuspractice which of these is wrongaxyz , , bx, , cx dx_y_z , , is the only one that' wrong www bitdegree org
12,224
object-oriented programming languages (oopsare based on classes and objects of those classes python is exactly that more sopython possesses the features that are credited to oops inheritancepolymorphismetc what is 'slicing'in pythonslicing is when you select multiple items from places like listsstrings and so on so those are the more basic python interview questions that you might receive during your job interview nowlet' try and move more towards the advanced stuff and some untouched python technical interview questions leaked exercises write piece of code that would calculate list of given numbers write piece of code that would randomize items from the list www bitdegree org
12,225
interview questions www bitdegree org
12,226
between 'rangeand 'xrange'yesalbeit it might not be noticeable at first in terms of functionality and the tasks they performboth commands are nearly identical the key differencehoweveris that range (when usedbrings back list objectwhile xrange returns an xrange object what is the dogpile effectthis is one of the python interview questions that might be tricky to memorize at firstso do give it few good tries dogpile effect happens when website' cache expiresyet it is hit by many different requests from the user this can cause many different problemsfrom lag spikes to complete crashes system called semaphore lock is used to prevent dogpiles from happening explain what is called 'encapsulationencapsulation is one of the features that python has because it' an object-oriented programming language encapsulation is process of grouping related data members into onesingle place along with the member themselvesencapsulation also returns their functionstoo www bitdegree org
12,227
termination happenfirst of allit should be said abnormal termination is bad you don' want it to happen in your coding experiencealthough it' almost unavoidable at one point or anotherespecially when you're beginner programmer abnormal termination is crash of your program in the middle of its executionwhile the main tasks are still running this is usually caused by faulty code or some software issues leaked interview exercise if you would need to count all of the capital letters in file how would you do it does python have compilerthis is actually one of the tougher python interview questionsmostly because not many people pay attention to it python indeed does have its own compilerbut it' rather easy to miss this is because it works automatically you don' really notice it www bitdegree org
12,228
patchingmonkey patching refers to modifications that you would make to the code when it' already running leaked interview exercises write piece of code that could save images locally for the exercise imagine that you know the image url questionif list is [ ]what will list [- beanswer"- always points to the last index in listso the answer would be what is 'decoratordecorators are used to inserting new and fresh pieces of code into an already existing class or function with the help of decoratorsyou can make these codes run before or after the original one what do the functions 'help()and 'dir()doboth of these functions can be accessed from the python interpreter they are used to view consolidated dumps from inbuilt functions help(shows you the documentation stringwhile dir(displays the defined symbols www bitdegree org
12,229
co pyrig ht (ctuto rials po int co python has been an object-oriented lang uag from day one because of thiscreating and using classes and objects are downrig ht easy his helps you become an expert in using python' object-oriented prog ramming support if you don' have any previous experience with object-oriented (ooprog ramming you may want to consult an introductory course on it or at least tutorial of some sort so that you have rasp of the basic concepts howeverhere is small introduction of object-oriented prog ramming (oopto bring you at speedoverview of oop terminolog classa user-defined prototype for an object that defines set of attributes that characterize any object of the class he attributes are data members (class variables and instance variablesand methodsaccessed via dot notation class variablea variable that is shared by all instances of class class variables are defined within class but outside any of the class' methods class variables aren' used as frequently as instance variables are data membera class variable or instance variable that holds data associated with class and its objects func tion overloading he assig nment of more than one behavior to particular function he operation performed varies by the types of objects (arg umentsinvolved instanc variablea variable that is defined inside method and belong only to the current instance of class inheritanc he transfer of the characteristics of class to other classes that are derived from it instanc ean individual object of certain class an object obj that belong to class circlefor exampleis an instance of the class circle instantiation he creation of an instance of class method special kind of function that is defined in class definition bjec unique instance of data structure that' defined by its class an object comprises both data members (class variables and instance variablesand methods perator overloading he assig nment of more than one function to particular operator creating classest he class statement creates new class definition he name of the class immediately follows the keyword class followed by colon as followsclass classname'optional class documentation stringclass_suite he class has documentation string which can be accessed via classname __doc__ he class_suite consists of all the component statements defining class membersdata attributes and functions examplefollowing is the example of simple python class
12,230
'common base class for all employeesempcount def __init__(selfnamesalary)self name name self salary salary employee empcount + def displaycount(self)print "total employee %demployee empcount def displayemployee(self)print "name "self name"salary"self salary he variable empcount is class variable whose value would be shared among all instances of this class his can be accessed as employee empcount from inside the class or outside the class he first method __init__(is special methodwhich is called class constructor or initialization method that python calls when you create new instance of this class you declare other class methods like normal functions with the exception that the first arg ument to each method is self python adds the self arg ument to the list for youyou don' need to include it when you call the methods creating instance objectst create instances of classyou call the class using class name and pass in whatever arg uments its __init__ method accepts "this would create first object of employee classemp employee("zara" "this would create second object of employee classemp employee("manni" accessing attributesyou access the object' attributes using the dot operator with object class variable would be accessed using class name as followsemp displayemployee(emp displayemployee(print "total employee %demployee empcount nowputting all the concepts tog ether#!/usr/bin/python class employee'common base class for all employeesempcount def __init__(selfnamesalary)self name name self salary salary employee empcount + def displaycount(self)print "total employee %demployee empcount def displayemployee(self)print "name "self name"salary"self salary "this would create first object of employee classemp employee("zara" "this would create second object of employee classemp employee("manni"
12,231
emp displayemployee(print "total employee %demployee empcount when the above code is executedit produces the following resultname zara ,salary name manni ,salary total employee you can addremove or modify attributes of classes and objects at any timeemp age emp age del emp age add an 'ageattribute modify 'ageattribute delete 'ageattribute instead of using the normal statements to access attributesyou can use following functionst he etattr(objname[default]to access the attribute of object he hasattr(obj,nameto check if an attribute exists or not he setattr(obj,name,valueto set an attribute if attribute does not existthen it would be created he delattr(objnameto delete an attribute hasattr(emp 'age'returns true if 'ageattribute exists getattr(emp 'age'returns value of 'ageattribute setattr(emp 'age' set attribute 'ageat delattr(empl'age'delete attribute 'agebuilt-in class attributesevery python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute__dic t__ dictionary containing the class' namespace __doc __ class documentation string or none if undefined __name__class name __module__module name in which the class is defined his attribute is "__main__in interactive mode __bases__ possibly empty tuple containing the base classesin the order of their occurrence in the base class list for the above class let' try to access all these attributes#!/usr/bin/python class employee'common base class for all employeesempcount def __init__(selfnamesalary)self name name self salary salary employee empcount + def displaycount(self)print "total employee %demployee empcount def displayemployee(self)print "name "self name"salary"self salary
12,232
print "employee __name__:"employee __name__ print "employee __module__:"employee __module__ print "employee __bases__:"employee __bases__ print "employee __dict__:"employee __dict__ when the above code is executedit produces the following resultemployee __doc__common base class for all employees employee __name__employee employee __module____main__ employee __bases__(employee __dict__{'__module__''__main__''displaycount''empcount' 'displayemployee''__doc__''common base class for all employees''__init__'destroying objects (garbag collection)python deletes unneeded objects (built-in types or class instancesautomatically to free memory space he process by which python periodically reclaims blocks of memory that no long er are in use is termed arbag collection python' arbag collector runs during prog ram execution and is trig ered when an object' reference count reaches zero an object' reference count chang es as the number of aliases that point to it chang es an object' reference count increases when it' assig ned new name or placed in container (listtuple or dictionaryt he object' reference count decreases when it' deleted with delits reference is reassig nedor its reference oes out of scope when an object' reference count reaches zeropython collects it automatically [bcreate object increase ref count increase ref count of of del [ - decrease ref count decrease ref count decrease ref count of of of you normally won' notice when the arbag collector destroys an orphaned instance and reclaims its space but class can implement the special method __del__()called destructorthat is invoked when the instance is about to be destroyed his method mig ht be used to clean up any nonmemory resources used by an instance examplet his __del__(destructor prints the class name of an instance that is about to be destroyed#!/usr/bin/python class pointdef __initselfx= = )self self def __del__(self)class_name self __class__ __name__ print class_name"destroyedpt point(pt pt pt pt print id(pt )id(pt )id(pt prints the ids of the obejcts del pt del pt del pt when the above code is executedit produces following result
12,233
point destroyed noteideallyyou should define your classes in separate filethen you should import them in your main prog ram file using import statement kindly check python modules for more details on importing modules and classes class inheritanceinstead of starting from scratchyou can create class by deriving it from preexisting class by listing the parent class in parentheses after the new class name he child class inherits the attributes of its parent classand you can use those attributes as if they were defined in the child class child class can also override data members and methods from the parent syntaxderived classes are declared much like their parent classhowevera list of base classes to inherit from are iven after the class nameclass subclassname (parentclass [parentclass ])'optional class documentation stringclass_suite example#!/usr/bin/python class parentdefine parent class parentattr def __init__(self)print "calling parent constructordef parentmethod(self)print 'calling parent methoddef setattr(selfattr)parent parentattr attr def getattr(self)print "parent attribute :"parent parentattr class child(parent)define child class def __init__(self)print "calling child constructordef childmethod(self)print 'calling child methodc child( childmethod( parentmethod( setattr( getattr(instance of child child calls its method calls parent' method again call parent' method again call parent' method when the above code is executedit produces the following resultcalling child constructor calling child method calling parent method parent attribute similar wayyou can drive class from multiple parent classes as followsclass adefine your class
12,234
define your calss class (ab)subclass of and you can use issubclass(or isinstance(functions to check relationships of two classes and instances he issubc lass(subsupboolean function returns true if the iven subclass sub is indeed subclass of the superclass sup he isinstanc (objclassboolean function returns true if obj is an instance of class class or is an instance of subclass of class overriding methodsyou can always override your parent class methods one reason for overriding parent' methods is because you may want special or different functionality in your subclass example#!/usr/bin/python class parentdefine parent class def mymethod(self)print 'calling parent methodclass child(parent)define child class def mymethod(self)print 'calling child methodc child( mymethod(instance of child child calls overridden method when the above code is executedit produces the following resultcalling child method base overloading methodsfollowing table lists some eneric functionality that you can override in your own classessn methoddesc ription sample call __init__ self [,arg constructor (with any optional arg umentssample call obj classname(args __del__self destructordeletes an object sample call dell obj __repr__self evaluatable string representation sample call repr(obj __str__self printable string representation sample call str(obj __c mp__ selfx object comparison sample call cmp(objx
12,235
suppose you've created vector class to represent two-dimensional vectorswhat happens when you use the plus operator to add themmost likely python will yell at you you couldhoweverdefine the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectationexample#!/usr/bin/python class vectordef __init__(selfab)self self def __str__(self)return 'vector (% % )(self aself bdef __add__(self,other)return vector(self other aself other bv vector( , vector( ,- print when the above code is executedit produces the following resultvector( , data hiding an object' attributes may or may not be visible outside the class definition for these casesyou can name attributes with double underscore prefixand those attributes will not be directly visible to outsiders example#!/usr/bin/python class justcounter__secretcount def count(self)self __secretcount + print self __secretcount counter justcounter(counter count(counter count(print counter __secretcount when the above code is executedit produces the following result traceback (most recent call last)file "test py"line in print counter __secretcount attributeerrorjustcounter instance has no attribute '__secretcountpython protects those members by internally chang ing the name to include the class name you can access such attributes as object _classname__attrname if you would replace your last line as following then it would work
12,236
print counter _justcounter__secretcount when the above code is executedit produces the following result
12,237
unit structure learning objective introduction overview of object-oriented programming (oop basic concepts of objects and classes constructor in python __init__ inheritance in python overriding parent methods super(function multiple inheritance multilevel inheritance data encapsulation let' sum up references page
12,238
learning objective python is primarily designed as an object-oriented programming language this unit will focus on object orientation as programming paradigm with creating and using classesobjects and methods this will help you become an expert in using python' object-oriented programming support there are some basic programming concepts in oop such as inheritanceencapsulationand abstraction this unit will discuss object-oriented concepts in python with inheritanceencapsulation and polymorphism in this unityou will be able toidentify the object-oriented nature of python define classobject and method in python differentiate functions and methods in python introduction programming languages that allow the programmer to define new classes of objects are called object-oriented languages these languages also support style of programming called object-oriented programming python classes provide all the standard features of object-oriented programming the class inheritance mechanism facilitates you to define multiple base classesany methods of its base class(scan be overridden by the derived classand method can call the method of base class with the same name overview of object-oriented programming (oopin oopprograms are made up of objects and functions that are required to work with those objects soprograms contain object definitions and function definitions each object definition corresponds to some object or concept in the real worldand the functions that operate on that object correspond to the ways real-world objects interact class is new type or blueprint where objects are instances of particular class for examplethe draw polygon class correspond to drawing polygon it may include objects like circle or square object-oriented programming concept is model organized around "class/objectconcept rather than on functions objects are modelled after real-world entities page
12,239
when we create an objectwe call it an instance of class class is defined as type in python you can find out the type of any object using the type function functions are used to utilize the code in more than one place in program python provides inbuilt functions like print(and you can create your own functions in addition to built-in functions an object has two characteristicsattributes behaviour let' take an exampleman/women is an objectwhereas nameagecolor are attributes and singingdancing is behaviour the concept of oop in python focuses on creating reusable code this concept is also known as dry (don' repeat yourselfpython class python class is simply representation of type of object it is the blueprintplantemplate that describes the details of an object class is blueprint from which the individual objects are created class is composed of three thingsa nameattributesand operations the simplest form of class definition looks like thisclass class definitionslike function definitions in practicethe statements inside class definition will usually be function definitionsbut other statements are allowedand sometimes useful when class definition is entereda new name-space is createdand used as the local scope thusall assignments to local variables go into this new name-space in particularfunction definitions bind the name of the new function here the class definition syntax has two partsa class header and set of method definitions that follow the class header the class header consists of the class name and the parent class name the class name is python identifier page
12,240
class studentdef display(selfname )print ("your name is "namest student(st student(st display("aseem"st display("sibananda"outputyour name is aseem your name is sibananda in the above examplea class named student has been created function named display is defined display(function contain two-argument self and name two objects st and st have been created python object an object can be considered "thingthat can perform set of related activities the set of activities that the object performs defines the object' behaviour in pure oop termsan object is an instance of class syntax of object creation obj classname(hereobj is the object name whereas classname is the name of the class whose object has been created examplest student(you call the class using class name and call the function with arguments st display(argumentexampleclass studentnumber def dis(self,name)print(nameprint(numberst student(st dis("aseem"page
12,241
aseem traceback (most recent call last)nameerrorname 'numberis not defined explanationthe above example shows that number = while executingit is giving an errorthe number is class variable whose value would be shared among all instances of this class this can be accessed as student number from inside the class or outside the class the method inside the class can access the class variables by using self let' rewrite the program again class studentnumber def dis(self,name,number)print(nameprint(numberprint (self numberst student student(st dis("aseem", outputaseem now you can understand the meaning of self to access the class variable from method dis(we used self because the interpreter binds the parameter self to that object (means classobject is the instance of classthe code binds the parameter self in the method dis(to the student class object referenced by the variable st the code for dis(can then use self to access that particular object' number another exampleclass studentnumber def dis(self,name,number)print(nameprint(numberprint(self numberself number self number print(self numberst student(page
12,242
st student(st dis("aseem", print("value is ",student numberoutputaseem aseem value is exampleclass studentnumber def dis(self,name,number)print(nameprint(numberprint(student numberstudent number student number print(student numberst student(st dis("game", st student(st dis("aseem", print("value is ",student numberoutputaseem aseem value is page
12,243
the variable but student number can change the class variable because of the class variable number and class the number inside the method is the same constructor in python __init__ class functions that begin with double underscore (__are called special functions as they have special meaning of one particular interest is the __init__(function this special function gets called whenever new object of that class is instantiated this type of function is also called constructors in object-oriented programming (oopwe normally use it to initialize all the variables the init method (short for "initialization"is special method that gets invoked when an object is created its full name is __ init __ (two underscore charactersfollowed by initand then two more underscoresexampleclass dogdef __init__(self)print(" am inside the constructor method "instantiate the parrot class obj dog(if we added the above __init__ method to the dog classand create an object of the class dog then the program would output the following outputi am inside the constructor method this is because the constructor method is automatically initialized you should use this method to carry out any initializing you would like to do with your class objects instead of using the constructor method abovelet' create one that uses named variable that we can use to assign names to objects we'll pass the name as parameter and set self name equal to nameexampleclass sharkdef __init__(selfname)self name name def swim(self)print(self name is plying cricket "page
12,244
print(self name is being awesome "obj=shark("aseem"obj swim(obj be_awesome(outputaseem is plying cricket aseem is being awesome we see that the name we passed to the object is being printed out we defined the __init__ method with the parameter name (along with the self-keywordand defined variable within the method because the constructor method is automatically initializedwe do not need to explicitly call itonly pass the arguments in the parentheses following the class name when we create new instance of the class let' write the above program again using main function class sharkdef __init__(selfname)self name name def swim(self)print(self name is plying cricket "def be_awesome(self)print(self name is being awesome "def main()obj=shark("aseem"obj swim(obj be_awesome(if __name__ ="__main__"main(outputaseem is plying cricket aseem is being awesome page
12,245
example class dogclass attribute species "animalinstance attribute def __init__(selfnameage)self name name self age age instantiate the parrot class obj dog("blu" obj dog("woo" access the class attributes print("obj is {}format(dog species)print("obj is also {}format(dog species)access the instance attributes print("{is {years oldformatobj nameobj age)print("{is {years oldformatobj nameobj age)in the above examplewe define new class called dog it has function__init__(to initialize the variables inheritance in python object-oriented programming creates reusable patterns of code to curtail redundancy in development projects one way that object-oriented programming achieves recyclable code is through inheritance when one subclass can leverage code from another base class inheritance allows you to acquire the properties to base new class from an existing one by doing sothe new child class automatically gets all of the methods and attributes of the existing parent class in this wayyou can say the child class inherits the attributes of its parent class inheritance is way to form new classes using class that is already defined it is way of arranging objects in hierarchy from the most general to the most specific if we think of inheritance in terms of biologywe can think of child inheriting certain traits from their parent that isa child can inherit parent' height or eye color children also may share the same last name with their parents classes called child classes or subclasses inherit methods and variables from parent classes or base classes page
12,246
heightand eye_color that the child class child will inherit from the parent because the child subclass is inheriting from the parent base classthe child class can reuse the code of parentallowing the programmer to use fewer lines of code and decrease redundancy syntaxclass parentclassbody of parentclass class childclass(parentclass)body of child class so here child class inherits features from the parent classadding new features to it this results in re-usability of code exampleclass parentdef sum(self, , ) = + print("addition is ",cclass child(parent)def mul(self, , ) = * print("multiplication ",cc child(creating object of child class sum( , mul( , accessing the sum function of parent class using object of the child class outputaddition is multiplication the above example shows simple example of inheritance the child class inherit the properties of the parent classthat' why the object of child class can access the method of the parent class child or subclasses are classes that will inherit from the parent class that means that each child class will be able to make use of the methods and variables of the parent class another examplepage
12,247
subclasses each of these fish will have first names and last names in addition to characteristics let' add the methods swim(and swim_backwards(to the fish class so that every subclass will also be able to make use of these methods base classparent class class fishdef __init__(selfnoofeyes= last_name="fish")self noofeyes noofeyes self last_name last_name def swim(self)print("the fish is swimming "def swim_backwards(self)print("the fish can swim backwards " goldfish child class that subclasses the fish class will be able to make use of both the method swim(and swim_backwards(method declared in fish without needing to declare it the first line of child class looks little different than non-child classes as you must pass the parent class into the child class as parameterclass goldfish(fish)the goldfish class is child of the fish class we know this because of the inclusion of the word fish in parentheses with child classeswe can choose to add more methodsoverride existing parent methodsor simply accept the default parent methods with the pass keywordwhat we have done in this caseclass goldfish(fish)pass we can now create goldfish object without having to define any additional methods gf goldfish("terry"print(gf name gf last_name +"has "gf noofeyes ,"eyes"gf swim(gf swim_backwards(we have created goldfish object gf that makes use of each of the methods of the fish class even though we did not define those methods in the goldfish child class page
12,248
because all of the other variables were initialized so the complete code will looks like this class fishdef __init__(selfnamenoofeyes= last_name="fish")self name=name self noofeyes noofeyes self last_name last_name def swim(self)print("the fish is swimming "def swim_backwards(self)print("the fish can swim backwards "class goldfish(fish)pass gf goldfish("terry"print(gf name gf last_name +"has ",gf noofeyes ,"eyes"gf swim(gf swim_backwards(outputterry fish has eyes the fish is swimming the fish can swim backwards nextlet' create another child class called clownfish that includes its own method its special method will permit it to live with sea anemoneclass clownfish(fish)def live_with_anemone(self)print("the clownfish is coexisting with sea anemone "so the complete code will look like as follows page
12,249
parent class fish class fishdef __init__(selfnamenoofeyes= last_name="fish")self name=name self noofeyes noofeyes self last_name last_name def swim(self)print("the fish is swimming "def swim_backwards(self)print("the fish can swim backwards "child class goldfish class goldfish(fish)pass child class clownfish class clownfish(fish)def live_with_anemone(self)print("the clownfish is coexisting with sea anemone "gf goldfish("terry"print(gf name gf last_name +"has ",gf noofeyes ,"eyes"gf swim(gf swim_backwards(print(""casey clownfish("casey"print(casey name casey last_name +"has "casey noofeyes ,"eyes"casey swim(casey swim_backwards(casey live_with_anemone(outputterry fish has eyes the fish is swimming the fish can swim backwards terry fish has eyes the fish is swimming the fish can swim backwards the clownfish is coexisting with sea anemone page
12,250
as well as its child class method of live_with_anemone(if we try to use the live_with_anemone(method in gf objectwe'll receive an error this is because the method live_with_anemone(belongs only to the clownfish child classand not the fish parent class overriding parent methods so farwe have looked at the child class goldfish that made use of the pass keyword to inherit all of the parent class fish behavioursand another child class clownfish that inherited all of the parent class behaviours and also created its own unique method that is specific to the child class sometimeshoweverwe will want to make use of some of the parent class behaviours but not all of them when we change parent class methods we override them when constructing parent and child classesit is important to keep program design in mind so that overriding does not produce unnecessary or redundant code we'll create newfish child class of the fish parent class but suppose this newfish has one eye and can' swim backwards but as it is child class of fish class it inherits all the features of fish class like noofeye= and the swim_backwards(method of fish class which not our requirements for thatwe'll override swim_backwards(method the __init__(constructor method and the exampleclass fishdef __init__(selfnamenoofeyes= last_name="fish")self name=name self noofeyes noofeyes self last_name last_name def swim(self)print("the fish is swimming "def swim_backwards(self)print("the fish can swim backwards "class goldfish(fish)pass class clownfish(fish)page
12,251
print("the clownfish is coexisting with sea anemone "class newfish(fish)def swim_backwards(self)print("the fish can not swim backwards "gf goldfish("terry"print(gf name gf last_name +"has ",gf noofeyes ,"eyes"gf swim(gf swim_backwards(print(""casey clownfish("casey"print(casey name casey last_name +"has ",casey noofeyes ,"eyes"casey swim(casey swim_backwards(casey live_with_anemone(print(""nf newfish("derry", print(nf name nf last_name +has ",nf noofeyes ,"eyes"nf swim(nf swim_backwards(outputterry fish has eyes the fish is swimming the fish can swim backwards casey fish has eyes the fish is swimming the fish can swim backwards the clownfish is coexisting with sea anemone derry fish has eyes the fish is swimming the fish can not swim backwards the newfish child class successfully overrode the __init__(and swim_backwards(methods of the fish parent classwhile also inheriting the swim(method of the parent class page
12,252
with the super(functionyou can gain access to inherited methods that have been overwritten in class object when we use the super(functionwe are calling parent method into child method to make use of it for examplewe may want to override one aspect of the parent method with certain functionalitybut then call the rest of the original parent method to finish the method the super(function is most commonly used within the __init__(method because that is where you will most likely need to add some uniqueness to the child class and then complete initialization from the parent to see how this workslet' modify our clownfish child class since clownfish are typically blue in colorlet' add color variable to the __init__(methodbut then maintain the rest of the parent class' variables and parametersclass clownfish(fish)def __init__(self,color="blue")self color=color #super(clownfishself__init__(selfor super(__init__(selfwe have overridden the __init__(method in the clownfish child classproviding different implementation of the __init__(that is already defined by its parent class fish within the __init__(method of our clownfish class we have explicitly invoked the __init__(method of the fish class by using the following syntax #super(clownfishself__init__(selfor super(__init__(selfbecause we have overridden the method now we can invoke the initialized variables of the parent class and also make use of the unique child variable let' use this in an instance of clownfishexampleclass fishdef __init__(selfnamenoofeyes= last_name="fish")self name=name self noofeyes noofeyes self last_name last_name def swim(self)print("the fish is swimming "class clownfish(fish)page
12,253
self color=color #super(clownfishself__init__(selfsuper(__init__(selfdef live_with_anemone(self)print("the clownfish is coexisting with sea anemone "casey clownfish(casey name="caseyprint(casey name casey last_name +has ",casey noofeyes ,"eyes"print("color is "+casey colorcasey swim(casey live_with_anemone(outputcasey fish has eyes color is blue the fish is swimming the clownfish is coexisting with sea anemone the output shows that the object casey of the clownfish child class is able to make use of both the child-specific __init__(variable color while also being able to call the fish parent __init__(variables of first_namelast_nameand noofeyes the built-in python function super(allows us to utilize parent class methods even when overriding certain aspects of those methods in our child classes multiple inheritance just like ++one class can acquire properties from more than one base classes or parent classes in python this is called multiple inheritances in multiple inheritancesthe features of all the parent classes are inherited into the derived class/child class the syntax for multiple inheritances is the same as single inheritance multiple inheritances allow programs to reduce redundancybut it can also introduce certain amount of complexity as well as ambiguityso it should be done with thought to overall program design page
12,254
class fishdef community(self)print(" am inside fish class"class mammaldef protect_mammal(self)print(" am inside mammal class "class goldfish(fishmammal)def protect_gf(self)print(" am inside goldfish class "obj=goldfish(creating an object of goldfish class obj community()obj protect_mammal(obj protect_gf(the fish class has method called community(that prints one lineand the mammal class has method called protect_mammal(that prints another line then we call both classes into the inheritance tuple this means that goldfish is inheriting from two-parent classes the object obj is set as goldfish object and can use the methods in both parent classes when we run the programwe'll see the following outputoutputi am inside fish class am inside mammal class am inside goldfish class the output shows that methods from both parent classes were effectively used in the child class multiple inheritances allow us to use the code from more than one parent class in child class if the same method is defined in multiple parent methodsthe child class will use the method of the first parent declared in its tuple list multilevel inheritance one can inherit form derived class too this is called multilevel inheritance in multilevel inheritancefeatures of the base class and the derived class is inherited into the new derived class page
12,255
class base#statement class derived (base)#statement class derived (derived )#statement herederived is derived from baseand derived is derived from derived so finally all the features of base class and derived class are present in derived class exampleclass fishdef community(self)print(" am inside fish class"class mammal(fish)def protect_mammal(self)print(" am inside mammal class "class goldfish(mammal)def protect_gf(self)print(" am inside goldfish class "obj=goldfish(obj community()obj protect_mammal(obj protect_gf(outputi am inside fish class am inside mammal class am inside goldfish class data encapsulation encapsulation hides the implementation details of class from other objects the aim of using encapsulation is that the data inside the object should only be accessed through public interface if we want to use the data stored in an object to perform an action or calculate derived valuewe define method associated with the object which does this page
12,256
name of the variable with single underscoreyou can define protected variables in python and also by using double underscore '__ in front of the variable or function name you will be able to define private members exampleclass persondef __init__(self)self fname 'aseempublic variable self __lname 'patel#private variable #outside class person(print("my name is " fnameprint("my last name is " __lnameoutputmy name is saman traceback (most recent call last)file " :/users/osou- /pycharmprojects/myfirstpythonprogramprogram py"line in print("my last name is ", __lnameattributeerror'personobject has no attribute '__lnamein this example accessing public variables outside the classthe definition is possible but cannot access private variable outside the class but we can access this private variable __lname by accessing it through function inside the class person as followexampleclass persondef __init__(self)self fname 'aseemself __lname 'pateldef printpersonname(self)return self fname +self __lname person(print("my name is ", fnameprint( printpersonname()page
12,257
my name is aseem aseem patel in the previous programthe private variable was not possible to access outside the class but herethe private variable __lname was get called inside the method printpersonname(and this method was accessed by the object of person class let' sum up in this unit we learnt about different features of object-oriented features of python programming like classobjectinheritancemethod overloadingconstructordestructorencapsulationsuper function we also learnt about data abstraction which keeps data safe and secure and how to make code reusable using inheritance we also explored the various characteristics of classes and objects and also several terminologies related with it we have also seen the pros and cons of object-oriented programming python is highly object-oriented and understanding these concepts carefully will help you lot in different field references programming with python by the open university of sri lankadepartment of electrical and computer engineering page
12,258
unit structure learning objective introduction syntax error runtime errors semantic errors syntax errors exceptions exception handling catching specific exceptions in python the except clause with multiple exceptions python the try/finally statement raising an exception user-defined exceptions let' sum up references page
12,259
learning objective this unit introduces you to the different kinds of errors that can occur in program and how to distinguish among them in order to track them down quicker the three types of errors that will be discussed in this unit aresyntax errorsruntime errors and semantic errors the latter part of this unit will discuss the definition of exception and the importance of handling it using appropriate techniques the objective of this unit is toidentify the possibilities where programs can lead to unexpected outcomes describe the techniques used to distinguish among the type of errors describe the errors and exceptions handling mechanisms in python write robust code using appropriate error handling techniques introduction programmers must be always mindful of possible errors that may arise in their programs examples abounda function may not receive arguments that it is designed to accepta necessary resource may be missingor connection across network may be lost when designing programone must anticipate the exceptional circumstances that may arise and take appropriate measures to handle them there is no single correct approach to handling errors in program python interpreter handles errors by terminating immediately and printing an error messageso that programmers can address issues as soon as they arise in any caseprogrammers must make conscious choices about how their programs should react to exceptional conditions different kinds of errors occur in program and it is important to distinguish among them in order to track them down more quickly the following are the three types of error that occurs in python programs syntax error runtime error semantic error syntax error syntax errors are produced by python when it is translating the source code into byte code they usually indicate that there is something wrong with the syntax of the program exampleomitting the colon at the end of def statement yields the somewhat redundant message syntaxerrorinvalid syntax syntax errors are usually easy to fix once you figure out what they are unfortunatelythe error messages are often page
12,260
syntaxerrorinvalid tokenneither of which is very informative on the other handthe message does tell you where in the program the problem occurred actuallyit tells you where python noticed problemwhich is not necessarily where the error is sometimes the error is prior to the location of the error messageoften on the preceding line runtime errors runtime errors are produced by the interpreter if something goes wrong while the program is running most runtime error messages include information about where the error occurred and what functions were executed examplean infinite recursion eventually causes the runtime error "maximum recursion depth exceeded semantic errors semantic errors are problems with program that runs without producing error messages but does not do the right thing examplean expression may not be evaluated in the order you expectyielding an incorrect result in some wayssemantic errors are the hardest to debugbecause the interpreter provides no information about what is wrong only you know what the program is supposed to do the first step is to make connection between the program text and the behavior you are seeing you need guess about what the program is actually doing for example num num num averagenum +num +num / print ('the average of the three numbers is:',averageoutputthe average of the three numbers is but the output of the actual calculation should bethe average of the three numbers is thereforethe output of the program stated above is incorrect because of the order of operations in arithmetic in order to rectify this problemthe following parenthesis should be addedaverage(num +num +num )/ page
12,261
num num num averagenum +num +num / print ('the average of the three numbers is:',averageoutputthe average of the three numbers is this example gives you an idea of how program may not give you an error but yet logically be incorrect syntax errors exceptions syntaxerror occurs when you try to run syntactically invalid python codethat iswhen you're asking python to execute code that is not actually python code when this happensthe code is not executed at allnot even those lines that are syntactically valid this is very different from an exceptionan exception occurs when there is an error during execution of syntactically valid python code in python terminologyan exception is raised to illustrate thislet' define an unsafe functionthat isa function that can easily result in an exception def oneover( )print /icalling oneover( results in zerodivisionerror ( special kind of exceptionbecause dividing any number by is not allowedexampledef oneover( )print /ioneover( outputzerodivisionerrordivision by zero exception handling an exception can be handled by an enclosing try statement try statement consists of multiple clausesthe first begins with try and the rest begin with excepttry statement with an except clause the try and except block in python is used to catch and handle exceptions python executes code following the try statement as "normalpart of the program the page
12,262
in the preceding try clause in order to handle the exceptiontry and except block is used single try statement can have multiple except statement due to multiple python exceptionprogram can throw an exception in appropriate section syntaxtryexcept as the is always executed immediately when the try statement is executed suites of the except clauses are only executed when an exception is raised during the course of executing the examplewhile truetryx int(input("please enter number")break exceptprint("oopsthat was no valid number try again "outputplease enter numbera oopsthat was no valid number try again please enter numberx oopsthat was no valid number try again please enter number process finished with exit code this kind of try-except statement catches all the exceptions that occur using this kind of try-except statement is not considered good programming practice thoughbecause it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur page
12,263
in the previous examplewe did not mention any exception in except clause this is not good programming practice as it will catch all exceptions and handle every case in the same way we can specify which exceptions an except clause will catch try clause can have any number of except clause to handle them differently but only one will be executed in case an exception occurs examplewhile truetryx int(input("please enter number")break except valueerrorprint("oopsthat was no valid number try again "exampletryx / except zerodivisionerror as eprint('handling 'type( ) = outputhandling it is good practice to specify which exceptions should be caught for examplethis program triggers zerodivisionerror error when called with and typeerror called it with str or some other value that doesn' work in numeric division thereforewe can specify that we want to catch only those two exceptionsand in addition specify that we want to keep the exception object as the variable the except clause with multiple exceptions an except clause may name multiple exceptions as parenthesized tuple we can use tuple of values to specify multiple exceptions in an except clause examplewhile truetrynum int(input("enter the number ")re /num except valueerrorprint("value is not int type"page
12,264
except zerodivisionerrorprint("don' use zero"break print("result is ",reoutputenter the number result is enter the number result is enter the number don' use zero enter the number value is not int type process finished with exit code in above example you can understand that the error throws in particular exception block one single exception block can handle multiple exception types syntax except exception exception exampletrynum int(input("enter the number ")re /num except (valueerrorzerodivisionerrorprint ("something is wrong"elseprint ("result is ",reoutputenter the number result is enter the number something is wrong enter the number something is wrong we can see that one exception block is handling two type of exceptions page
12,265
you can use finallyblock along with tryblock the finally block is place to put any code that must executewhether the try-block raised an exception or not syntax try#run this action first exceptrun if exception occurs finally #always run this code exampletrynum int(input("enter the number ")re /num exceptprint ("something is wrong"elseprint ("result is ",refinallyprint ("finally program ends"outputenter the number result is finally program ends enter the number something is wrong finally program ends enter the number something is wrong finally program ends the finally-block is executed once the try-block is complete and any raised exceptions have been handled infect finally block will run even if new exception is raised raising an exception in python programmingexceptions are raised when corresponding errors occur at run timebut we can force specified exception to occur using the keyword raise to trigger exceptions explicitlyyou can code raise statements page
12,266
raise raise instance of class raise make and raise instance of class raise reraise the most recent exception exampleval int(input("enter the number ")tryif val == raise ioerror("hello"except ioerrorprint ("an exception is raisedelseprint ("value is not "outputenter the number value is not enter the number an exception is raised if you enter value equal to then if block will raise the exception by using raise keyword the except block will handle that exception user-defined exceptions programs may name their own exceptions by creating new exception class exceptions should typically be derived from the exception classeither directly or indirectly exception classes can be defined which do anything any other class can dobut are usually kept simpleoften only offering number of attributes that allow information about the error to be extracted by handlers for the exception when creating module that can raise several distinct errorsa common practice is to create base class for exceptions defined by that moduleand subclass to create specific exception classes for different error conditions exampleclass myerror(exception)def __init__(selfvalue)self value value tryraise myerror("ohh"except myerrorprint("my exception occurred"outputmy exception occurred page
12,267
built-in exceptions in this examplethe default __init__(of exception has been overridden the new behaviour simply creates the value attribute this replaces the default behaviour of creating the args attribute in tryblock exception is raised explicitly by using raise keyword the exception is caught by except block exampledefine python user-defined exceptions class error(exception)pass class valuetoosmallerror(error)pass class valuetoolargeerror(error)pass number while truetryi_num int(input("enter number")if i_num numberraise valuetoosmallerror elif i_num numberraise valuetoolargeerror break except valuetoosmallerrorprint("this value is too smalltry again!"print(except valuetoolargeerrorprint("this value is too largetry again!"print(print("congratulationsyou guessed it correctly "outputenter number this value is too largetry againenter number this value is too smalltry againenter number congratulationsyou guessed it correctly page
12,268
the objective of this study unit is to introduce the types of errors and the techniques to distinguish among them in order to resolve these errors in the first part of this unitwe discuss definitions of errors and the techniques commonly used to identify such errors in the latter part of the unit we discuss error handling which gives an overview of what exceptions are and the techniques to handle them efficiently you also get to know about user-defined exceptions that are supported by python references programming with python by the open university of sri lankadepartment of electrical and computer engineering page
12,269
unit structure learning objective introduction what is file file formats support by python file operations opening file closing file read and write files read the file as single string read the file line by line writing file searching through file python pickle let' sum up references page
12,270
learning objective in this we start to work with files secondary memory/files are not erased even when the power is turned off or in the case of usb flash drivethe data we write from our programs can be removed from the system and transported to another system we will primarily focus on reading and writing text files such as those we create in text editor introduction most of the programs we have seen so far are transient in the sense that they run for short time and produce some outputbut when they endtheir data disappears if you run the program againit starts with clean slate other programs are persistentthey run for long time (or all the time)they keep at least some of their data in permanent storage ( hard drivefor example)and if they shut down and restartthey pick up where they left off examples of persistent programs are operating systemswhich run pretty much whenever computer is onand web serverswhich run all the timewaiting for requests to come in on the network one of the simplest ways for programs to maintain their data is by reading and writing text files in this we start to work with files secondary memory/files is not erased even when the power is turned off or in the case of usb flash drivethe data we write from our programs can be removed from the system and transported to another system we will primarily focus on reading and writing text files such as those we create in text editor later we will see how to work with database files which are binary filesspecifically designed to be read and written through database software any program you write will involve readingwritingor manipulating data for this reasonit' especially useful to know how to handle different file formatswhich store different types of data for exampleconsider python program that checks list of users for access control your list of users will likely be stored and saved in text file perhaps you are not working with textbut instead have program that does financial analysis in order to do some number crunchingyou will likely have to input those numbers from saved spreadsheet regardless of your applicationit is almost guaranteed that inputting or outputting data will be involved page
12,271
handle after brief introduction to file formatswe'll go through how to openreadand write text file in python what is filea file is simply resource for storing information on computer files are stored in directories on hard driveand because they retain their data after the computer is shut downthey are persistent storage mechanisminstead of temporary storage such as ram file can contain any kind of data files are normally used to store data and information likeconfiguration settings of program simple data such as contact names against the phone numbers imagespicturesphotosetc file formats support by python python is super accommodating and canwith relative easehandle number of different file formatsincluding but not limited to the followingtxtplain text file(txt filestores data that represents only characters (or stringsand excludes any structured metadata csvcomma-separated values file uses commas (or other delimitersto structure stored dataallowing data to be saved in table format htmlhypertext markup language file stores structured data and is commonly used with most websites jsonjavascript object notation is simple and efficient formatmaking it one of the most commonly used formats to store and transfer data in this unitwe will focus on the txt file format file operations python handles file using set of in-built functions some of the functions areopen(and close()read()readline(and many more some of the basic operations for file handling are given below opening file working with file readwrite and append closing file opening file the text file is sequence of characters stored on permanent medium like hard driveflash memoryor cd-rom page
12,272
with the file syntaxfile object open(file_name [access_mode]file_namerepresents the file name that you want to access access_modedeterminesin which mode the file has to be openedi readwriteappendetc examplepath=" :\\myfirstpythonprogram\\aseem txtdays_file open (path,' 'in this examplewe have created string variable to store this information in our programwe have created the path variable and set the variable to the aseem txt path we only want to read from the file "aseem txt"so we can use the 'rmode then we use the open(function to open the "aseem txtfile and assign it to the variable days_file the file may be opened in one of the following modesfile mode rwarb wb ab rbwbaboperations open for read open for write (truncateopen for write (appendopen for read/write open for read/write (truncateopen for read/write (appendopen for binary read open for binary write (truncateopen for binary write (appendopen for read/write open for read/write (truncateopen for read/write (appendpage
12,273
after performing all file operations of the python filewe need to close it by using the close(function the close(function return true on success or false on failure syntaxfile object close(examplepath=" :\\myfirstpythonprogram\\aseem txtdays_file open (path,' 'days_file close(read and write files since our file has been openedwe can now manipulate it ( read from itthrough the variable we assigned to it python provides three related operations for reading information from file we'll show how to use all three operations as examples that you can try out to get an understanding of how they work suppose we have text file named "aseem txthaving contain as follows read the file as single string syntaxfile object read(read(returns the entire contents of the file as single string examplepath' :\\myfirstpythonprogram\\aseem txtdays_file open (path,' 'print(days_file read()days_file close(outputaseem kumar patel odisha state open university page
12,274
readline(returns the next line of the filereturning the text up to and including the next newline character more simply putthis operation will read file lineby-line syntaxdays_file readline(examplepath' :\myfirstpythonprogram\\aseem txtdays_file open (path,' 'print(days_file readline()days_file close(outputaseem kumar patel once we read line with the readline operation it will pass to the next line so if we were to call this operation againit would return the next line in the file examplepath' :\myfirstpythonprogram\\aseem txtdays_file open (path,' 'print(days_file readline()print(days_file readline()days_file close(outputaseem kumar patel odisha state open university read the file line by line the last operationreadlines(returns list of the lines in the filewhere each item of the list represents single line syntaxdays_file readlines(examplepath' :\myfirstpythonprogram\\aseem txtdays_file open (path,' 'print(days_file readlines()days_file close(output['aseem kumar patel \ ''odisha state open university \ ''sambalpurodisha 'page
12,275
read using one of the read operationsit cannot be read again for exampleif you were to first run days_file read(followed by days_file readlines(the second operation would return an empty string thereforeanytime you wish to read from file you will have to first open new file variable examplepath' :\\users\\osou- \\pycharmprojects\\myfirstpythonprogram\\aseem txtdays_file open (path,' 'print(days_file read()print("+++++++++++++++++++++++++"print(days_file readline()print("+++++++++++++++++++++++++"print(days_file readlines()days_file close(outputaseem kumar patel odisha state open university sambalpurodisha ++++++++++++++++++++++++++++++++++++++++++++++++[writing file writing to text file is similar to reading from the file when opening the file two choices are availableeither to append or to truncate the file appending to the file leaves any content already within the file untouched while truncating the file removes any content already within the file important to noteif new_days txt already existed before opening the file its old contents would have been destroyedso be careful when using the 'wmode syntaxfile object write(dataexamplepath' :\\myfirstpythonprogram\\aseem txtdays="hello worlddays_file open (path,' 'print(days_file write(days)days_file open (path,' 'print(days_file read()days_file close(page
12,276
an example of writing list to file with each list item on new line is given below list of data values to be outputted alist [ 'one''two''three''four''five''six''seven''eight''nine''ten'open the file for writing datafile open('aseem txt'' 'loop through each item in the list and write it to the output file for eachitem in alistdatafile write(str(eachitem)+'\ 'datafile open('aseem txt',' 'print(datafile readlines()close the output file datafile close(output[' \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ ''one\ ''two\ ''three\ ''four\ ''five\ ''six\ ''seven\ ''eight\ ''nine\ ''ten\ 'if we change the mode from "wto "aappend mode then the new content will be added with the existing content let' see the below example for better understanding examplelist of data values to be outputted alist [ ,datafile open('aseem txt',' 'print("data in aseem txt file before append operation"print(datafile readlines()open the file for writing datafile open('aseem txt'' 'for eachitem in alistdatafile write(str(eachitem)+'\ 'datafile open('aseem txt',' 'print("data in aseem txt file after appeand operation"page
12,277
close the output file datafile close(outputdata in aseem txt file before appeand operation ['aseem patel\ ''odisha state open university'data in aseem txt file after append operation ['aseem patel\ ''odisha state open university \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ '' \ ' searching through file when you are searching through data in fileit is very common pattern to read through fileignoring most of the lines and only processing lines which meet particular condition we can combine the pattern for reading file with string methods to build simple search mechanisms for exampleif we wanted to read file and only print outlines which started with the prefix "from:"we could use the string method starts with to select only those lines with the desired prefixexamplefhand open('aseem txt',' 'print("data in aseem txt file"print(fhand read()print("data in aseem txt file after search"fhand open('aseem txt',' 'for line in fhandif line startswith('from:')print(lineoutputdata in aseem txt file fromzqian@osou ac in fromrjlowe@osou ac in frmstephen marquard@osou ac in fromlouis@osou ac in frozqian@osou ac in fromrjlowe@osou ac in data in aseem txt file after search fromzqian@osou ac in fromrjlowe@osou ac in page
12,278
fromrjlowe@osou ac in python pickle text files are convenient because you can readwrite and append them with any text editorbut they are limited to storing series of character sometimes you may want to store more complex information like listdictionary here we will use python pickle python pickle is used to storing more complex data like listdictionary python pickle module is used for serializing and de-serializing python object structure any object in python can be pickled so that it can be saved on disk what pickle does is that it "serializesthe object first before writing it to file pickling is way to convert python object (listdictetc into character stream the idea is that this character stream contains all the information necessary to reconstruct the object in another python script the pickle module is used for implementing binary protocols for serializing and de-serializing python object structure picklingit is process where python object hierarchy is converted into byte stream unpicklingit is the inverse of pickling process where byte stream is converted into an object hierarchy dumps(this function is called to serialize an object hierarchy loads(this function is called to de-serialize data stream exampleimport pickle skill ["python""java""php"pickle_file open("pick dat","ab"pickle dump(skill,pickle_fileaa=open("pick dat",'rb'db pickle load(aaprint(dbpickle_file close(output['python''java''php'page
12,279
import pickle def storedata()initializing data to be stored in db aseem {'key''aseem','name''aseem patel''age' ,'pay' siba {'key''siba','name''siba panda''age' ,'pay' database db {db['aseem'aseem db['siba'siba it' important to use binary mode dbfile open('examplepickle','ab'sourcedestination pickle dump(db,dbfiledbfile close(def loaddata()for reading also binary mode is important dbfile open('examplepickle','rb'db pickle load(dbfilefor keys in dbprint(keys,'=>',db[keys]dbfile close(if __name__ ='__main__'storedata(loaddata(outputaseem ={'key''aseem''name''aseem patel''age' 'pay' siba ={'key''siba''name''siba panda''age' 'pay' page
12,280
in this unitwe went through how to handle and manipulate plain text files in python now you can openreadwriteand close files in pythonand you can continue working with your own data in python references python for informatics by charles severance page
12,281
unit structure unit structure introduction operations using numpy why numpy instead of lists importing numpy how to install numpy in pycharm common functions of numpy simple program using numpy array how numpy is better than lists in terms of memory management how numpy is faster and more convenient than lists in terms of time operations on arrays array arithmetic arithmetic operations aggregation let' sum up references page
12,282
introduction numpy (pronounced num-pie and acronym for 'numerical pythonor 'numeric python'is popular scientific library for python that gives developeracademicor scientist tools to work with high-level mathematical functions as well as multi-dimensional arrays and matrices it is blessing for integrating cc+and fortran tools it also provides numerous functions for fourier transform (ftand linear algebra python has an integer typea float typeand complex typehoweverthis is not enough for scientific computing andfor this reasonnumpy has lot more data types with varying precisiondependent on memory requirements the built-in data types of python discussed in the previous part are powerful and flexible enough for many programming tasks howeverin sciencewe often want to do computations on collection of numerical data suppose we have five participantsfor each of which we have an age and weightand we want to compute their body mass index (bmiin matlabwe can use vector of weights and vector of length and operate on thoseelement-wise the closest thing to vector in python would be howeverthe data type does not allow such element-wise operations as you might rememberoperators such as '+and '*perform concatenations and replications of listswhereas operators such as '/and '-do not work at allthe numpy package is the workhorse of data analysismachine learningand scientific computing in the python ecosystem it vastly simplifies manipulating and crunching vectors and matrices some of python' leading package relies on numpy as fundamental piece of their infrastructure (examples include scikitlearnscipypandasand tensorflowbeyond the ability to slice and dice numeric datamastering numpy will give you an edge when dealing and debugging with advanced use cases in these libraries operations using numpy using numpya developer can perform the following operations mathematical and logical operations on arrays fourier transforms and routines for shape manipulation operations related to linear algebra numpy has in-built functions for linear algebra and random number generation why numpy instead of listsone might think of why one should prefer arrays in numpy instead we can create lists having the same data type if this statement also rings bell then the following reasons may convince youpage
12,283
array stored as the list will require more space as compared to arrays they are speedier to work with and hence are more efficient than the lists they are more convenient to deal with we will learn about these points in more details in later part of this unit importing numpy before going details on numpy let' try to understand how to write simple python program using numpy firstlyyou need to import the numpy library importing numpy can be done by running the following commandimport numpy as np it is general approach to import numpy with alias as 'npif an alias is not provided then to access the functions from numpy we shall write numpy function to make it easier an alias 'npis introduced so we can write np function so just write the above statement in python file and run it if it shows any error message then we need to install numpy in our system examplenumpyexample py import numpy as np outputimport numpy as np modulenotfounderrorno module named 'numpyif we get such type of message then our numpy is not installed in the system the first step is to install the numpy package into the system how to install numpy in pycharm step- open the pycharm ide as follows page
12,284
goto file->setting goto file optionpresent at the top of the pycharm and click on setting option page
12,285
in setting project:projectname -project interpreter-go to setting wizard and select projectprojectname option where you will get two option project interpreter and program structure choose the first option "project interpreterand click on "+symbol present in the right top corner as shown in the below figure step- then it will show you an available packages wizard on the screen type numpy in the search box and click on install package button after whilethe numpy package will be get installed page
12,286
if it will show you screen like above then numpy is installed in your system successfully and you are ready to start writing python program using numpy common functions of numpy here have listed few important functions that are used with numpy very frequently functions tasks array create numpy array ndim dimension of the array shape size of the array (number of rows and columnssize total number of elements in the array dtype type of elements in the arrayi int character reshape reshapes the array without changing the original shape resize reshapes the array alsochange the original shape arrange create sequence of numbers in an array itemsize size in bytes of each item diag create diagonal matrix vstack stacking vertically hstack stacking horizontally simple program using numpy array you can create numpy array by passing python list to it and using "np array()in this casepython creates the array we can see on the right herepage
12,287
import numpy as np np array([ , , , , , , , , ]print(aoutput[ notice that in np array square brackets are present absence of square bracket introduces an error to print the array we can use print(alistex py items [ , , , , , , , , print(itemsoutput[ in the abovewe have written two different programs one is using numpy and another is using list initiallyboth of the programs look the same even the output is the same but numpy is had more advantage over lists especially based on speed and memory allocation there are often cases when we want numpy to initialize the values of the array for us numpy provides methods like ones()zeros()and random random(for these cases we just pass them the number of elements we want it to generate array array in numpy can be created in the following mannerg np array([( , , ),( , , )]alternatively np array([[ , , ],[ , , ]]page
12,288
import numpy as np np array([( , , ),( , , )]print(goutput[[ [ ]it is very simple to write array and print the dimensiontotal number of elements and shape can be ascertained by ndimsize and shape respectivelyg ndim size shape exampleimport numpy as np np array([( , , ),( , , )]print(gprint( ndim#dimension of the array print( sizetotal number of elements in the array print( shapesize of the array (number of rows and columnsprint( itemsizememory occupies by an data item print( dtypedatatype of the data items output[[ [ ] ( int here is the dimension of the arraymeans is -dimensional array is the number of elements in the array and ( , shows the number of rows and column of the matrix here bytes represent the size of each element in array and dtype returns the data types of the array which is int (integer bitspage
12,289
let' try to write program to create list and numpy to store elements and try to check how much of space it occupies in memory examplelistsex py import time import sys =range( print(sys getsizeof( )*len( )output here getsizeof(function of sys object returns the space allocated for single value and len(function returns the number of element stores in the list so when we multiply sys getsizeof( )*len( ))it returns the total space allocated to the list numpyex py import numpy as np =np arange( print( size* itemsizeoutput herein numpy example size represents the size of an individual element and itemsize returns the total number of elements in numpy array so size* itemsize returns the total space allocated to the numpy array so you can see the list "soccupies bit of space for list size whereas for numpy of the same size occupies just bits of memory this proves that numpy is better compared to lists in terms of memory management how numpy is faster and more convenient than lists in terms of time let' try to understand this with an example where we try to add to the array of the element of length and find out the time taken to perform this task using lists and numpy array page
12,290
numpylistsex py import numpy as np import sys import time size= =range(sizedefined list of size =range(sizedefined list of size =np arange((size)defined numpy array of size =np arange((size)defined numpy array of size start=time time(result=[( ,yfor , in zip( , )code to print((time time()-start)* time in milisec start=time time(result= + print((time time()-start)* time in milisec herefirstwe import the packages of python that we required in this program numpysys and time then declared variable named size which is equal to then we have defined two lists and with size and two numpy array and with the same size as and now we try to calculate the sum of both the lists and both the numpy array and also calculate the time taken to calculate the sum of lists and sum of numpy arrays and output so this is the reason why we choose the numpy array over lists operations on arrays numpy array is basically like container that holds numeric data that' all of the same data types we can create very simple numpy array as followsimport numpy as np np array([[ , , , , , ],[ , , , , , ]]page
12,291
rows and columns notice as well that all of the data are integers againin numpy arrayall of the data must be of the same data type keep in mind that numpy arrays can be quite bit more complicated as well it' possible to construct -dimensional arrays and -dimensional arrays for the sake of clarity thoughwe'll work with and -dimensional arrays in this post array arithmetic let' create two numpy arrays to showcase their usefulness we'll call them data and onesadding them up position-wise ( adding the values of each rowis as simple as typing data oneswhen started learning such toolsi found it refreshing that an abstraction like this makes me not have to program such calculation in loops it' wonderful abstraction that allows you to think about problems at higher level and it' not only addition that we can do this waythere are often cases when we want carry out an operation between an array and single number (we can also call this an operation between vector and scalarpage
12,292
it to kilometers we simply say data see how numpy understood that operation to mean that the multiplication should happen with each cellthat concept is called broadcastingand it' very useful arithmetic operations the operators +-*and *all act element-wise on arrays suppose we have two numpy array of np array([ ] np array([ ]and if we want to perform summation of these two then it is very simple just add + and you will get the result examplenumpylistsex py import numpy as np np array([ ] np array([ ]print( +boutput similarlyif we want to multiply these two array then perform * examplenumpylistsex py import numpy as np np array([ ] np array([ ]print( *boutput examplewrite python program for additionsubtractionmultiplication and division numpylistsex py import numpy as np np array([ ] np array([ ]page
12,293
print("substraction is ", -bprint("multiplication is ", *bprint("division is ", /boutputaddition is subtraction is [- - - - multiplication is division is [ we can also use to take the inner product of two flat arrays @ examplewrite python program for additionsubtractionmultiplication of matrix numpylistsex py import numpy as np np arange( reshape( , print ('first array:'print ( print ('second array: np arange( reshape( , print(bprint ('add the two arrays:print (np add( , )print ('subtract the two arrays:'print (np subtract( ,bprint ('multiply the two arrays:print (np multiply( ,boutputfirst array[[ [ [ ]second array[[ [ [ ]add the two arrayspage
12,294
[ ]subtract the two arrays[[ [ [ ]multiply the two arrays[ [ ]aggregation additional benefits numpy gives us are aggregation functionsin addition to minmaxand sumyou get all the greats like mean to get the averageprod to get the result of multiplying all the elements togetherstd to get standard deviation and plenty of others few of them are as follows numpy power(this function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array exampleimport numpy as np np array([ , , ]print ('my array is:'printa print ('applying power function:'print(np power( , print ('my second array: np array([ , , ]print ( print ('applying power function:'print (np power( , )page
12,295
my array is[ applying power function my second array[ applying power function numpy median(median is defined as the value separating the higher half of data sample from the lower half the numpy median(function is used as shown in the following program import numpy as np np array([[ , , ],[ , , ],[ , , ]]print('our array is:'print(aprint('applying median(function:'print(np median( )print('applying median(function along axis :'print(np median( ,axis= )print('applying median(function along axis :'print(np median( ,axis= )numpy mean(arithmetic mean is the sum of elements along an axis divided by the number of elements the numpy mean(function returns the arithmetic mean of elements in the array if the axis is mentionedit is calculated along it import numpy as np np array([[ , , ],[ , , ],[ , , ]]print 'our array is:print print 'applying mean(function:print np mean(aprint 'applying mean(function along axis :print np mean(aaxis print 'applying mean(function along axis :print np mean(aaxis numpy average(page
12,296
with its properties and methods object is simply collection of methods(functionsthat acts on those data data(variablesand creating classesa class is block of statement that combine data and operationswhich are performed on the datainto group as single unit and acts as blueprint for the creation of objects syntaxclass classnameoptional class documentation string #list of python class variables python class constructor #python class method definitions in class we can define variablesfunctions etc while writing function in class we have to pass atleast one argument that is called self parameter the self parameter is reference to the class itself and is used to access variables that belongs to the class
12,297
class studentdef display(self)defining method in class print("hello python"in python programming self is default variable that contains the memory address of the instance of the current class so we can use self to refer to all the instance variable and instance methods objects and creating objectsan object is an instance of class that has some attributes and behavior objects can be used to access the attributes of the class exampleclass studentdef display(self)defining method in class print("hello python" =student(#creating object of class display(#calling method of class using object outputhello python
12,298
class cardef get(self,color,style)self color=color self style=style def put(self)print(self colorprint(self stylec=car( get('brio','red' put(outputbrio red instance variable and class variableinstance variable is defined in method and its scope is only within the object that defines it every object of the class has its own copy of that variable any changes made to the variable don' reflect in other objects of that class
12,299
instances of that class instance variables are unique for each instancewhile class variables are shared by all instances examplefor instance and class variables class samplex= is class variable def get(self, ) is instance variable self = =sample( get( access attributes print( ,", ys =sample( = print( ,", youtput