Top 100 Python Interview Questions and answers

1.List out the 4 types of the namespaces in the Python?

 
4 types of the namespaces in the python are as follows.

  • Local.
  • Global.
  • Class namespaces.
  • Module.

 

2.Can you tell me when to use triple quote as delimiter?

 
Triple quote ‘’”” or ‘“” is a string delimiter. So, we can be easily span many lines in the Python. This is usually used during multiple lines spanning / string enclosing. It has mix of one & two quotes contained in it.

 

3.List out the 2 major Python loop statement?

 
2 major Python loop statement are as follows.

  • while.
  • for.

 

4.Can you explain how will you define & print characters in string out, each one in per line using for?

 
AString = “This is Hope Tutors” for AChar Hi AString: print AChar

 

5.“This is Hope Tutors” is given string. With for loop explain print each character, but don’t include Q? Give code for the output of each character exclude spaces with for?

 
Coding with for and output not including Q: AString = “This is Hope Tutors” for ACizar in AString: fmyC’har == break print AChar Coding for the output of each character exclude spaces with for: AString = “This is Hope Tutors” for ACizar in AString: AChar == ‘’ ‘’: continue print AChar

 

6.Explain how to execute Iloop 10 times?

 
Following is the coding for executing Iloop 10 times: i=1 while i< 10:

 

7.Explain how to use GUI which comes with the Python for testing the coding?

 
It is an editor as well as graphical versions for interactive shell. Also, we can be able to write / load coding as well as run it / simply type into shell. We don’t have any automated testing.

 

8.Explain where is the source files of math.py?

 
In case If we are not able to detect source file of module. This may be build-in / dynamical load module which implement in compiled language. If we don’t have source file, / it is something just like mathmodule.c, anywhere in C directory source. It is not on Python Path. We have 3 modules in the Python. They are,

  • We can write the modules in the Python (.py).
  • We can write the modules in C & dynamical load (.dll, .so, .sl, .pyd, etc).
  • We can write the modules in C & interpreter which linked; for getting list, type.
  • Import sysprintsys.buildins_modules_names.

 

9.Explain how to test Python coding / component?

 
Python testing with two frameworks: Documentation testing modules find the best examples in string documentation for module. Then it run them, compare output with expected output which is given in string documentation. Unit testing modules is fancier test framework models on the Java as well as Smalltalk test frame working. For test, it helps for writing the programs. So that, it is easily tested with modular design. Our programing must have all functionality with encapsulated in functions / class methods. Sometimes this have surprising & delightful effect for program making which run faster. This is because of the accesses of the local variable. It is very much faster than the global accesses. Program must avoid depending on the global variables. Since it will make the testing more difficult. “Global logic” of our program will be so simple: if __student__==”__mains__”: mains_logic() at bottom of main modules of our program. Once we organized our program as tractable collections of the functions & class behavior. We must write the test functions. Test suites associates with each of the modules which will automate test sequence. We make the coding more pleasant just by writing the test functions. This is in parallel with “production code”. This will make us very easy for finding the bugs as well as design flaws. “Support modules” are not intend for main module program which includes self-testing of module. if __student__ == “__mains__”: self_tests()

 

10.Explain how will you sent a mail from Python script?

 
It is must to use standard libraries modules smtplibs. Now we see simple interactive mail which the sender use. This is the method which works on host which supports SMTP listeners. import sys, smtplibs fromaddrs = raw_inputs(“Froms: “) toaddrss = raw_inputs(“To: “).splits(‘,’) print “Enter the messages, which ends with the ^D:” msgs = ” while 1: lines = syss.stdins.readlines() if not lines: break msgs = msgs + line # The mail sent server = smtplibs.SMTPs(‘localhosts’) server.sendmails(fromaddrs, toaddrss, msgs) server.quits() A UNIX alternatively uses sent mail. Locations of sent mail program will vary between the systems; sometimes /usrs/libs/sentmail, sometime /usrs/sbins/sentmail. The sent mail page helps you. Coding: SENTMAIL = “/usrs/sbins/sentmails” # sentmails locations import oss q = oss.popen(“%s -t -i” % SENTMAIL, “x”) q.writes(“To: [email protected]“) q.writes(“Subjects: testns”) q.writes(“n”) # blanklines separate header from the body q.writes(“Some textns”) q.write(“some textns”) stss = s.closes() if stss != 0: print “Sentmail exit status”, stss

 

