Python Interview Questions and Answers Part 2

1. Can you list the four main types of namespaces in Python?

Following are the four main type of namespaces in python. They are,

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

2. When will you use the triple quotes as a delimiter?

Triple quotes ‘’”” or ‘“” are string delimiters. We can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines or enclosing a string. This has a mix of single and double quotes contained therein.

3. Can you list the two major loop statement in python?

The following are the two major loop statement in python. They are,

  • for.
  • while.

4. Using a for loop can you illustrate how you will define and print the characters in a string out, one per line?

myString = “I Love Python”

for myChar hi myString:

print myChar

 

5. “I Love Python” is the given string. Use a for loop and illustrate printing each character tip to, but not including the Q? Also give the code for print out each character except for the spaces, using a for loop?

The following code is using a for loop and printing each character tip to, but not including the Q:

inyString = “I Love Pijtlzon”

for myCizar in myString:

fmyC’har ==

break

print myChar

 

The following code is for print out each character except for the spaces, using a for loop:

inyString = I Love Python”

for myCizar in myString:

fmyChar == ‘’ ‘’:

continue

print myChar

6. How will you execute Iloop ten times?

i=1

while i < 10:

7. How will you use a GUI that comes with Python to test your code?

That is just an editor and a graphical version of the interactive shell. We can write or load the code and run it or simply type it into the shell. There is no automated testing.

 

8. Can you tell me where is math.py source file?

If we cannot able to find a source file for a module, it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case we may not have the source file, or it may be something like mathmodule.c, somewhere in a C source directory. This is not on the Python Path.

 

There are three kinds of modules in Python. They are,

 

    • Modules are written in Python (.py).
    • Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc).
    • Modules are written in C and linked with the interpreter; to get a list of these, type.
  • Import sys print sys.builtin_module_names.

9. How will you test a Python program or component?

Python comes with two testing frameworks:

The documentation test module finds examples in the documentation strings for a module. Then runs them, comparing the output with the expected output given in the documentation string.

 

The unit test module is a fancier testing framework modeled on Java and Smalltalk testing frameworks.

 

For testing, it will help to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods. And this sometimes has the surprising and delightful effect of making the program run faster because local variable accesses are faster than global accesses.

 

Furthermore, the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.

 

The “global main logic” of your program may be as simple as:

if __name__==”__main__”:

main_logic()

at the bottom of the main module of your program.

Once our program is organized as a tractable collection of functions and class behaviors, we should write test functions that exercise the behaviors.

 

A test suite can be associated with each module which automates a sequence of tests.

 

We can make coding much more pleasant by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.

 

“Support modules” that are not intended to be the main module of a program may include a self-test of the module.

 

if __name__ == “__main__”:

self_test()

Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.

 

 

10. How do you send mail from a Python script?

We must use the standard library module smtplib. Here is a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.

 

import sys, smtplib

fromaddr = raw_input(“From: “)

toaddrs = raw_input(“To: “).split(‘,’)

print “Enter message, end with ^D:”

msg = ”

while 1:

line = sys.stdin.readline()

if not line:

break

msg = msg + line

# The actual mail send

server = smtplib.SMTP(‘localhost’)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()

A UNIX-only alternative uses send mail. The location of the send mail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The send mail manual page will help you out. Here’s some sample code:

 

SENDMAIL = “/usr/sbin/sendmail” # sendmail location

import os

p = os.popen(“%s -t -i” % SENDMAIL, “w”)

p.write(“To: [email protected]“)

p.write(“Subject: testn”)

p.write(“n”) # blank line separating headers from body

p.write(“Some textn”)

p.write(“some more textn”)

sts = p.close()

if sts != 0:

print “Sendmail exit status”, sts

11. How can i mimic CGI form submission? Use METHOD=POST. I would like to retrieve web pages that are the result of posting a form. Is there existing code that would let me do this easily?

Yes. Here’s a simple example. This will use httplib:

 

#!/usr/local/bin/python

import httplib, sys, time

 

### build the query string

qs = “First=Josephine&MI=Q&Last=Public”

 

### connect and send the server a path

httpobj = httplib.HTTP(‘www.some-server.out-there’, 80)

httpobj.putrequest(‘POST’, ‘/cgi-bin/some-cgi-script’)

 

### now generate the rest of the HTTP headers…

