Python Interview Questions With Answers
Python Interview Questions With Answers
list() – This function is used to convert any data type to a list type.
10) What are local variables and global variables in Python? Explain
with an example.
Global Variables:
Variables declared outside a function or in global space are called global
variables. These variables can be accessed by any function in the program.
Local Variables:
Example:
a = 2
def add():
b = 3
c = a+b
print(c)
add()
Output: 5
When you try to access the local variable outside the function add(), it will
throw an error.
Example:
a = lambda x, y : x+y
print(a(5, 6))
Output: 11
Ans:
break: Allows loop termination when some condition is met and the control is
transferred to the next statement.
continue: Allows skipping some part of a loop when some specific condition is
met and the control is transferred to the beginning of the loop
pass: Used when you need some block of code syntactically, but you want to
skip its execution. This is basically a null operation. Nothing happens when this
is executed.
Ans: help() and dir() both functions are accessible from the Python interpreter
and used for viewing a consolidated dump of built-in functions.
help() function: The help() function is used to display the documentation string
and also facilitates you to see the help related to modules, keywords,
attributes, etc.
dir() function: The dir() function is used to display the defined symbols.
The following example contains some keys. Country, Capital & PM. Their
corresponding values are India, Delhi and Modi respectively.
Example:
17) What does this mean: *args, **kwargs? And why would we use it?
Ans: We use *args when we aren’t sure how many arguments are going to be
passed to a function, or if we want to pass a stored list or tuple of arguments to
a function. **kwargs is used when we don’t know how many keyword
arguments will be passed to a function, or it can be used to pass the values of
a dictionary as keyword arguments. The identifiers args and kwargs are a
convention, you could also use *bob and **billy but that would not be wise.
18) Explain split(), sub(), subn() methods of “re” module in Python.
Ans: To modify the strings, Python’s “re” module is providing 3 methods. They
are:
• split() – uses a regex pattern to “split” a given string into a list.
• sub() – finds all substrings where the regex pattern matches and
then replace them with a different string
• subn() – it is similar to sub() and also returns the new string along
with the no. of replacements.
19) How can files be deleted in Python?
Ans: To delete a file in Python, you need to import the OS Module. After that,
you need to use the os.remove() function.
import os
os.remove("xyz.txt")
Output:
array(‘d’, [1.1, 2.1, 3.1, 3.4])
array(‘d’, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])
Output:
4.6
3.1
Ans: Shallow copy is used when a new instance type gets created and it keeps
the values that are copied in the new instance. Shallow copy is used to copy
the reference pointers just like it copies the values. These references point to
the original objects and the changes made in any member of the class will also
affect the original copy of it. Shallow copy allows faster execution of the
program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy
doesn’t copy the reference pointers to the objects. It makes the reference to an
object and the new object that is pointed by some other object gets stored. The
changes made in the original copy won’t affect any other copy that uses the
object. Deep copy makes execution of the program slower due to making
certain copies for each object that is been called.
Example:
import copy
a = [1,2,3,4,5]
print(a)
b = a # Shallow copy
c = copy.copy(a) # deep copy
b.pop()
print("After pop\n")
print(a)
print(b)
print(c)
Output:
[1, 2, 3, 4, 5]
After pop
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
23) How can you randomize the items of a list in place in Python?
Example:
Output:
['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag'
Ans: Iterators are objects which can be traversed though or iterated upon.
Example:
Output:
List Iteration
python
is
best
Tuple Iteration
python
is
best
String Iteration
Dictionary Iteration
xyz 123
abc 345
Example:
Output:
1
2
3
As another example, below is a generator for Fibonacci Numbers.
def fib(limit):
Output:
0
1
Ans: Python support both Object Oriented and Procedural Programming language as it is a
high level programming language designed for general purpose programming. Python are multi-
paradigm, you can write programs or libraries that are largely procedural, object-oriented, or
functional in all of these languages. It depends on what you mean by functional. Python does have
some features of a functional language.
OOP's concepts like, Classes, Encapsulation, Polymorphism, Inheritance etc.. in Python makes it
as an object oriented programming language.
In Similar way we can created procedural program through python using loops, for, while etc.. and
control structure.
Ans: Python libraries are a collection of Python packages. Some of the majorly
used python libraries are – numpy, scipy, matlpotlib, socket, paramiko etc.,
Output: abc
Output:
XYZ
23
20000
31) Does python support multiple inheritance?
Ans: Multiple inheritance means that a class can be derived from more than one
parent classes. Python does support multiple inheritance.
32) What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. So, for instance, if the
parent class has a method named ABC then the child class also can have a
method with the same name ABC having its own parameters and variables.
Python allows polymorphism.
Example:
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
# instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
Output:
Parrot can fly
Penguin can't fly
33) Define encapsulation in Python?
Ans: Encapsulation means binding the code and the data together. A Python
class in an example of encapsulation.
Example:
class Car:
def __init__(self):
self.__updateSoftware()
def drive(self):
print('driving')
def __updateSoftware(self):
print('updating software')
redcar = Car()
redcar.drive()
#redcar.__updateSoftware() not accesible from object.
Output:
hi
37) Decorators in Python
Decorators are very powerful and useful tool in Python since it allows
programmers to modify the behavior of function or class. Decorators allow us
to wrap another function in order to extend the behavior of wrapped function,
without permanently modifying it.
In Decorators, functions are taken as the argument into another function and
then called inside the wrapper function.
Example:
Function decorator
# defining a decorator
def hello_decorator(func):
# inner1 is a Wrapper function in
# which the argument is called
# inner function can access the outer local
# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")
# calling the actual function now
# inside the wrapper function.
func()
print("This is after function execution")
return inner1
# defining a function, to be called inside wrapper
def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)
# calling the function
function_to_be_used()
Output:
Output:
Inside decorator
I like python
Class Decorator:
class my_decorator(object):
def __init__(self, f):
print("inside my_decorator.__init__()")
f() # Prove that function definition has completed
def __call__(self):
print("inside my_decorator.__call__()")
@my_decorator
def aFunction():
print("inside aFunction()")
print("Finished decorating aFunction()")
aFunction()
Output:
inside my_decorator.__init__()
inside aFunction()
Finished decorating aFunction()
inside my_decorator.__call__()
Programmatic problems:
1) Write a program to accept inputs from command line and use them in the script.
2) Write a program to read a log/text file and find out whether particular keyword is present or
not.
3) Write a program to run other programming language executable from Python script.
4) Write a script to automate camera feature testing on mobile device.