100% found this document useful (1 vote)
309 views32 pages

Python Interview Questions 1

Python is an interpreted, interactive, object-oriented programming language that combines power with clear syntax. It has interfaces to system calls, libraries, and window systems, and is extensible in C/C++. Python is portable across many operating systems. Static analysis tools like PyChecker and Pylint help find bugs. Local variables in Python are implicitly global if only referenced inside a function, while global variables must be explicitly declared if assigned within a function. Modules can share global variables and objects can be copied using copy.copy() or copy.deepcopy().

Uploaded by

03sri03
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
309 views32 pages

Python Interview Questions 1

Python is an interpreted, interactive, object-oriented programming language that combines power with clear syntax. It has interfaces to system calls, libraries, and window systems, and is extensible in C/C++. Python is portable across many operating systems. Static analysis tools like PyChecker and Pylint help find bugs. Local variables in Python are implicitly global if only referenced inside a function, while global variables must be explicitly declared if assigned within a function. Modules can share global variables and objects can be copied using copy.copy() or copy.deepcopy().

Uploaded by

03sri03
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 32

1. Question 1. 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.
2. Question 2. Is There A Tool To Help Find Bugs Or Perform Static Analysis?
Answer :
Yes.
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.
Perl Scripting Interview Questions
3. Question 3. 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.
4. Question 4. How Do I Share Global Variables Across Modules?
Answer :
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:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print config.x
Perl Scripting Tutorial
5. Question 5. 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[:]
C++ Interview Questions
6. Question 6. How Can I Find The Methods Or Attributes Of An Object?
Answer :
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. Question 7. Is There An Equivalent Of C's "?:" Ternary Operator?
Answer :
No

C++ Tutorial   PHP Interview Questions


8. Question 8. How Do I Convert A Number To A String?
Answer :
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. Question 9. What's A Negative Index?
Answer :
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.
C Interview Questions
10. Question 10. How Do I Apply A Method To A Sequence Of Objects?
Answer :
Use a list comprehension:
result = [obj.method() for obj in List]
PHP Tutorial
11. Question 11. What Is A Class?
Answer :
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.
Ruby on Rails Interview Questions
12. Question 12. What Is A Method?
Answer :
A method is a function on some object x that you normally call as
x.name(arguments...). Methods are defined as functions inside the class
definition:
class C:
def meth (self, arg):
return arg*2 + self.attribute
Perl Scripting Interview Questions
13. Question 13. 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).

C Tutorial
14. Question 14. 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.
15. Question 15. 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)
Ruby Interview Questions
16. Question 16. 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
Ruby on Rails Tutorial
17. Question 17. How Do I Delete A File?
Answer :
Use os.remove(filename) or os.unlink(filename);
Django Interview Questions
18. Question 18. How Do I Copy A File?
Answer :
The shutil module contains a copyfile() function.

C++ Interview Questions


19. Question 19. 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()
Django Tutorial
20. Question 20. 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.

Lisp programming Interview Questions


21. Question 21. 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.
22. Question 22. 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).
Ruby on Rails 2.1 Tutorial
23. Question 23. 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.
R Programming language Interview Questions
24. Question 24. 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.

PHP Interview Questions


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

Lisp programming Tutorial


26. Question 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.

wxPython Interview Questions


27. Question 27. 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.

C Interview Questions
28. Question 28. 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

R Programming language Tutorial


29. Question 29. 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
Python Automation Testing Interview Questions
30. Question 30. 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.
31. Question 31. Is A *.pyd File The Same As A Dll?
Answer :
Yes .

wxPython Tutorial
32. Question 32. 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))
33. Question 33. 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.

Ruby on Rails Interview Questions


34. Question 34. 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.
35. Question 35. 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.
36. Question 36. 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.

Ruby Interview Questions


37. Question 37. 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.
38. Question 38. 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.
39. Question 39. 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.
40. Question 40. 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.

Django Interview Questions


41. Question 41. 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.
42. Question 42. 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.

Lisp programming Interview Questions


43. Question 43. 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.
44. Question 44. 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.
45. Question 45. 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.
46. Question 46. 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.
47. Question 47. 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.
48. Question 48. 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.
49. Question 49. 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")
50. Question 50. 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.
51. Question 51. 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 :
All the outputs will be 1
1
1
1
1
a
Python Basic Interview Questions
1) What is Python?
Ans: Python is a high-level and object-oriented programming language with unified
semantics designed primarily for developing apps and web. It is the core language in
the field of Rapid Application Development (RAD) as it offers options such as
dynamic binding and dynamic typing.
2) What are the benefits of Python?
Ans: The benefits of Python are as follows:
 Speed and Productivity: Utilizing the productivity and speed of Python will enhance the
