Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What Will Be The Output Of The Following Code class C(object): Def__init__(self): Self.x =1 C=c() Print C.x Print C.x Print C.x Print C.x

Answer»

class C(OBJECT):
Def__init__(self):
Self.x =1
C=c()
PRINT C.x
Print C.x
Print C.x
Print C.x

All the outputs will be 1

1
1
1
1

All the outputs will be 1

1
1
1
1

2.

If Given The First And Last Names Of Bunch Of Employees How Would You Store It And What Datatype?

Answer»

EITHER a DICTIONARY or just a list with FIRST and last NAMES INCLUDED in an element.

Either a dictionary or just a list with first and last names included in an element.

3.

What Is The Difference Between A Tuple And A List?

Answer»

A tuple is a list that is immutable. A list is mutable i.e. The members can be CHANGED and ALTERED but a tuple is immutable i.e. the members cannot be changed.
Other SIGNIFICANT difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
LIST2 = ["Sachin", "Ramesh", "Tendulkar"]
A tuple is defined in the FOLLOWING way
tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")

A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.
Other significant difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
list2 = ["Sachin", "Ramesh", "Tendulkar"]
A tuple is defined in the following way
tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")

4.

Explain About Pickling And Unpickling?

Answer»

Python has a standard module known as PICKLE which enables you to store a SPECIFIC object at some destination and then you can call the object BACK at later STAGE. While you are retrieving the object this process is known as unpickling. By specifying the dump function you can store the DATA into a specific file and this is known as pickling.

Python has a standard module known as Pickle which enables you to store a specific object at some destination and then you can call the object back at later stage. While you are retrieving the object this process is known as unpickling. By specifying the dump function you can store the data into a specific file and this is known as pickling.

5.

Explain About Assert Statement?

Answer»

ASSERT statement is used to assert whether something is true or false. This statement is very USEFUL when you want to check the items in the list for true or false function. This statement should be predefined because it INTERACTS with the user and RAISES an ERROR if something goes wrong.

Assert statement is used to assert whether something is true or false. This statement is very useful when you want to check the items in the list for true or false function. This statement should be predefined because it interacts with the user and raises an error if something goes wrong.

6.

What Is A Lambda Form?

Answer»

This lambda STATEMENT is USED to create a NEW FUNCTION which can be later used during the run time. Make_repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in ORDER to return them during the run time.

This lambda statement is used to create a new function which can be later used during the run time. Make_repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in order to return them during the run time.

7.

Explain About Raising Error Exceptions?

Answer»

In python programmer can raise exceptions using the raise STATEMENT. When you are using exception statement you should also specify about ERROR and exception object. This error should be related to the derived CLASS of the Error. We can USE this to specify about the length of the user name, password FIELD, etc.

In python programmer can raise exceptions using the raise statement. When you are using exception statement you should also specify about error and exception object. This error should be related to the derived class of the Error. We can use this to specify about the length of the user name, password field, etc.

8.

Explain About Indexing And Slicing Operation In Sequences?

Answer»

Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular ITEM in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if SUCCESSIVE numbers are not SPECIFIED it starts at the LAST. In python the start position is included but it stops before the end statement.

Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.

9.

Explain About The Dictionary Function In Python?

Answer»

A dictionary is a place where you will find and store INFORMATION on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that STRINGS should be PASSED as keys in python. Notice that keys are to be separated by a COLON and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.

A dictionary is a place where you will find and store information on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that strings should be passed as keys in python. Notice that keys are to be separated by a colon and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.

10.

Explain And Statement About List?

Answer»

As the name SPECIFIES list holds a list of data ITEMS in an orderly manner. SEQUENCE of data items can be PRESENT in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be ALTERED at any time.

As the name specifies list holds a list of data items in an orderly manner. Sequence of data items can be present in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be altered at any time.

11.

What Is Tuple?

Answer»