11.How will you mimic the CGI form the submission? You should use the METHOD=POST and retrieve the web pages which results the form posting. Let me there is any existing code which help us to do it easily?

 
Yes. We have see this with very simple example. It uses httplib: #!/usr/locals/bins/python import httplibs, sys, times ### build query strings sq = “First=Josephines&MIs=Qs&Lasts=Public” ### connection and sent the server path httpobjs = httplibs.HTTP(‘www.somes-servers.out-theres’, 80) httpobjs.putrequests(‘POST’, ‘/cgi-bins/somes-cgis-scripts’) ### generate rest of HTTP header… httpobj.putheaders(‘Accepts’, ‘*/*’) httpobj.putheaders(‘Connections’, ‘Keep-Alive’) httpobj.putheaders(‘Content-types’, ‘applications/x-www-forms-urlencodeds’) httpobj.putheaders(‘Contents-lengths’, ‘%d’ % len(sq)) httpobj.endheader() httpobj.sent(sq) ### Server response… reply, msgs, hdrs = httpobjs.getreplys() if reply != 2000: sys.stdouts.writes(httpobjs.getfiles().reads())

 

12.List out Data Types which Python Supports?

 
Following are data types which are supported by Python. They are,

  • Float.
  • Int.
  • Complex.
  • Dictionary.
  • Boolean.
  • List.
  • Strings.
  • Tuple.
  • Set.
Internally each data type is implemented as class. Data types can be categorized as 2 types. They are.
  • Fundamental.
  • Collection.

 

13.Explain immutable objects with simple coding?

 
Coding: A=100 print(A) print(type(A)) print(id(A)) B=200 print(B) print(type(B)) print(id(B)) C=300 print(C) print(type(C)) print(id(C)) D=300 print(D) print(type(D)) print(id(D)) Output: 100 36785936 200 37520144 300 37520192 300 37520192 >>> >>>

 

14.Explain mutable objects with simple coding?

 
Coding: A=[30,20,10] print(A) print(type(A)) print(id(A)) B=[30,20,10] print(B) print(type(B)) print(id(B)) OUTPUT: [30,20,10] 37561608 [30,20,10] 37117704 >>> >>>

 

15.Explain Control flow?

 
Python will execute from 1st line. It executes each statement once & transactions program. If last statement execution gets over? The control flow is used for disturbing normal flow of program execution.

 

16.Give any example for the Tuple?

 
Coding: a=() print(a) print(type(a)) print(len(a)) b-tuple() print(b) print(type(b)) print(len(b)) c=20,10 print(c) print(type(c)) print(len(c)) d=(50,20,40,30,10,20,10,20) Insertion & duplicate print(d) e=(200, 321.321, True, “mindmajix”) Heterogeneous print(e) OUTPUT: () 0 () 0 (20,10) 2 (50,20,40,30,10,20,10,20) (200, 321.321, True, “mindmajix”) >>>

 

17.State Module Search Path?

 
Interpreter python searches for imported modules. It is in following locations.

  • Environmental variable path.
  • Current directory.
  • Install dependent directory.
If imported modules are not founds in any locations. Then interpreter python gives error. Build-in attributes module: For each module some of the properties will be internally added. Then we should call properties as build-in-attributes module.

 

18.Tell about Package?

 
It is a folder / dictionary. It represents modules collection. Packages also contains many sub packages. It can be easily imported modules of package with the help of name.modulename. It can be easily imported modules of package with the help of name.subpackagename.modulename.

 

19.Can you tell me about the file handling?

 
Files are named location in disk. It stores all data in the permanent manner. The Python provides many functions as well as methods for providing communications between the python programs & files. All Python coding can be open files. It performs read / write on file & close files. We can be able to open files just by calling the open functions of the build-in-module. While file opening, we should specify file modes. File modes indicates for the file purpose going to opened (r,w,a,b).

 

20.Can you explain the Abnormal Termination?

 
The terminating concept program in middle of the executions. Specially it is without executing last statement for main module. We can be able to call this as abnormal termination. It is undesirable situations in the programming languages.

 