process control capabilities and possesses strong integration.
 Extensive Support for Libraries: Python provides a large standard library that includes
areas such as operating system interfaces, web service tools, internet protocols, and string
protocols. Most of the programming tasks are already been scripted in the standard library which
reduces effort and time.
 User-friendly Data Structures: Python has an in-built dictionary of data structures that are
used to build fast user-friendly data structures.
 Existence of Third Party Modules: The presence of third party modules in the Python
Package Index (PyPI) will make Python capable to interact with other platforms and
languages.
 Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for
beginners to learn.
3) What are the key features of Python?
Ans: The following are the significant features of Python, and they are:
 Interpreted Language: Python is an interpreted language that is used to execute the code
line by line at a time. This makes debugging easy.
 Highly Portable: As Python can run on different platforms such as Unix, Macintosh, Linux,
Windows, and so on. So, we can say that it is a highly portable language.
 Extensible: It ensures that the Python code can be compiled on various other languages
such as C, C++ and so on.
 GUI programming Support: It implies that the Python provides support to develop graphical
user interfaces
4) What type of language is Python? Programming or
Scripting?
Ans: Python is suitable for scripting, but in general it is considered as a general-
purpose programming language.
5) What are the applications of Python?
Ans: The applications of Python are as follows:
 GUI based desktop applications
 Image processing applications
 Business and Enterprise applications
 Prototyping
 Web and web framework applications

6) What is the difference between list and tuple in Python?


Ans: The difference between tuple and list are as follows:
List  Tuple

The list is mutable (can be changed) A tuple is immutable (remains constant)

These lists performance is slower Tuple performance is faster when compared to lists

Syntax: list_1 = [20, ‘Mindmajix’, 30] Syntax: tup_1 = (20, ‘Mindmajix’, 30)

7) What are the global and local variables in Python?


Ans: Global Variables in Python: The variables that are declared outside the
function are called global variables. These variables can be accessed or invoked by
any function in the program.
Example: 
1 def v() :
2 print g
3 g = "welcome to mindmajix"
4 v()
Output:
1 Welcome to mindmajix
Local Variables in Python: The variables that are declared inside a function are
called local variables. These type of variables can be accessed only inside the
function.
8) Define PYTHON PATH?
Ans: PYTHONPATH is an environmental variable that is used when we import a
module. Suppose at any time we import a module, PYTHONPATH is used to check
the presence of the modules that are imported in different directories. Loading of the
module will be determined by interpreters.
9) What are the two major loop statements?
Ans: for and while
10) What do you understand by the term PEP 8?
Ans: PEP 8 is the Python latest coding convention and it is abbreviated as Python
Enhancement Proposal. It is all about how to format your Python code for maximum
readability.
11) How memory management is done in Python?
Ans:
 In Python memory management is done using private heap space. The private heap is the
storage area for all the data structures and objects. The interpreter has access to the private heap
and the programmer cannot access this private heap. 
 The storage allocation for the data structures and objects in Python is done by the memory
manager. The access for some tools is provided by core API for programmers to code.
 The built-in garbage collector in Python is used to recycle all the unused memory so that it
can be available for heap storage area.
12) Java vs Python
Ans: The major difference between Java and Python are as follows:
Function Java  Python

Coding In Java, we need to write a long In Python coding is simple and


code to print something. smaller when compared to Java

Syntax In Java we need to put a semicolon Whereas, in Python indentation i


at the end of the statement and also mandatory as it improves the
code must be placed in curly readability of the code.
braces.

Dynamic In Java, we need to declare the In this case, codes are dynamica
type for each variable typed and this is also known as
duck typing

Easy to use Java is not easy to use because of In Python, it is very easy to code
its larger coding and perform very easily.

Databases Java Database Connectivity In Python database access layers


