Python Interview Questions

What Is Python?
Python is an interpreted, 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.

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.

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.

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

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[:]

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.

Is There An Equivalent Of C’s “?:” Ternary Operator?

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’.

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 seq[-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.

How Do I Apply A Method To A Sequence Of Objects?
Use a list comprehension:
result = [obj.method() for obj in List]

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 datatype.
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 accessor methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats.

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

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).

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.

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__’:
__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)

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

How Do I Delete A File?
Use os.remove(filename) or os.unlink(filename);

How Do I Copy A File?

The shutil module contains a copyfile() function.

How Do I Run A Subprocess With Pipes Connected To Both Input And Output?
Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2(“command”)
output = fromchild.readline()

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.

Leave a Reply