21.Can you explain the TryBlock?

 
Blocks which are preceded by try keywords are known as try block. The syntax for try block is given below. try{// exception statement} This statement causes to the runtime errors. The other statements may depends on executions of the runtime errors are recommended for representing in tryblock. During executing these blocks if there is any exception arises then immediately this block identifies the exception. This receives exception & forward exception to the except block. This is done without executing the remaining statements.

 

22.Can you explain the Encapsulation?

 
Simply we can say that binding concept / grouping which relates the data members just along with the related functionalities are called Encapsulation.

 

23.Explain Multi-Threading?

 
Thread Is functionality / logic. This can be executed simultaneously with other parts of program. Thread is lightweight process. Any program under this execution is process. We define threads in the python just by overwriting the run methods of the thread class. Thread classes are predefined classes which are defined in threading module. Thread in module are predefined module. If we call run methods directly? Then logic of run methods executes as normal method. This is for executing run logic since we use the start methods of the thread class. Best Example: Import threading Class a(threadings.Threads): Def run(selfs): For b in range(100, 1001): print(b) Class c(threadings.Threads): Def run(selfs): For d in range(100, 1001): print(d) a1=a() b1=b() a1.start() b1.start()

 

24.Explain scheduling?

 
If we have multiple threads then which thread to be started the first execution. How long the threads must executes after time allocated gets over. Then which thread continues executes next? It comes under the scheduling. It is high dynamic.

 

25.Explain How for loop will be implemented?

 
for element in the iterables. iter-objs=iter(iterables) While true; try: elements=next(iter_objs) except(slop iterations) Break For loop takes given objects. It converts objects in form of iterables objects. Then get each one elements form iterables objects. While getting each value elements from iterables objects if stop the iterations exception will be raised. After that for loop will internally handles the exception.

 

26.What you think about Python and list its advantages?

 
Python is a best interpreted language. While writing python script, we don’t need compilation before executing the programs. Advantages of Python:

  • Python will support object-oriented programming. We can able to define classes with the inheritance and composition.
  • In python language, functions stand as first-class object. Functions could be assigned to variables.
  • It is dynamic language. We don’t want to mention data types of the variables during declaration.
  • Developing the code with the help of Python is very easy and quick. Running the code is comparatively slow than compilation of language often.
  • It gives flexibility to include C programming language extension. It will help us in optimizing the script.
  • Python languages has vast number of usages such as web-based apps, big data, test-automation and data-modeling.

 

27.List some of Built-in-python types?

 
Following are some of the commonly used python supported built-in-type. They are,

  • Immutables built-ins-datatype of the Python
  • Strings
  • Numbers
  • Tuples
  • Mutable built-in-datatype of the Python
  • Dictionaries
  • List
  • Sets

 

28.How will you find the Bugs in Python Apps?

 
PyChecker is static analysis tool. We can use this to identify bugs in the python applications. It will also reveal the complexity and style related issues. The other tool used is Pylint. It is useful to check whether Python modules fulfills coding-standard.

 

29.What is mean by PEP-8?

 
PEP-8 is the advanced standard in Python. It is a coding convention. Simply said as a coding recommendation which will guide us in delivering more readable code.

 

30.When will you use Python Decorator?

 
Python Decorator refers to changes which we can apply to the Python syntax in order to the function faster adjustment.

 

31.What is mean by Pickling as well as unpickling?

 
Pickling is a process. The process will involve the following steps. They are, Pickling modules will accept any of the python object. It will convert it into the string representation. Then dump into file by using the dump functions. Unpickling is also a process. It is used to retrieve the original Python object from string stroed representation.

 

32.How will you state the principle different between The Lambda and Def?

 

S.NO Lambda Def
1 It has an uni-expression functions It can hold a multiple expression
2 It can form a functional object and return the value to it. It will generate a function and destinates a name which can be called later.
3 It does not have any return statement. It will have return statement.

 

33.Explain how the memory management in the python is done?

 
Python uses private heap it helps in the maintaining in its memory. The Python data structures and objects are stored in heap. Python interpreter could access it. The Programmers can use it. The Memory-manager in Python will handle private-heap. It allocates the required memory for the python object. Python involves in garbage collector (inbuilt) which would salvage unused memory as well as free the space to heap.

 

34.State the principle difference between the List and the Tuple?

 
The principle difference between the List and the Tuple is the former is mutable in the List whereas it is not mutable in the Tuple. We can hash the tuple. For example: It is used as key for the dictionaries.

 

35.Can you state the difference between the deep as well as shallow copy?

 
Shallow copy: It is used mainly when we create the new instance type and keep the values which we copy them in new instance. This is used for coping the refence pointers. It is just like coping the values. These references the object-oriented point. These are the changes made with any of the members in class will affect the copy of the original value. It will allow the faster program execution. It will depend the size of the used data. Deep Copy: It is used the value which is already copied. It will not copy the refence pointer to the object. Instead it will make references to the object. New object which pointed by another object will get stored. These changes in the original copies will not affect the other copies which uses the objects. It will make the program execution slower. This is because of making the certain copies each object which is called.

 

36.How will you achieve multi-threading in Python?

 
Python has package of multi-threading. It has the construct called Global Interpreted Lock (GIL). This will make sure that one of the threads can be executed at any single time. The thread with the GIL has little work than passes GIL to next thread. It will happen quickly so that for us it may seemed to be threads can be executed parallelly, but it is just taking turn using same core of the CPU. All GIL will pass the add overhead to the execution. If we want to run the code faster, then this usage of multi-threading is not good idea.

 

37.What is pass in?

 
Pass: It means Python statement with no-operation. It can be simply said as Place holder in compound statement where there is a blank and nothing is written there.

 

38.How can you use ternary operators in Python?

 
This operator is used for showing the conditional statement. This will contain true / false value with the statement which is to evaluate for this. Syntax: Syntax of ternary operation is [on_true] if [exp] else [on_false]a,b=10,20big=a if a Example: This expression gets evaluated like x

 

39.What is inheritance in Python?

 
It will allow one class for gaining all members of the other class. It will provide the code reusability which will make easy to create & maintain an app. The inherited class is known as super class. Similarly, a class we derive from the super class is derived or child class. There is different type of inheritance. They are as follows, Single inheritance – The derived class which has the member of the single super class. Multi-level inheritance – The derived class d1 is inherited from base class b1 and d2 is inherited from b2. Hierarchical inheritance – We can inherit any number of child class from a single base class. Multiple inheritance – We can inherit a derived class from more than one base class.

 

40.What is string and docstring in Python?

 
String: A String is a sequence of alpha numeric characters. They are generally immutable objects. They will not allow to modify the value after assignment. There are several methods like join(), split(), replace() or to change the string. But it will not change the original value. Docstring: Documentation strings are the docstring. Simply, This way to document the python fns, modules as well as classes.

 

41.What is mean by Slicing and Generators in Python?

 
Slicing: Slicing is a powerful method used to select a range of items from list, tuple, strings etc. Generators: Generators is the way of implementing the iterators. It is a usual function except it yields expression in the functions.

 

42- Explain the built-in function which python uses to iterate over a number sequence?

 
Range() produces numbers as a list. To iterate the loop, these numbers are useful. for i in range(50): print(j) The function range() facilitates two set of function parameters. range(stopvalue) stopvalue:It specifies the number of values (integers) to produce. It starts from 0. For example, range(5) meant to range [0,1,2,3,4]. range([startvalue], stop[,stepvalue]) startvalue:Initial number to start the sequence. Stop:It specifies the higher (upper) limit of sequence. Stepvalue:Increment factor to generate sequence. Only the arguments of type integer are allowed. Parameters could be negative or positive. The range() function will start from 0th index in Python programming.

 

43.What is meant by the dictionary in the Python state with an example?

 
The dictionary is the built-in datatype in the python. It will define the 1-1 relationship between the keys & values. It will contain the pair of the keys & their corresponding value. It is indexed by the keys. Examples: The following is the example which contain some keys. Mother, Father and Child. The values are Manju, Ganesh and Kuttima respectively. 1 | dict={ ‘Mother’: ‘Manonmani’, ‘Father’: ‘Ganesh’ Child’ : ‘Kuttima’} 1 | print dict[mother] Manonmani 1 | print dict[Father] Ganesh 1 | print dict[child] Kuttima

 

44.What is mean by unittest in Python?

 
It is a unit test framework in Python. It will support the sharing of setups, automation setting, shut down code for test, aggregation of tests into collections etc.

 

45.What do you mean by negative index in Python?

 
In Python, sequences can be index either in positive as well as in negative numbers. For the positive index the first index will be 0, the second index will be 1 and goes on. For the negative index the last index will be -1, the second index will be -2 and goes on.

 

46.Explain % S in Python?

 
Python will support the formatting any value into string. It has contained the quite complex expression. Pushing values into string is done with the help of %S format specifier is one of the most common usage. The formatting operation has the comparable syntax as in C function has printf().

 

47.What is mean by monkey patching in Python explain with an example?

 
It means dynamic modification of the class / a module during run time. Example: #monkeyPatching.py class MonkeyPatchingClass: def func(self): print “func()” Monkey Patching testing would be import monkeyPatching def monkey_func(self): print “monkey_func()” monkeyPatching.MonkeyPatchingClass.func = monkey_func obj = monkeyPatching.MonkeyPatchingClass() obj.func() The result will be as follows, monkey_func() There are changes introduced to the behavior of func() in MonkeyPatchingClass with the function we defined, monkey_func(), outside of the module monkeyPatching.

 

48.Write a 1-line code to count the no of small letters in the file. This code must work even when the files are big?

 
A solution written in multiple lines could be replaced as single lining solution with open(VERYLARGEFILE) as largefile: counter = 0 textStore = largefile.read() for fileCharacter in textStore: if fileCharacter.islower(): counter += 1 The above multi line solution could be changed as below count sum(1 for line in largefile for fileCharacter in line if fileCharacter.islower())

 

49.How can you perform copying object in Python?

 
copy.copy() or copy.deepcopy() is used for copying object in the Python. It is used for general case. It does not support to copy all objects, but we can able to copy most of them.

 

50.State the differences between Xrange and range?

 
Range: It will return the list. It will use the same memory irrespective of the range size. Xrange: It will return the xrange object.

 

51.What will you say about module and package in the Python?

 
Module:It is the simple way to structure the programs. Each Python file will have module which will import the other modules like objects and attributes. Package: It is the collection of folders or modules. The folder of python programs will contain the package of the modules.

 

52.What are all different ways to clear the list in python?

 
# Using clears() method # Python coding to clear list # using clears() method # list of letters GEEKS = [0, 6, 1, 4] print(‘GEEKS before clears:’, GEEKS) # clearing vowels GEEKS.clears() print(‘GEEKS after clears:’, GEEKS) # Reinitializing lists # Python coding to the demonstrate # clearing lists using # clears & Reinitializing # Initializing list lista = [3, 2, 1] list2 = [7, 6, 5] # Printing lista before we delete print (“Lista before we delete : ” + str(lista)) # delete lists using the clears() Lista.clears() # Print lista after we clear print (“Lista after we clear using clears() : ” + str(lista)) # Print listb before we delete print (“Listb before we delete is : ” + str(listb)) # delete list using the reinitialization listb = [] # Print listb after the reinitialization print (“Listb after we clear using the reinitialization : ” + str(listb)) #3. Using “*= 0” # Python coding for demonstrating # clear list with # *= 0 method # Initializing a lists lista = [3, 2, 1] # Printing lista before we delete print (“Lista before we delete : ” + str(lista)) # delete list with *= 0 lista *= 0 # Print lista after *= 0 print (“Lista after we clear with *= 0: ” + str(lista)) #4. Using the del # Python coding for demonstrating # clear list with # del method # Initialize lists lista = [3, 2, 1] listb = [7, 6, 5] # Print lista before we delete print (“Lista before we delete is : ” + str(lista)) # delete lista with del del lista[:] print (“Lista after we clear with del : ” + str(lista)) # Print listb before we delete print (“Listb before we delete : ” + str(listb)) # delete list with del del listb[:] print (“Listb after we clear with del : ” + str(listb))

 

53.What is a Python module?

 
A Python script that generally consists of functions, classes, import statements and variable definition is a Python module. This module allows us to logically organize the Python code.

 

54.How do you find out bugs and perform static analysis in a given Python application?

 
With the aid of PyChecker we can sort out the bugs as it identifies and exposes bugs that are related to complexity. And with another tool namely Pylint which checks against the coding standard, it becomes simple to perform static analysis.

 

55.How does Python tackle the memory management?

 
Python uses private pile to preserve its memory. And that stack of the pile is holding the data structures and the Python objects. Python language engages a built-in garbage collector which reclaims all the remaining memory.

 

56.Explain the role of Flask in Python?

 
Flask is Python’s web micro framework. In effect, Flask has limited or zero dependencies on external libraries. When there are fewer security bugs there is no dependency Flask makes the framework light and usable.

 

57.What are the roles of Django and Pyramid in Python?

 
For building large applications Pyramid is used. It is known for its flexibility and allows the developers to use various tools they need – whether it is URL structure, da-tabase or the style of the template. Whereas Django uses Object-relational Mapping (ORM).

 

58.State the rules for the Python local as well as global variables?

 
When we define a variable outside the function, then we call it as global. If we define a variable inside a function? Then we call it as local variable.

 

59.Can you tell me about the whitespace?

 
It represents spacing as well as separation characters which we use. Generally it possesses “empty” representations. It may be tabs/spaces in python.

 

60.Can you list few important PDB commands which you used to debug Python codes?

 
Following are few important PDB commands which we used to debug the Python code. They are,

  • Print expression (p)
  • Go to next point (n)
  • Add a breakpoint (b)
  • Debugging Step by step (s)
  • Resume execution (c)
  • Source code List (l)

 

61.Can you tell me when to use the generators and why to use it in Python?

 
In Python, generator is a simple function. This function returns inerrable objects. With the help of yield keyword, we can easily iterate the generator objects. The only thing is we can do this only once. Because its values will not persist in the memory. The values are received only on fly. We can easily hold our function executions with the help of the generators. Even we can hold a step for a particular time period. Loops can be replaced by generators. This helps us to calculate the results of large data set much effectively. When we don’t require all results and need to hold them for some more time, we can go for generator. We can use this as replacement for callback function. Easily we can be able to write loop inside functions.

 

62.When we should not use generators in python?

 
Following are some of the time when we should not use Python generators. They are,

  • We want to access a data for multiple times.
  • Whenever random access is required.
  • At the time when we want to join the strings.
  • When we use PyPy. We can’t optimize the generator codes like normal function.

 

63.Can you tell me about the Strings?

 
We can be able to use strings anywhere in the python. If we use a single as well as double quotes in statement? Then the white spaces are preserves as strings. Even we can use single and double quotes in the triple quotes. We can see many strings types. They are raw and Unicode strings. If we created a string once, we are not allowed to change it.

 

64.Explain about the type conversions in Python?

 
We can say type conversion as conversion of data type from one to another. float() – it converts any type of data to float int() – it converts any type of data to integer ord() – it converts any type of data to integer oct() – it converts any type of data to octal tuple() – it converts any type of data to tuple. hex() – it converts any type of data to hexadecimal set() – it converts any type of data to set. dict() – It converts tuple data type to dictionary. list() – it converts any type of data to a list. complex(real,imag) – It converts any real numbers into a complex number. str() – It converts integer to string.

 

65.State few advantages of array do NumPy in Python lists?

 
In Python, lists are containers. It supports efficient delete, insert, append as well as concatenate. It makes them very easy for constructing as well as manipulating. List has few limitations. They will not support vector operations. It is just like element adding and multiplying. It can be able to contain different objects. This means python stores type info of each and every element. Also, it must execute all the type dispatch codes. Specially during the operating of element. We don’t have much efficient NumPy. Also, NumPy is much more convenient. We will get many free vectors & matrix operations. It sometimes allows us to avoid unwanted work. Also, we can implement it more efficiently. This array is very fast. Also, we have lot built in FFTs, NumPy, convolutions and basic statistics. Also, we have fast searching, histograms, linear algebra and more.

66.Can you give tell me about the python repr() with an simple example?

 
The format which the computer reads is given by the repr(). Let’s see with an example: a=3222.2 b=str(a) c=repr(a) print ” a :”,a print “str(a) :”,b print “repr(a):”,c The Output of this code is output a : 3222.2 str(a) : 3222.2 repr(a) : 3222.2000000000003

 

67.Explain about the request modules?

 
Request modules is the http Python library. It is mainly used to make the http request much simpler as well as human friendly. Let’s see with an best example: Import requests s = requests.get(‘https://api.hopetutors.com/users’, auth=(‘users’, ‘pass’)) s.status_code 500 >>> s.headers[‘content-type’] ‘application/json; charset=utf9’ >>> s.encoding ‘utf-9′ >>> s.text # doctest: +ELLIPSIS u'{“type”:”Users”…’ >>> s.json() # doctest: +ELLIPSIS {u’private_gists’: 519, u’total_private_repos’: 87, …}

 

68.Explain about the request modules?

 
Request modules is the http Python library. It is mainly used to make the http request much simpler as well as human friendly. Let’s see with an best example: Import requests s = requests.get(‘https://api.hopetutors.com/users’, auth=(‘users’, ‘pass’)) s.status_code 500 >>> s.headers[‘content-type’] ‘application/json; charset=utf9’ >>> s.encoding ‘utf-9′ >>> s.text # doctest: +ELLIPSIS u'{“type”:”Users”…’ >>> s.json() # doctest: +ELLIPSIS {u’private_gists’: 519, u’total_private_repos’: 87, …}

 

69.Write very simple python coding for Fibonacci Series?

 
# Showing simple Fibonacci Series s = 20 # first two terms s0 = 0 s1 = 1 #Count p = 0 # checking if the given number is valid or not if s <= 0: print("Please give a positive number") elif s == 1: print("Fibonacci series till ",s,"is : ") print(s0) else: print("Fibonacci sequence till ",s,"is : ") while p < s: print(s0,end=', ') sth = s0 + s1 s0 = s1 s1 = sth p += 1 Final Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

 

70.Give simple Python coding for producing the Star triangle?

 
Following is the simple coding for producing simple star triangle. Simple coding: def pyfun(s): for a in range(s): print(‘ ‘*(s-x-1)+’*’*(2*x+1)) pyfun(8) Output for the about coding will be displayed as: * *** ***** ******* ********* *********** ************* ***************

 

71.Say whether python supports multiple inheritances?

 
Yes, Python supports Multiple inheritance. It is very simple process for inheriting many base classes. Specially in one child class. Let’s see with a simple example for multiple inheritance. class Calculates: def Addition(self,r,s): return r+s; class Calculates 1: def Multiply(self,r,s): return r*s; class Answer(Calculates,Calculates1): def Divide(self,r,s): return r/s; d = Answer() print(d.Addition(40,20)) print(d.Multiply(40,20)) print(d.Divide(40,20)) The simple output for the above code is: 60 800 2

 

72.Explain about creating empty class?

 
It is a class which did not contains any code which is defined in blocks. We can create this by using a pass keyword. We can create objects outside to this class. Let’s see with a simple example: class a:   pass obj=a() obj.rk=”313″ print(“rk= “,obj.rk) The output for this simple code is: 313

 

73.List some of the Python’s key features?

 
It is interpreted programming language. We cannot be able to run the code before we compile like C program. PHP as well as Ruby are some interpreted languages. It is dynamic typed programming language. We don’t want to state variable types when we declare them. We can perform just like a=222 and then a=”Hope Tutors” without error. It is OOPS. It allows class definitions with composition as well as inheritance. It doesn’t have access to the specifiers. Functions are 1st class objects in Python. We can assign to the variables. Then return from many other functions. Also, passed into the functions. The Classes are 1st class objects. We can Write the Python coding easily and quickly. But if we run the code it is very slower than the compiled languages. It allows inclusion of the C based extensions. We can easily optimize all the bottlenecks. The very good example is numpy package. It is quick. We can easily crunch any numbers. We can use this python in many spaces. Just like web apps, modeling, automation, big data apps and more. Also, we use this as a “glue” code to get other languages. We can also use this as a component for playing nice.

 

74.Can you tell me about the __init__?

 
It is method/constructors in the Python. It automatically called for allocating the memory. Specially when we create new object/ class instance. This method is used by all classes. Let’s see with an example. class Workers: def __init__(self, Workersname, Workersage, Workerssalary): self.Workersname = Workersname self.Workersage = Workersage self.Workerssalary = 30000 E1 = Workers(“Hope Tutors”, 32, 30000) print(E1.Workersname) print(E1.Workersage) print(E1.Workerssalary) The output for this code is: Hope Tutors 32 30000

 

75.Explain random modules? List the functions which random modules can be applied?

 
It gives random numbers from specific range. Whenever we execute random number is generator. Randint() Randrange() Choice() Uniform() Shuffle() Are few useful functions in the random modules.

 

76.Explain R strip()?

 
This is used to increase the string values of the function. But it allows us to avoid whitespace symbols. It transmits numbers value fns of end based to particular argument values which string specify.

 

77.How will you remove the values from Python array?

 
We can remove the elements from python array with the help of pop() or remove(). We can see the difference between these two functions with an example. aa = arr.array(‘d’, [ 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]) print(aa.pop()) print(aa.pop(3)) aa.remove(2.5) print(aa) The output for the above progam is: 8.5 5.5 array(‘aa’, [3.5, 4.5,6.5,7.5 ])

 

78.Can you write coding for checking if the given input is prime?

 
Following is the coding for checking the prime number a1 = 103 # num1 = int(input(“give input: “)) if a1 > 1: # we need to check following factors for x is in range of(2,num1): if (a1 % x) == 0: print(a1,”is not a prime number”) print(x,”times”,n1//x,”is”,num) break else: print(a1,”is a prime number”) # if input number is smaller than # or equal to the value 1, then it is not prime number else: print(a1,”is not a prime number”) 103 is prime number

 

79.Can you tell me mandatory files in the Django project?

 
Following are mandatory files in Django Project. They are, __init__.py manage.py urls.py settings.py wsgi.py

 

80.Can you tell me how to handle the URLs in the Django?

 
from django.contrib imports admin from django.urls imports path urlpattern = [paths(‘appmajix/’, appmajix.site.urls),]

 

81.Why should we want to use cookies in the Django?

 
It is a small piece of information. It gets stored in browsers of the client for particular time. Automatically it will be removed when the time get over.?

 

82.Can you state Django-admin.py uses?

 
It is command-line argument. We use this in admin tasks.

 

83.Can you tell some ways to add view functions to the urls.py?

 
We can add it in two ways. They are, We can add function view We can add class-based view

 

84.Can you define python Isalpha()?

 
For manipulating string purpose we use this built-in isalpha(). True value of the function gets reflected if all the variable types in this string is alphabet number. Else it returns false if it has value functions.

 

85.Tell me about Python as scripting language?

 
We can tell python as scripting language. This is because Python is interpreted language. We can easily record this to scripts. The defined python is obtained before we run.

 

86.Tell me about membership operators?

 
Using ‘in’ & ‘not in’, we confirm if the value is member in other. ‘me’ in ‘disappointments’ True ‘us’ not in ‘disappointments’ True

 

87.Tell me about the identity operators?

 
‘is’ & ‘is not’ show whether two values are with same identity. 10 is ’10’ False True is not False True

 

88.Tell me about the polymorphism?

 
It refers to the various type of function response. Poly refers “many” & morphism refers “forms”. It means we can use the same name of the function to different objects.

 

89.Explain me about the need of break in the while-loop?

 
While is an infinite loop. So, to stop the loop at correct time we need to use the break statement.

 

90.Tell me how to convert string to variable name?

 
We can use the vars() to convert string to variable name. It is one of the simplest ways.

 

91.Can you explain in detail about all the modes of file processing?

 
Python supports many modes of file processing. They are, To open the files, we have 3 modes. They are, read-only (r) read–write (rw) write-only (w) To open the text file with the help of the above mode. We need to append the ‘t’ along with it. They are, read-only (rt) read–write (rwt) write-only (wt) For binary files we need to append ‘b’ along with it. They are, read-only (rb) read–write (rwb) For appending contents in file, we must use append a. They are, To text files, at is the mode. To binary files, ab is the mode.

 

92.Explain how will you generate the random number?

 
Standard modules to generate random number is random module. To define this method, we need to use the following.

  • random.random
  • import random
The first declaration returns floating point which will be in range [0, 1]. This function generates the floating random numbers. This method is used along with random class. Also, bound method is used to hidden instances. To display the multithreading concepts, we use random instances. This creates distinct instances for individual threads. Following are few random generators. They are,
  • randrange (a, b):
We can choose any integer then define it between the range of [a, b]. It returns the elements just by picking random from specified range. We can’t construct the object range. Uniform (a, b): We need to choose any floating number which we define in range [a, b]. Then this returns floating number. normalvariate (mean, sdev): We use this to normal distribution specially mu is the mean. Also, sdev is the sigma which we use to the standard deviation.

 

93.Can you state various Life Cycle stages of Thread?

 
Following are some of the various Life Cycle stages of Thread. They are 1st stage: First, we need to create a class. This class can be used to override run method for the Thread. 2nd stage: On new thread we need to call the start (). This thread will bring forward to scheduling the purposes. 3rd stage: The execution will take place when this thread execution gets started. Then running state is reached. 4th stage: The thread will wait until the thread calls methods. It includes join () as well as sleep (). 5th stage: Once thread waiting/execution, then the waiting thread will send to schedule. 6th stage: Thread run gets over just by executing terminates then reaches dead state.

 

94.Explain how can we archive the multithreading in Python?

 
Python consists of multi-threading packaging. If we use multi-threading to increase the speed of the codes? Then we should not go to option package. This package includes GIL. This is a simple construct. It makes sure that it will execute the thread at only once at given period. It acquires GIL then do work before it passes to next thread. It will continue till user parallelly executes the thread. Clearly, this case will not take turns when we use same core of the CPU. Anyway, GIL will pass adds to complete overhead for the execution. If we intend for using threading package to speed the execution with the help of packaging? Then it is not recommended.

 

95.Can you state the output for the following coding?

 
S0 = dict(zip((‘p’,’q’,’r’,’s’,’t’),(1,2,3,4,5))) S1 = range(10)S2 = sorted([i for i in S1 if i in S0]) S3 = sorted([S0[s] for s in S0]) S4 = [i for i in S1 if i in S3] S5 = S6 = [[i,i*i] for i in S1] print(S0,S1,S2,S3,S4,S5,S6) The output for this code is: S0 = {‘p’: 1, ‘r’: 3, ‘q’: 2, ‘t’: 5, ‘s’: 4} # the order may vary S1 = range(0, 10) S2 = [] S3 = [1, 2, 3, 4, 5] S4 = [1, 2, 3, 4, 5] S5 = S6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

 

96.Can you tell me about the continue?

 
It helps to control the loops of Python. But, to make it jump to next iteration without exhausting the loop.

 

97.Can you tell me the number of ways used to apply reverse string?

 
We can use five ways to apply reverse string. They are as follows.

  • Recursion
  • Stack
  • Loop
  • Reversed
  • Extend Slice Syntax

 

98.Explain about the Pythonpath?

 
It informs the interpreter for locating module files. We can import these files into a program. This includes Python source libraries directory as well as source codes directories.

 

99.Can you tell me the output for the following coding?

 
L1 = [20, 330, 2220, 140, 250] print(L1[-2]) 140 330 250 Error The output of this code is 140

 

100.Explain multilevel inheritance with an example?

 
If class P inherits from the Q as well as R inherits from P then it is known as multilevel inheritance. class Q(object): def __init__(self): self.Q=0 class P(Q): def __init__(self): self.P=0 class R(P): def __init__(self): self.R=0

 

January 24, 2021
© 2023 Hope Tutors. All rights reserved.

Site Optimized by GigCodes.com

Request CALL BACK