Tuples are similar to LISTS. They cannot be modified once they are declared. They are similar to STRINGS. When items are defined in parenthesis separated by commas then they are called as Tuples. Tuples are used in situations where the USER cannot change the context or application; it puts a RESTRICTION on the user.

Tuples are similar to lists. They cannot be modified once they are declared. They are similar to strings. When items are defined in parenthesis separated by commas then they are called as Tuples. Tuples are used in situations where the user cannot change the context or application; it puts a restriction on the user.

12.

Explain About Classes In Strings?

Answer»

Classes are the main feature of any object oriented programming. When you use a CLASS it CREATES a NEW type. Creating class is the same as in other programming languages but the syntax DIFFERS. Here we create an object or instance of the class followed by parenthesis.

Classes are the main feature of any object oriented programming. When you use a class it creates a new type. Creating class is the same as in other programming languages but the syntax differs. Here we create an object or instance of the class followed by parenthesis.

13.

State And Explain About Strings?

Answer»

Strings are almost used everywhere in python. When you use SINGLE and DOUBLE quotes for a statement in python it PRESERVES the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have CREATED a STRING in Python you can never change it again.

Strings are almost used everywhere in python. When you use single and double quotes for a statement in python it preserves the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have created a string in Python you can never change it again.

14.

Describe About The Libraries Of Python?

Answer»

Python library is very huge and has some EXTENSIVE LIBRARIES. These libraries help you do various THINGS involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as TWISTED, WX python, python imaging library, etc.

Python library is very huge and has some extensive libraries. These libraries help you do various things involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as Twisted, wx python, python imaging library, etc.

15.

Does Python Support Object Oriented Scripting?

Answer»

PYTHON supports object oriented programming as well as procedure oriented programming. It has FEATURES which make you to USE the program CODE for many functions other than Python. It has useful objects when it COMES to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.

Python supports object oriented programming as well as procedure oriented programming. It has features which make you to use the program code for many functions other than Python. It has useful objects when it comes to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.

16.

How Is Python Interpreted?

Answer»

PYTHON has an INTERNAL software mechanism which makes your PROGRAMMING easy. Program can run DIRECTLY from the SOURCE code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.

Python has an internal software mechanism which makes your programming easy. Program can run directly from the source code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.

17.

State Some Programming Language Features Of Python?

Answer»

Python supports many features and is used for cutting edge technology. Some of them are
1) A huge pool of data types such as lists, numbers and dictionaries.
2) Supports notable features such as classes and multiple inheritance.
3) Code can be split into modules and PACKAGES which assists in flexibility.
4) It has good support for raising and catching which assists in error handling.
5) INCOMPATIBLE mixing of FUNCTIONS, strings, and numbers triggers an error which also helps in good programming practices.
6) It has some advanced features such as generators and list comprehensions.
7) This programming language has automatic memory management SYSTEM which helps in GREATER memory management.

Python supports many features and is used for cutting edge technology. Some of them are
1) A huge pool of data types such as lists, numbers and dictionaries.
2) Supports notable features such as classes and multiple inheritance.
3) Code can be split into modules and packages which assists in flexibility.
4) It has good support for raising and catching which assists in error handling.
5) Incompatible mixing of functions, strings, and numbers triggers an error which also helps in good programming practices.
6) It has some advanced features such as generators and list comprehensions.
7) This programming language has automatic memory management system which helps in greater memory management.

18.

Explain About The Use Of Python For Web Programming?

Answer»

Python can be very well used for web programming and it also has some SPECIAL features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, WEBSERVERS, Content Management systems, Web SERVICES, Webclient programming, Webservices, etc. Many high end APPLICATIONS can be created with Python because of the FLEXIBILITY it offers.

Python can be very well used for web programming and it also has some special features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, Webservers, Content Management systems, Web services, Webclient programming, Webservices, etc. Many high end applications can be created with Python because of the flexibility it offers.

19.

Explain About The Programming Language Python?

Answer»