(JDBC) is more popular and used are weaker when compared to
most commonly. Java.
Explore in detail differences @ Python vs Java
13) Define modules in Python?
Ans: Module is defined as a file that includes a set of various functions and Python
statements that we want to add in our application. 
Example of creating` a module: 
In order to create a module first, we need to save the code that we want in a file
with .py extension.
Save the module with module.py
1 def wishes(name):
2 Print("Hi, " + name)
14) What are the built-in types available in Python?
Ans: The built-in types in Python are as follows:
 Integer
 Complex numbers
 Floating-point numbers
 Strings
 Built-in functions

15) What are Python Decorators?


Ans: Decorator is the most useful tool in Python as it allows programmers to alter
the changes in the behavior of class or function. 
Example for Python Decorator is:
1 @gfg_decorator
2 def hi_decorator():
3     print("Gfg")
16) How do we find bugs and statistical problems in Python?
Ans: We can detect bugs in python source code using a static analysis tool named
PyChecker. Moreover, there is another tool called PyLint that checks whether the
Python modules meet their coding standards or not.
17) What is the difference between .py and .pyc files?
Ans: .py files are Python source files. .pyc files are the compiled bytecode files that
are generated by the Python compiler
18) How do you invoke the Python interpreter for interactive
use?
Ans: By using python or pythonx.y we can invoke Python interpreter. where x.y is
the version of the Python interpreter.
19) Define String in Python?
Ans: String in Python is formed using a sequence of characters. Value once
assigned to a string cannot be modified because they are immutable objects. String
literals in Python can be declared using double quotes or single quotes.
Exam
1 print("Hi")
2 print('Hi')
ple:
20) What do you understand by the term namespace in
Python?
Ans: A namespace in Python can be defined as a system that is designed to provide
a unique name for every object in python. Types of namespaces that are present in
Python are:
 Local namespace
 Global namespace
 Built-in namespace
Scope of an object in Python: 
Scope refers to the availability and accessibility of an object in the coding region.
21) How do you create a Python function?
Ans: Functions are defined using the def statement.
An example might be def foo(bar):
22) Define iterators in Python?
Ans: In Python, an iterator can be defined as an object that can be iterated or
traversed upon. In another way, it is mainly used to iterate a group of containers,
elements, the same as a list.
23) How does a function return values?
Ans: Functions return values using the return statement.
24) Define slicing in Python?
Ans: Slicing is a procedure used to select a particular range of items from sequence
types such as Strings, lists, and so on.
25) How can Python be an interpreted language?
Ans: As in Python the code which we write is not machine-level code before runtime
so, this is the reason why Python is called as an interpreted language. 
26) What happens when a function doesn’t have a return
statement? Is this valid?
Ans: Yes, this is valid. The function will then return a None object. The end of a
function is defined by the block of code is executed (i.e., the indenting) not by any
explicit keyword.
27) Define package in Python?
Ans: In Python packages are defined as the collection of different modules.
28) How can we make a Python script executable on Unix?
Ans: In order to make a Python script executable on Unix, we need to perform two
things. They are:
Script file mode must be executable and
The first line should always begin with #.
29) Which command is used to delete files in Python?
Ans: OS.unlink(filename) or OS.remove(filename) are the commands used to delete
files in Python Programming.
Example: 
1 import OS
2 OS.remove("abc.txt")
30) Define pickling and unpickling in Python?
Ans: 
Pickling in Python: The process in which the pickle module accepts various Python
objects and converts into a string representation and dumps the file accordingly
using dump function is called pickling. 
Subscribe to our youtube channel to get new updates..!
Unpickling in Python: The process of retrieving actual Python objects from the
stored string representation is called unpickling.
Check Out Python Tutorials
31) Explain the difference between local and global
namespaces?
Ans: Local namespaces are created within a function when that function is called.
Global namespaces are created when the program starts.
32) What is a boolean in Python?
Ans: Boolean is one of the built-in data types in Python, it mainly contains two
values, and they are true and false. 
Python bool() is the method used to convert a value to a boolean value.
1 Syntax for bool() method: bool([a])
33) What is Python String format and Python String replace?
Ans: 
Python String Format: The String format() method in Python is mainly used to
format the given string into an accurate output or result.
Syntax for String format() method:
1 template.format(p0, p1, ..., k0=v0, k1=v1, ...)
Python String Replace: This method is mainly used to return a copy of the string in
which all the occurrence of the substring is replaced by another substring.
Syntax for String replace() method: 
1 str.replace(old, new [, count])

34Q. Name some of the built-in modules in Python?


Ans: The built-in modules in Python are:
 sys module
 OS module
 random module
 collection module
 JSON
 Math module

35Q. What are the functions in Python?


Ans: In Python, functions are defined as a block of code that is executable only
when it is called. The def keyword is used to define a function in Python.
Example:
1 def Func():
2 print("Hello, Welcome toMindmajix")
3 Func(); #calling the function
Output: Hello, Welcome to Mindmajix

36) What are Dict and List comprehensions in Python?


Ans: These are mostly used as syntax constructions to ease the creation of list and
dictionaries based on existing iterable.
37Q. Define the term lambda?
Ans: Lambda is the small anonymous function in Python that is often used as an
inline function.

38Q. When would you use triple quotes as a delimiter?


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

39Q. Define self in Python?


Ans: In Python self is defined as an object or an instance of a class. This self is
explicitly considered as the first parameter in Python. Moreover, we can also access
all the methods and attributes of the classes in Python programming using self
keyword.  
In the case of the init method, self refers to the newer creation of the object.
Whereas in the case of other methods self refers to the object whose method was
called. 

40Q. What is _init_?


Ans: The _init_ is a special type of method in Python that is called automatically
when the memory is allocated for a new object. The main role of _init_ is to initialize
the values of instance members for objects. 
Example:
1
2 class  Student:
def _init_ (self, name, age, marks):
3 self.name = name
4 self.age = age
5 self.marks = 950
6 S1 = Student("ABC", 22, 950)
7 # S1 is the instance of class Student.
# _init allocates memory for S1.
8 print(S1.name)
9 print(S1.age)
10 print(S1.marks)
11
Output: 
1 ABC
2 22
3 950

41Q. Define generators in Python?


Ans: The way of implementing an effective representation of iterators is known as
generators. It is only the normal function that yields expression in the function. 

42Q. Define docstring in Python?


Ans: The docstring in Python is also called a documentation string, it provides a way
to document the Python classes, functions, and modules.

43Q. How do we convert the string to lowercase?


Ans: lower() function is used to convert string to lowercase.
Example:
1 str = 'XYZ'
2 print(str.lower())
Output:
1 xyz

44Q. How to remove values from a Python array?


Ans: The elements can be removed from a Python array using remove() or pop()
function. The difference between pop() and remove() will be explained in the below
example.
Example:
1 x = arr.array('d',  [ 1.0, 2.2, 3.4, 4.8, 5.2, 6.6, 7.3])
2 print(x.pop())
3 print(x.pop(3))
4 x.remove(1.0)
print(a)
5
Output: 
1 7.3
2 4.8
3 array(‘d’, [2.2, 3.4, 5.2, 6.6])

 45Q. What is Try Block?


A block which is preceded by the try keyword is known as a try block
Syntax:
1 try{
2    //statements that may cause an exception
3 }

46Q. Why do we use the split method in Python?


Ans: split() method in Python is mainly used to separate a given string.
Example:
1 x = "Mindmajix Online Training"
2 print(a.split())
Output:
1 [‘Mindmajix’, ‘Online’, ‘Training’]

47Q. How can we access a module written in Python from C?


Ans: We can access the module written in Python from C by using the following
method.
1 Module == PyImport_ImportModule("<modulename>");
48Q. How do you copy an object in Python?

Python Certification Training!


Explore Curriculum

Ans: To copy objects in Python we can use methods


called copy.copy() or copy.deepcopy().

49Q. How do we reverse a list in Python?


Ans: By using list.reverse(): we can reverse the objects of the list in Python.
 
Python Programming Interview Questions and Answers
50Q. How can we debug a Python program?
Ans:  By using the following command we can debug the Python program
1 $ python -m pdb python-script.py

51Q. Write a program to count the number of capital letters in a file?


Ans:
1 with open(SOME_LARGE_FILE) as countletter:
2 count = 0
3 text = countletter.read()
4 for character in text:
if character.isupper():
5 count += 1
6

52Q. Write a program to display the Fibonacci sequence in Python?


Ans:
1 # Displaying Fibonacci sequence
n = 10
2
# first two terms
3 n0 = 0
4 n1 = 1
5 #Count
6 x = 0
# check if the number of terms is valid
7 if n <= 0:
8    print("Enter positive integer")
9 elif n == 1:
10    print("Numbers in Fibonacci sequence upto",n,":")
11    print(n0)
else:
12    print("Numbers in Fibonacci sequence upto",n,":")
13    while x < n:
14        print(n0,end=', ')
15        nth = n0 + n1
       n0 = n1
16
17
18
       n1 = nth
19        x += 1
20
21
Output:
1 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

53Q. Write a program in Python to produce Star triangle?


Ans: The code to produce star triangle is as follows:
1 def pyfun(r):
2 for a in range(r):
3 print(' '*(r-x-1)+'*'*(2*x+1)) 
4 pyfun(9)
Output: 
1
2         *
       ***
3       *****
4      *******
5     *********
6    ***********
  *************
7  ***************
8 *****************
9

54Q. Write a program to check whether the given number is prime or


not?
Ans: The code to check prime number is as follows:
1
2 # program to check the number is prime or not
3 n1 = 409
4 # num1 = int(input("Enter any one number: "))
5 # prime number is greater than 1
if n1 > 1:
6 # check the following factors
7 for x is in range of(2,num1):
8 if (n1 % x) == 0:
9 print(n1,"is not a prime number")
10 print(x,"times",n1//x,"is",num)
break
11 else:
12 print(n1,"is a prime number")
13 # if input number is smaller than
14 # or equal to the value 1, then it is not prime number
15 else:
print(n1,"is not a prime number")
16
17
Output:
1 409 is a prime number
55Q. Write Python code to check the given sequence is a palindrome
or not?
Ans:
1
2 # Python code to check a given sequence
#  is palindrome or not
3 my_string1 = 'MOM'
4 My_string1 = my_string1.casefold()
5 # reverse the given string
6 rev_string1  = reversed(my_string1)
7 # check whether the string is equal to the reverse of it or not
if list(my_string1) == list(rev_string1):
8 print("It is a palindrome")
9 else:
10 print("It is not a palindrome")
11
Output:
1 it is a palindrome

56Q. Write Python code to sort a numerical dataset?


Ans: The code to sort a numerical dataset is as follows:
1 list = [ "13", "16", "1", "5" , "8"]
2 list = [int(x) for x in the list]
3 list.sort()
4 print(list)
Output: 
1 1, 5, 8, 13, 16

57Q. What is the output of the following code?


1 x = ['ab','cd']
2 print(list(map(list, x)))
Ans: The output of the following code is
1 [ [‘a’, ‘b’], [‘c’, ‘d’]
 

Python Coding Interview Questions & Examples


58Q. What is the procedure to install Python on Windows and set path
variable?
Ans: We need to implement the following steps to install Python on Windows, and
they are:
 First you need to install Python from https://www.python.org/downloads/
 After installing Python on your PC, find the place where it is located in your PC using the cmd
python command.
 Then visit advanced system settings on your PC and add new variable. Name the new
variable as PYTHON_NAME then copy the path and paste it.
 Search for the path variable and select one of the values for it and click on ‘edit’.
 Finally we need to add a semicolon at the end of the value and if the semicolon is not present
then type %PYTHON_NAME%.

59Q. Differentiate between SciPy and NumPy?


Ans: The difference between SciPy and NumPy is as follows:
NumPy SciPy

Numerical Python is called NumPy Scientific Python is called SciPy

It is used for performing general and efficient This is an entire collection of tools in Python mainl
computations on numerical data which is saved in used to perform operations like differentiation,
arrays. For example indexing, reshaping, sorting, and integration and many more.
so on

There are some of the linear algebraic functions For performing algebraic computations this module
present in this module but they are not fully fledged. contain some of the fully fledged operations

60Q. How do Python arrays and lists differ from each other?
Ans: The difference between Python array and Python list are as follows:
Arrays Lists

Array is defined as a linear structure that is used to List are used to store arbitrary and heterogenous da
store only homogeneous data.

Since array stores only similar type of data so it List stores different types of data so it requires huge
occupies less amount of memory when compared to amount of memory 
list.

Length of the array is fixed at the time of designing Length of the list is no fixed, and adding items in th
and no more elements can be added in the middle. middle is possible in lists.

61Q. Can we make multi-line comments in Python?


Ans: In python there is no specific syntax to display multi-line comments like other
languages. In order to display mitli-line comments in Python, programmers use triple-
quoted (docstrings) strings. If the docstring is not used as the first statement in the
present method, it will not be considered by Python parser.
Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download
Now!

62Q. What is the difference between range and xrange?


Ans: These both the methods are mainly used in Python to iterate the for loop for a
fixed number of times. They differ only when we talk regarding Python versions.
The difference between range and xrange are as follows:

Range() method Xrange() method


The xrange() method is not supported in Python3 so The xrange() method is used only in the Python
that the range() method is used for iteration in for version 2 for the iteration in for loops.
loops.

List is returned by this range() method It only returns the generator object because it doesn
produce a static list during run time.

It occupies a huge amount of memory as it stores the It occupies less memory because it only stores one
complete list of iterating numbers in memory.  number at the time in memory.

63Q. Explain how can we build or set up the database in Django?


Ans: we can make use of edit mysite/setting.py command, it is a simple Python
module consists of levels for presenting or displaying Django settings.
By default Django uses SQLite; this also makes easy for Django users in case of any
other type of installations. For example, if your database choice is different then you
need to follow certain keys in the DATABASE like default items to match database
connection settings.
 Engines: By these engines you change the database by using commands such as
‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’,
‘django.db.backends.oracle’, ‘django.db.backends.mysql’, and so on.
 Name: This represents the name of your own database. If you are familiar with using SQLite
as your database, in such case database is available as a file on your particular system.
Moreover, the name should be as a fully absolute or exact path along with the file name of the
particular file.
 Suppose if we are not using SQlite as your database then additional settings such password,
user, the host must be added.
Django mainly uses SQLite as its default database to store entire information in a
single file of the filesystem. If you want to use different database servers rather than
SQLite, then make use of database administration tools to create a new database for
the Django project.  Another way is by using your own database in that place, and
remaining is to explain Django about how to use it. This is the place in which
Python’s project settings.py file comes into the picture. 
We need to add the below code to the setting.py file:
1 DATABASE  = {
2 ‘Default’ : {
3 ‘ENGINE’ :  ‘django.db.backends.sqlite3’,
4 ‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’),
5 }}
6

64Q. List out the inheritance styles in Django?


Ans: There are three possible inheritance styles in Django, and they are:
 Proxy models: This style is mainly used for those who want to modify the Python level
behaviour of the model, without modifying the model’s fields.
 Abstract Base Classes: This inheritance style is used only when we want to make parent
class hold the data which they don’t want to repeat it again in the child class.
 Multi-table Inheritance: This inheritance style is used only when we want to subclass an
existing model and there must a database table designed for each model on its own.
65Q. How to save an image locally using Python in which we already
know the URL address?
Ans: The following code is used to save the image locally from the URL address
which we know.
1 import urllib.request
2 urllib.request.urlretrieve("URL", "local-filename.jpg")

66Q. How can we access sessions in flask?


Ans: A session will basically allow us to remember information from one request to
another. In a flask, a signed cookie is used to make the user look at the session
contents and modify them. Moreover, the user can change the session only when
the secret key named Flask.secret_key is present.

67Q. Is flask an MVC model? If yes, justify your answer by showing an


example of your application with the help of MVC pattern?
Ans: Basically, flask is a minimalistic framework that behaves the same as MVC
framework. So MVC will be perfectly suitable for the flask and we will consider the
MVC pattern in the below example.
1 from flask import Flask                
2 In this code your,
3 app = Flask(_name_)                     
4 @app.route(“/”)                               
5 Def hey():                                         
return “Welcome to Appmajix”    
6 app.run(debug = True)
7
The following code can be fragmented into
Configuration part will be,
1 In this code your,
2 app = Flask(_name_)
View part will be,
1 @app.route(“/”)                               
2 Def hey():                                         
3 return “Welcome to Appmajix”
While your main part will be,
1 app.run(debug = True)

68Q. What are the database connections in Python Flask, explain?


Ans: Database powered applications are supported by flask. The relational database
systems need to create a schema that requires piping the schema.sql file into a
SQLite3 command. So, in this case you need to install SQLite3 command on your
system to initiate and create the database in the flask.
We can request a database using flask in three ways, and they are:
 before_request(): Using this we can request database before only without passing
arguments.
 after_request(): This method is called after requesting the database and also send the
response to client.
 teardown_request(): This method is called in the cases where the responses are not
guaranteed and the exception is raised. They have no access to modify the request.

69Q. Explain the procedure to minimize or lower the outages of


Memcached server in your Python development?

Ans: The following are the steps used to minimize the outages of the Memcached
server in your Python development, and they are.
 When a single instance fails, this will impact on larger load of the database server. The client
makes the request when the data is reloaded. In order to avoid this, the code that you have
written must be used to lower cache stampedes then it will used to leave a minimal impact.
 The other way is to bring out the instance of the memcached on a new machine by using the
IP address of the lost machine.
 Another important option is to lower the server outages is code. This code provides you the
liberty to modify the memcached server list with minimal work
 Another way is by setting timeout value that will be one of the options for memcac
1 Class Student:
2 def __init__(self, name):
3 self.name = name
4 S1=Student("XYZ")
print(S1.name)
5
 hed clients to implement the memcached server outage. When the performance of the server
goes down, the client keeps on sending a request until the timeout limit is reached.

70Q. What is Dogpile effect?


Ans: This is defined as an occurrence of event when the cache expires and also
when the websites are hit with more number of requests by the client at a time. This
dogpile effect can be averted by the use of a semaphore lock. If in the particular
system the value expires then, first of all, the particular process receives the lock and
begin generating new value.
 
Python OOPS Concepts
71Q. What are the OOPS concepts available in Python?
Ans: Python is also object-oriented programming language like other programming
languages. It also contains different OOPS concepts, and they are 
 Object
 Class
 Method
 Encapsulation
 Abstraction
 Inheritance
 Polymorphism
72Q. Define object in Python?
Ans: An object in Python is defined as an instance that has both state and
behaviour. Everything in Python is made of objects.

73Q. What is a class in Python?


Ans: Class is defined as a logical entity that is a huge collection of objects and it also
contains both methods and attributes.  

74Q. How to create a class in Python?


Ans: In Python programming, the class is created using a class keyword. The syntax
for creating a class is as follows:
1 class ClassName:
2 #code (statement-suite)
Example of creating a class in Python.
Output: 
1 XYZ

75Q. What is the syntax for creating an instance of a class in Python?


Ans: The syntax for creating an instance of a class is as follows:
1 <object-name> = <class-name>(<arguments>)

76Q. Define what is “Method” in Python programming?


Ans: The Method is defined as the function associated with a particular object. The
method which we define should not be unique as a class instance. Any type of
objects can have methods.

77Q. Does multiple inheritances is supported in Python?


Ans: Multiple inheritance is supported in python. It is a process that provides
flexibility to inherit multiple base classes in a child class. 
Example of multiple inheritance in Python is as follows:
1
2 class Calculus: 
3 def Sum(self,a,b): 
return a+b; 
4 class Calculus1: 
5 def Mul(self,a,b): 
6 return a*b; 
7 class Derived(Calculus,Calculus1): 
8 def Div(self,a,b): 
return a/b; 
9 d = Derived() 
10 print(d.Sum(10,30)) 
11 print(d.Mul(10,30)) 
12 print(d.Div(10,30))
13
Output:
1 40
2 300
3 0.3333

78Q. What is data abstraction in Python?


Ans: In simple words, abstraction can be defined as hiding of unnecessary data and
showing or executing necessary data. In technical terms, abstraction can be defined
as hiding internal process and showing only the functionality. In Python abstraction
can be achieved using encapsulation.

79Q. Define encapsulation in Python?


Ans: Encapsulation is one of the most important aspects of object-oriented
programming. Binding or wrapping of code and data together into a single cell is
called encapsulation. Encapsulation in Python is mainly used to restrict access to
methods and variables.
Python Training in Bangalore

80Q. What is polymorphism in Python?


Ans: By using polymorphism in Python we will understand how to perform a single
task in different ways. For example, designing a shape is the task and various
possible ways in shapes are a triangle, rectangle, circle, and so on.

81Q. Does Python make use of access specifiers?


Ans: Python does not make use of access specifiers and also it does not provide a
way to access an instance variable. Python introduced a concept of prefixing the
name of the method, function, or variable by using a double or single underscore to
act like the behaviour of private and protected access specifiers.

82Q. How can we create an empty class in Python?


Ans: Empty class in Python is defined as a class that does not contain any code
defined within the block. It can be created using pass keyword and object to this
class can be created outside the class itself.
Example:
1 class x:
2 &nbsp; pass
3 obj=x()
4 obj.id="123"
print("Id = ",obj.id)
5
Output:
1 123

83Q. Define Constructor in Python?


Ans: Constructor is a special type of method with a block of code to initialize the
state of instance members of the class. A constructor is called only when the
instance of the object is created. It is also used to verify that they are sufficient
resources for objects to perform a specific task.
There are two types of constructors in Python, and they are:
 Parameterized constructor
 Non-parameterized constructor

84Q. How can we create a constructor in Python programming?


Ans: The _init_ method in Python stimulates the constructor of the class. Creating a
constructor in Python can be explained clearly in the below example.
1
2 class Student: 
def __init__(self,name,id): 
3 self.id = id; 
4 self.name = name; 
5 def display (self): 
6 print("ID: %d nName: %s"%(self.id,self.name)) 
stu1 =Student("nirvi",105) 
7
stu2 = Student("tanvi",106)  
8 #accessing display() method to print employee 1 information    
9
stu1.display();  
10 #accessing display() method to print employee 2 information 
11 stu2.display();
12
Output:
1 ID: 1
2 Name: nirvi
3 ID: 106
4 Name: Tanvi

85Q. Define Inheritance in Python?


Ans: When an object of child class has the ability to acquire the properties of a
parent class then it is called inheritance. It is mainly used to acquire runtime
polymorphism and also it provides code reusability.
 
Python Interview FAQs
1Q. What is the best Python IDE for beginners?
Ans: There are many IDE’s to execute Python code. But, as a beginner, the
following two IDE’s will be helpful 
 PyCharm
 Spyder
2Q. What are the cool things you can do with Python?
Ans: The following are some of the things that you can perform using Python:
 Automate tasks
 Play games
 Build a Blockchain to mine Bitcoins
 Build a chatbot interface combined with AI
3. Does Python replace Java?
Ans: Python alone can't replace Java, whereas a group of programming languages
can replace Java but JVM can't be replaced.
4. How do I prepare for Python interview?
Ans:
 First of all, learn how to write code in the white paper without any support (IDE)
 Maintain basic Python control flow
 Be confident in explaining your program flow
 Learn where to use oops concepts and generators
5. Why should you choose Python?
Ans: There is no doubt, Python is the best choice for coding in the interview. Other
than Python,  if you prefer to choose C++ or java you need to worry about structure
and syntax.
6. Can we use Python for coding in interviews?
Ans: Choosing an appropriate language to code also matters at the time of
interview. Any language can be used for coding but coding in Python is seeming less
and easy.
7. How to crack a coding interview?
Ans: It is not that easy as we usually think. Mugging up some programs and
executing the same will not work. The ideal way to crack the coding interview, you
should be proficient in writing code without the support of any IDE. Don't panic or
argue, test your code before you submit, wait for their feedback. Practising mock
interview will help. Coderbyte platform will help you in enhancing your skills.
8. Top 5 tips to crack the interview?
Ans: The following are the top 5 tips to crack Python interview:
 Building a proper profile will fetch you better results
 Setting up your portfolio might impress your interviewer
 Learn all the fundamentals of Python and OOps concepts as 90% of the interview start from
basics
 Feel free to write code pen and paper
 Apart from all the above practice is what required.
9. How can I practice code?
Ans: There are many online coding sites and platforms exclusively for practice
purpose. According to me the Ideal way of learning is by picking up a problem
statement and working on it to build your confidence levels.
In StackOverflow website, we can see 100 software developers posting their
problems.
10. How to crack my first interview?
Ans: Attending an interview as a fresher or first time is very challenging, but we are
here to support you. Learn the fundamentals of programming, practice some
available coding samples. 
>Back to top
 
 Top Python Tips and Tricks For Programmers
1. In-place swapping of two numbers
1 p, q = 20, 40
print(p, q)
2 p, q = q, p
3 print(p, q)
4
Output:
1 20 40
2 40 20

2. Reversing a String in Python


1 x = "MindmajixTraining"
2 print( "Reverse is" , x[: : -1]
Output:
1 Reverse is gniniarTxijamdniM

3. Create a single string from all the elements in the list


1 x = ["Mindmajix", "Online", "Training"]
2 print(" ".join(x))
Output:
1 Mindmajix Online Training

4. Use of Enums in Python


1 class Training:
2 Mindmajix, Online, Mindmajix = range(3)
3    
4 print(MyName.Mindmajix)
5 print(MyName.Online)
print(MyName.Mindmajix)
6
Output:
1 2
2 1
3 2

5. Return multiple values from functions


1 def a():
2 return 4, 5, 6, 7
3 p, q, r, s = a() 
4 print(p, q, r, s)
Output:
1 4, 5, 6, 7

6. Print String N times


1 n = 3
2 x = "Mindmajix";
3 print(a * n)
Output:
1 MindmajixMindmajixMindmajix

7. Check the memory usage of  an object


1 import sys
2 x = 10
3 print(sys.getsizeof(x))
Output:
1  

8. Find the most frequent value in a list


1 test = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9]
2 print(max(set(test), key = test.count))
Output:
1 9

9. Checking whether the two words are anagrams or not


1 from collections import Counter
2 def is_anagram(str1, str2):
3 return Counter(str1) == Counter(str2)
4 print(is_anagram('majix', 'magic')) 
print(is_anagram('majix', 'xijam'))
5
Output:
False
True

10. Print the file path of imported modules


1 import os;
2 import socket;
3 print(os)
4 print(socket)
Output:
1 <module 'os' from '/usr/lib/python3.5/os.py'>
2 <module 'socket' from '/usr/lib/python3.5/socket.py'>
 

You might also like