PYTHON INTERVIEW QUESTIONS AND ANSWERS

What are the key features of Python?

  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages includePHP and Ruby.
  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string"without error
  • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’spublic, private), the justification for this point is given as “we are all adults here”
  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number crunching it does isn’t actually done by Python
  • Python finds use in many spheres – web applications, automation, scientific modelling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.

What is the difference between deep and shallow copy?

 Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

How is Multithreading achieved in Python?

  1. Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
  2. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  3. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
  4. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.

How can the ternary operators be used in python?

The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.

Syntax:

The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y

Example:

The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.

What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

How Python is interpreted?

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

How memory is managed in Python?

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.

What are the tools that help to find bugs or perform static analysis?

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

What is the difference between list and tuple?

The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result you cannot change the value of the references. However, you can change the objects if it is mutable.

What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

How is memory managed in Python?

  1. Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
  2. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
  3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.

Explain Inheritance in Python with an example.

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  1. Single Inheritance – where a derived class acquires the members of a single super class.
  2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  3. Hierarchical inheritance – from one base class you can inherit any number of child classes
  4. Multiple inheritance – a derived class is inherited from more than one base class.

Explain what Flask is and its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.

What is the usage of help() and dir() function in Python?

Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. 

  1. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.
  2. Dir() function: The dir() function is used to display the defined symbols.

Whenever Python exits, why isn’t all the memory de-allocated?

  1. Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed.
  2. It is impossible to de-allocate those portions of memory that are reserved by the C library.

On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object.

What is Python good for?

Python is a high-level general-purpose programming language that can be applied to many different classes of problems.

The language comes with a large standard library that covers areas such as string processing like regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing, logging, profiling, parsing Python code, and operating system interfaces like system calls, file systems, TCP/IP sockets.

How does the Python version numbering scheme work?

Python versions are numbered A.B.C or A.B.

  • A is the major version number. It is only incremented for major changes in the language.
  • B is the minor version number, incremented for less earth-shattering changes.
  • C is the micro-level. It is incremented for each bug fix release.

Not all releases are bug fix releases. In the run-up to a new major release, ‘A’ series of development releases are made denoted as alpha, beta, or release candidate.

  • Alphas are early releases in which interfaces aren’t finalized yet; it’s not unexpected to see an interface change between two alpha releases.
  • Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs.
  • Alpha, beta and release candidate versions have an additional suffix.
  • The suffix for an alpha version is “aN” for some small number N,
  • The suffix for a beta version is “bN” for some small number N,
  • And the suffix for a release candidate version is “cN” for some small number N.

In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0.

You may also find version numbers with a “+” suffix, e.g. “2.2+”. These are unreleased versions, built directly from the subversion trunk. In practice, after a final minor release is made, the subversion trunk is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”.

Where is math.py (socket.py, regex.py, etc.) source file?

If you can’t 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 you may not have the source file or it may be something like mathmodule.c, somewhere in a C source directory (not on the Python Path).

There are (at least) three kinds of modules in Python:

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

How do I make a Python script executable on UNIX?

You need to do two things:

  • The script file’s mode must be executable and the first line must begin with “#!” followed by the path of the Python interpreter. The first is done by executing chmod +x scriptfile or perhaps chmod 755 ‘script’ file.
  • The second can be done in a number of ways.

The most straightforward way is to write:

#!/usr/local/bin/python

As the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the “env” program. Almost all UNIX variants support the following, assuming the python interpreter is in a directory on the users $PATH:

#! /usr/bin/env python

Don’t do this for CGI scripts. The $PATH variable for CGI scripts is often minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user’s environment is so full that the /usr/bin/env program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):

  1. #! /bin/sh
  2. “””:”
  3. exec python $0 ${1+”$@”}
  4. “””

The minor disadvantage is that this defines the script’s __doc__ string. However, you can fix that by adding:

__doc__ = “””…Whatever…”””

Why don’t my signal handlers work?

The most common problem is that the signal handler is declared with the wrong argument list. It is called as:
handler (signum, frame)
So it should be declared with two arguments:
def handler(signum, frame):

How do I test a Python program or component?

Python comes with two testing frameworks:

The documentation test modulefinds examples in the documentation strings for a module and runs them, comparing the output with the expected output given in the documentation string.
The unit test moduleis a fancier testing framework modeled on Java and Smalltalk testing frameworks.

For testing, it helps 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 your program is organized as a tractable collection of functions and class behaviors, you should write test functions that exercise the behaviors.

A test suite can be associated with each module which automates a sequence of tests.
You 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.

How do I find undefined g++ symbols __builtin_new or __pure_virtual?

To dynamically load g++ extension modules, you must:
Recompile Python
Re-link it using g++ (change LINKCC in the python Modules Makefile)
Link your extension module using g++ (e.g., “g++ -shared -o mymodule.so mymodule.o”).

How do I send mail from a Python script?