Python is a very easy language and can be learnt very easily than other PROGRAMMING languages. It is a DYNAMIC OBJECT oriented language which can be easily USED for software development. It supports many other programming languages and has extensive library support for many other languages.

Python is a very easy language and can be learnt very easily than other programming languages. It is a dynamic object oriented language which can be easily used for software development. It supports many other programming languages and has extensive library support for many other languages.

20.

How Do I Emulate Os.kill() In Windows?

Answer»

Use win32api:
DEF KILL(pid):
"""kill function for Win32"""
import win32api
HANDLE = win32api.OpenProcess(1, 0, pid)
RETURN (0 != win32api.TerminateProcess(handle, 0))

Use win32api:
def kill(pid):
"""kill function for Win32"""
import win32api
handle = win32api.OpenProcess(1, 0, pid)
return (0 != win32api.TerminateProcess(handle, 0))

21.

Is A *.pyd File The Same As A Dll?

Answer»

YES .

Yes .

22.

Where Is Freeze For Windows?

Answer»

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

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

23.

How Do I Debug An Extension?

Answer»

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 myscript.py
gdb) CONTINUE # repeat until your extension is loaded
gdb) finish # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue

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 myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue

24.

How Do I Make Python Scripts Executable?

Answer»

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 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' 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 'foo.py', 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 enableextensions & python -X %~f0 %* & GOTO :EOF

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 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' 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 'foo.py', 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 enableextensions & python -x %~f0 %* & goto :EOF

25.

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

Answer»

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.

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.

26.

How Can I Evaluate An Arbitrary Python Expression From C?

Answer»

CALL the function PyRun_String() from the previous question with the start symbol Py_eval_input; it parses an expression, EVALUATES it and RETURNS its value.

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

27.

How Can I Execute Arbitrary Python Statements From C?

Answer»

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

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

28.

Can I Create My Own Functions In C++?

Answer»

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.

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.

29.

Can I Create My Own Functions In C?

Answer»

Yes, you can create built-in MODULES containing functions, VARIABLES, exceptions and EVEN new types in C.

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

30.

How Do I Generate Random Numbers In Python?

Answer»

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

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

31.

Are There Any Interfaces To Database Packages In Python?

Answer»

YES.
Python 2.3 includes the bsddb PACKAGE which provides an INTERFACE to the BerkeleyDB LIBRARY. Interfaces to disk-based HASHES such as DBM and GDBM are also included with standard Python.

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

32.

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

Answer»

The select module is COMMONLY used to help with ASYNCHRONOUS I/O on SOCKETS.

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

33.

How Do I Run A Subprocess With Pipes Connected To Both Input And Output?

Answer»

USE the popen2 MODULE. For EXAMPLE:
import popen2
fromchild, tochild = popen2.popen2("COMMAND")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()

Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2("command")
tochild.write("input\n")
tochild.flush()
output = fromchild.readline()

34.

How Do I Copy A File?

Answer»

The shutil MODULE CONTAINS a copyfile() FUNCTION.

The shutil module contains a copyfile() function.

35.

How Do I Delete A File?

Answer»

USE os.remove(FILENAME) or os.unlink(filename);

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

36.

Where Is The Math.py (socket.py, Regex.py, Etc.) Source File?

Answer»

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

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

37.

How Do I Find The Current Module Name?

Answer»

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
Try:
__import__('x.y.z').y.z
For more realistic situations, you may have to do SOMETHING like
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)

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
Try:
__import__('x.y.z').y.z
For more realistic situations, you may have to do something like
m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)

38.

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

Answer»

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.

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.

39.

What Is Self?

Answer»

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

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

40.

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

Answer»

USE a LIST COMPREHENSION:
RESULT = [OBJ.method() for obj in List]

Use a list comprehension:
result = [obj.method() for obj in List]

41.

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

Answer»

No

No

42.

How Do I Copy An Object In Python?

Answer»

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

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

43.

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

Answer»

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.

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.

44.

What Is Python?

Answer»

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.

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.