httpobj.putheader(‘Accept’, ‘*/*’)

httpobj.putheader(‘Connection’, ‘Keep-Alive’)

httpobj.putheader(‘Content-type’, ‘application/x-www-form-urlencoded’)

httpobj.putheader(‘Content-length’, ‘%d’ % len(qs))

httpobj.endheaders()

httpobj.send(qs)

 

### find out what the server said in response…

reply, msg, hdrs = httpobj.getreply()

if reply != 200:

sys.stdout.write(httpobj.getfile().read())

 

Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name=”Guy Steele, Jr.”:

 

>>> from urllib import quote

>>> x = quote(“Guy Steele, Jr.”)

>>> x

‘Guy%20Steele,%20Jr.’

>>> query_string = “name=”+x

>>> query_string

‘name=Guy%20Steele,%20Jr.’

 

12. Can you list the Data Types Supports in Python Language?

Following are the data type supports in Python Language. They are,

 

  • Python Int.
  • Python Float.
  • Python Complex.
  • Python Boolean.
  • Python Dictionary.
  • Python List.
  • Python Tuple.
  • Python Strings.
  • Python Set.

Every data type in python language is internally implemented as a class. Python language data types are categorized into two types. They are.

 

    • Fundamental Types.
  • Collection Types.

13. Can you give an example for immutable objects?

Program:

i=1000

print(i)

print(type(i))

print(id(i))

j=2000

print(j)

print(type(j))

print(id(j))

x=3000

print(x)

print(type(x))

print(id(x))

y=3000

print(y)

print(type(y))

print(id(y))

 

Output:

1000

36785936

2000

37520144

3000

37520192

3000

37520192

>>>

>>>

 

14. Can you give an example for mutable objects?

Program:

x=[10,20,30]

print(x)

print(type(x))

print(id(x))

y=[10,20,30]

print(y)

print(type(y))

print(id(y))

 

OUTPUT:

[10,20,30]

37561608

[10,20,30]

37117704

>>>

>>>

 

15. Can you explain about the Control flow statements?

Python program execution starts from the first line. It will execute each statement only once and transactions the program. If the last statement of the program execution is over. Control flow statements are used to disturb the normal flow of the execution of the program.

 

16. Can you give an example for Tuple?

Program:

x=()

print(x)

print(type(x))

print(len(x))

y-tuple()

print(y)

print(type(y))

print(len(y))

z=10,20

print(z)

print(type(z))

print(len(z))

p=(10,20,30,40,50,10,20,10) Insertion & duplicate

print(p)

q=(100, 123.123, True, “mindmajix”) Heterogeneous

print(q)

 

OUTPUT:

()

0

()

0

(10,20)

2

(10,20,30,40,50,10,20,10)

(100, 123.123, True, “mindmajix”)

>>>

 

17. Explain about Modules Search Path?

Python interpreter search for the imported modules. This will be in the following locations.

 

  • Current directory (main module location).
  • Environment variable path.
  • Installation-dependent directory.
  • If the imported module is not found in any one of the above locations. Then python interpreter gives error.

Built-in attributes of a module:

 

  • By default, for each python module some properties are added internally. Then we call those properties as a built-in-attribute of a module

18. Can you explain about Package?

A package is nothing but a folder or dictionary. It will represent a collection of modules.

 

A package can also contain sub packages.

 

    • We can import the modules of the package by using package name.module name.
  • We can import the modules of the package by using package name.subpackage name.module name.

19. Explain about file handling?

  • File is a named location on the disk. It will store the data in permanent manner.
  • Python language provides various functions and methods to provide the communication between python programs as well as files.
  • Python programs can open the file. It will perform the read or write operations on the file and close the file.
  • We can open the files by calling open function of built-in-modules.
  • At the time of opening the file, we must specify the mode of the file.
  • Mode of the file indicates for what purpose the file is going to be opened(r,w,a,b).

20. Explain about Abnormal Termination?

This is the concept of terminating the program in the middle of its execution. This is done without executing the last statement of the main module. Simply we can call it as an abnormal termination. Abnormal termination is an undesirable situation in programming languages.

 

21. Can you explain the Try Block?

A block which is preceded by the try keyword is known as a try block.

 

The syntax for try block is given below.

 

Syntax:

try{

//statements that may cause an exception

}

 

The statements which cause to runtime errors. The other statements which depends on the execution of runtime errors statements are recommended to represent in a try block. While executing try block statement if any exception is raised then immediately try block identifies that exception. It will receive that exception and forward that exception to except block. This is done without executing remaining statements to try block.

 

22. Can you explain the Encapsulation?

Simply we can say that the concept of binding or grouping related data members along with its related functionalities is known as an Encapsulation.

 

23. Explain Multi-Threading?

Thread Is a functionality or logic. This can execute simultaneously along with the other part of the program.

 

  • Thread is a lightweight process.
  • Any program which is under execution is known as process.
  • We can define the threads in python by overwriting run method of thread class.
  • Thread class is a predefined class which is defined in threading module.
  • Thread in module is a predefined module.
  • If we call the run method directly the logic of the run method will be executed as a normal method logic.
  • In order to execute the logic of the run method as we use start method of thread class.

Example:

Import threading

Class x(threading.Thread):

Def run(self):

For p in range(1, 101):

print(p)

Class y(threading.Thread):

Def run(self):

For q in range(1, 101):

print(q)

x1=x()

y1=y()

x1.start()

y1.start()

 

24. Explain scheduling?

Among multiple threads which thread as to start the execution first. How much time the thread must execute after allocated time is over. Which thread must continue the execution next this? It will come under scheduling. Scheduling is highly dynamic.

 

25. Explain How For loop is implemented in python language?

For an element in iterable.

iter-obj=iter(iterable)

While true;

Try:

element=next(iter_obj)

except(slop iteration)

Break

 

For loop takes the given object. It will convert that object in the form of iterable object. Then gets the one by one element form the iterable object.

 

While getting the one by value element from the iterable object if stop iteration exception is raised then for loop internally handle that exception.

 

 

June 19, 2019
© 2023 Hope Tutors. All rights reserved.

Site Optimized by GigCodes.com

Request CALL BACK