Use the standard library module smtplib. Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.

  1. import sys, smtplib
  2. fromaddr = raw_input(“From: “)
  3. toaddrs = raw_input(“To: “).split(‘,’)
  4. print Enter message, end with ^D:”
  5. msg =
  6. while 1:
  7. line = sys.stdin.readline()
  8. if not line:
  9. break
  10. msg = msg + line
  11. # The actual mail send
  12. server = smtplib.SMTP(‘localhost’)
  13. server.sendmail(fromaddr, toaddrs, msg)
  14. 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:

  1. SENDMAIL = “/usr/sbin/sendmail # sendmail location
  2. import os
  3. p = os.popen(“%s t i % SENDMAIL, w”)
  4. p.write(“To: receiver@example.comn“)
  5. p.write(“Subject: testn”)
  6. p.write(“n”) # blank line separating headers from body
  7. p.write(“Some textn”)
  8. p.write(“some more textn”)
  9. sts = p.close()
  10. if sts != 0:
  11. print Sendmail exit status”, sts

How can I mimic CGI form submission (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 that uses httplib:

  1. #!/usr/local/bin/python
  2. import httplib, sys, time
  3. ### build the query string
  4. qs = First=Josephine&MI=Q&Last=Public
  5. ### connect and send the server a path
  6. httpobj = httplib.HTTP(‘www.someserver.outthere’, 80)
  7. httpobj.putrequest(‘POST’, ‘/cgibin/somecgiscript’)
  8. ### now generate the rest of the HTTP headers…
  9. httpobj.putheader(‘Accept’, ‘*/*’)
  10. httpobj.putheader(‘Connection’, ‘Keep-Alive’)
  11. httpobj.putheader(‘Content-type’, ‘application/x-www-form-urlencoded’)
  12. httpobj.putheader(‘Content-length’, ‘%d’ % len(qs))
  13. httpobj.endheaders()
  14. httpobj.send(qs)
  15. ### find out what the server said in response…
  16. reply, msg, hdrs = httpobj.getreply()
  17. if reply != 200:
  18. sys.stdout.write(httpobj.getfile().read())
  19. 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.”:
  20. >>> from urllib import quote
  21. >>> x = quote(“Guy Steele, Jr.”)
  22. >>> x
  23. ‘Guy%20Steele,%20Jr.’
  24. >>> query_string = “name=”+x
  25. >>> query_string
  26. ‘name=Guy%20Steele,%20Jr.’

Why is that none of my threads are not running? How can I make it work?

As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:

  1. import threading, time
  2. def thread_task(name, n):
  3. for i in range(n): print name, i
  4. for i in range(10)

    Installation of Python 3.6.1

    Download the required 3.6.1 python, executable installer file from the www.python.org.com website.
    Installation Process:

    • Click on the downloaded executable installer
    • Click On ‘Run’
    • Click on Customize Installation
    • Click on ‘Next’
    • Select the installation location by clicking on browse button
    • Click on ‘Install’
    • Click on ‘Yes’
    • Click on ‘Close’

    Path: Path is an environment variable of operating system by using e=which we can make it available the softwares which are installed in the directory to all other directions of the operating system.

    To set Path:

    • Right click on my computer
    • Click on properties
    • Click on Advanced system setting
    • Click on advanced
    • Click on environment variables
    • Go to system variables, select ‘path’
    • Click on ‘edit’
    • Copy the installation folder location of python software in the begging of the variable value
    • Click on ‘OK’

    Now path setting is secured.

What Are The Implementation In Python Program?

Python program can be implemented by two ways

1. Interactive Mode (Submit statement by statement explicitly)
2. Batch Mode (Writing all statements and submit all statements)

In Interactive mode python command shell is required. It is available in installation of python cell.
In Interactive mode is not suitable for developing the projects & Applications
Interactive mode is used for predefined function and programs.
Example

X=1000
Y=2000
X+Y
3000
QuitX+Y
X, Y is not found.

Interactive mode is unfit for looping purpose.

Interactive Mode:

  • The concept of submitting one by one python statements explicitly in the python interpreter is known as “Interactive Mode”
  • In Order to submit the one by one python statements explicitly to the python interpreter, we use python command line shell.
  • Python command line shell is present in python software
  • We can open the python command line shell by executing python command on command prompt or terminal

Example:

  1. c:/users/mindmajix>python
  2. >>>3+4
  3. 7
  4. >>> mindmajix’*3
  5. mindmajix mindmajix mindmajix
  6. >>> x=1000
  7. >>>y=2000
  8. >>>x+y
  9. 3000
  10. >>>Quit
  11. >>>x+y
  12. c:/users/sailu>python

Error: name ‘X’ not defined

Batch Mode:
In the concept of writing the group of python statements in a file, save the file with extension .py and submit that entire file to the python interpreter is known as Batch Mode.

  • In Order to develop the python files we use editors or IDE’s
  • Different editors are notepad, notepad++, edit+,nano, VI, gedil and so on.

Open the notepad and write the following code
Example

  1. X=1000
  2. Y=2000
  3. Print(x+y, xy, x*y)

Save the file in D drive mindmajix python folder with the demo.py
Open command prompt and execute following commands

  1. Python D:/mindmajix python/Demo.py
  2. 3000
  3. 1000
  4. 2000.000

Save another method if we correctly set the path

  1. D:
  2. D:/>d mindmajix python
  3. D:/mindmajix Python>python Demo.py
  4. 3000
  5. 1000
  6. 2000.000

What  Are The Data Types Supports in Python Language?

  • 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
564 People Rated
4.4/5
993 People Rated
3.6/5
0
Shares

Leave a Reply