Python Interview Questions

Get Technical Answers for Python Interview Questions by Python Developer Experts, Advanced Technical Questions for Freshers and Experience Persons. Get Free Practical Test

1. What Is Python?

Python is an interpreter, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

2. Is There A Tool To Help Find Bugs Or Perform Static Analysis?


PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style.

Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning


3. What Are The Rules For Local And Global Variables In Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.

Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Subscribe to our youtube channel to get new updates..!


4. How Do I Share Global Variables Across Modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

x = 0 # Default value of the 'x' configuration setting

Import config

config.x = 1

Import config

Import mod

Print config.x

Python Training Certification

Weekday / Weekend Batches


5. How Do I Copy An Object In Python?

In general, try copy.copy () or copy.deepcopy () for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

Newdict = olddict.copy ()

Sequences can be copied by slicing:

new_l = l [:]

6. How Can I Find The Methods Or Attributes Of An Object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

7. Is There An Equivalent Of C's "?:" Ternary Operator?


8. How Do I Convert A Number To A String?

To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'.

9. What's A Negative Index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of sew [-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

10. How Do I Apply A Method To A Sequence Of Objects?

Use a list comprehension:

Result = [obj.method () for obj in Li

11. What Is A Class?

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a data type.

A class can be based on one or more other classes, called its base class (es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessory methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, Outlook Mailbox that handle various specific mailbox formats.

12. What Is A Method?

A method is a function on some object x that you normally call as Methods are defined as functions inside the class definition:

Class C:

Def meth (self, arg):

Return arg*2 + self. Attribute

13. What Is Self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

14. How Do I Call A Method Defined In A Base Class From A Derived Class That Overrides It?

If you're using new-style classes, use the built-in super() function:

Class Derived (Base):

Def meth (self):

Super (Derived, self).meth ()

If you're using classic classes: For a class definition such as class Derived (Base): ... you can call method meth () defined in Base (or one of Base's base classes) as Base. Meth (self, arguments...). Here, Base. Meth is an unbound method, so you need to provide the self argument.

15. How Do I Find The Current Module Name?

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:

Def main():

Print 'Running test...'


If __name__ == '__main__':

Main ()

__import__ ('x.y.z') returns



For more realistic situations, you may have to do something like

m = __import__(s)

For i in s.split (".")[1:]:

m = getattr (m, i)

16. Where Is the (,, Etc.?) Source File?

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

1. Modules written in Python (.py);

2. Modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);

3. Modules written in C and linked with the interpreter; to get a list of these, type:

Import sys

Print sys.builtin_module_names

17. How Do I Delete A File?

Use os.remove (filename) or os.unlink (filename);

18. How Do I Copy A File?

The shutil module contains a copy file () function.

19. How Do I Run A Sub process With Pipes Connected To Both Input And Output?

Use the popen2 module. For example:

Import popen2

From child, to child = popen2.popen2("command")

tochild.write ("inputn")

tochild.flush ()

Output = fromchild.readline ()

20. How Do I Avoid Blocking In The Connect () Method Of A Socket?

The select module is commonly used to help with asynchronous I/O on sockets.

21. Are There Any Interfaces To Database Packages In Python?


Python 2.3 includes the buddy package which provides an interface to the Berkeley library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python.

22. How Do I Generate Random Numbers In Python?

The standard module random implements a random number generator. Usage is simple:

Import random

Random. Random ()

This returns a random floating point number in the range [0, 1).

23. Can I Create My Own Functions In C?

Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.

24. Can I Create My Own Functions In C++?

Yes, using the C compatibility features found in C++. Place extern "C" { ... } around the Python include files and put extern "C" before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.

25. How Can I Execute Arbitrary Python Statements From C?

The highest-level function to do this is PyRun_SimpleString () which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including Syntax Error).

26. How Can I Evaluate An Arbitrary Python Expression From C?

Call the function PyRun_String () from the previous with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value.

27. How Do I Interface To C++ Objects From Python?

Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.

28. How Do I Make Python Scripts Executable?

On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python. File) and gives that file type an open command that runs the interpreter (D: Program FilesPythonpython.exe "%1" %*). This is enough to make scripts executable from the command prompt as ''. If you'd rather be able to execute the script by simple typing 'food' with no extension you need to add .py to the PATHEXT environment variable.

On Windows NT, the steps taken by the installer as described above allow you to run a script with '', but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important.

The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line:

@setlocal enable extensions & python -x %~f0 %* & go to :EOF

29. How Do I Debug An Extension?

When using GDB with dynamically loaded extensions, you can't set a breakpoint in your extension until your extension is loaded.

In your .gdbinit file (or interactively), add the command:

Br _PyImport_LoadDynamicModule

Then, when you run GDB:

$ Gdb /local/bin/python

Gdb) run

Gdb) continue # repeat until your extension is loaded

Gdb) finish # so that your extension is loaded

Gdb) br myfunction.c:50

Gdb) continue

30. Where Is Freeze For Windows?

"Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.

Submit an interview question


Request for more information


Python tutorial for beginners

5th April | 08:00 AM

150 Registered

servicenow developer
Praneetha is a Post Graduate in Computer Science from Andhra University .She is currently working as an IT developer at hkr And she has great experience includes both IT development and operational roles. Connect with her also on LinkedIn and Twitter. Thank you

To Top