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 state...
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 ...
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 - reu...
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_profile...
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...
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 - i...
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 part...
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 comprehe...
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 grou...
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 func...
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 pa...
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 as...
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 character...
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 starti...
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 ...
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 st...
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 t...
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 com...
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 an...
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 managementthreadsstringsi...
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 ...
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 ...
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 do...
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 tho...
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...
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 tas...
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 i...
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...
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 sh...
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 ...
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__employ...
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 ...
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 i...
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/bi...
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 p...
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 additi...
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 ...
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 outsi...
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 numberoutpu...
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 i...
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 beca...
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("{i...
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 childclas...
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 noofeye...
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 "cl...
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 clow...
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 go...
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 noofeye...
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...
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 ...
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 ...
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 mamma...
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 ...
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 featur...
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 pa...
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 ...
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 pre...
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 p...
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 ...
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 ...
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 bloc...
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 ("somethi...
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 ...
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 examp...
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 handl...
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 s...
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 storag...
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...
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 bee...
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 ...
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- \\pycha...
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 i...
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 search...
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 mor...
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...
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...
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...
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 un...
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 ...
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 t...
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 ...
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 ...
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 t...
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=...
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 ...
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 arr...
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 nu...
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 ...
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 arra...
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 c...
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 instan...
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...
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